http://stackoverflow.com/comment/89407929
has text: @StephenMoss its unclear what exactly you are trying to accomplish. If you just want to change the title of the potion that is added the PotTitle without any of the string stuff will accomplish what you want.
type: Comment
comment on: http://stackoverflow.com/a/51213360
score: 0
type: AnswerComment

http://stackoverflow.com/a/51342101
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/51281779
score: 1
upvote count: 1
has body: I tried a slightly different approach. Have a look at the code below. Note: The kernel sizes of each filter used for blurring and morphological operations are parameters that you can tune to get better results. My approach is written to give you some direction. Also I recommend to visualize every step using cv2.imshow() to get a better idea of what is going on. Code: im = cv2.imread('80nm.tif') imgray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY) #--- Bilateral filtering --- blur = cv2.bilateralFilter(imgray, 6, 15, 15) #--- Perform Otsu threshold --- ret, otsu_th = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU) Next I used some steps from Watershed implementation of OpenCV #--- noise removal --- kernel = np.ones((3, 3), np.uint8) opening = cv2.morphologyEx(otsu_th, cv2.MORPH_OPEN, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3)), iterations = 2) #--- sure background area --- sure_bg = cv2.dilate(opening, kernel, iterations = 1) cv2.imshow('sure_bg', sure_bg) #--- Finding sure foreground area --- dist_transform = cv2.distanceTransform(opening, cv2.DIST_L2, 5) ret, sure_fg = cv2.threshold(dist_transform, 0.1 * dist_transform.max(), 255, 0) cv2.normalize(dist_transform, dist_transform, 0, 1, cv2.NORM_MINMAX, dtype=cv2.CV_32F) #cv2.imshow('dist_transform_normalized', dist_transform) #cv2.imshow('sure_fg', sure_fg) #--- Finding unknown region --- sure_fg = np.uint8(sure_fg) unknown = cv2.subtract(opening, sure_fg) cv2.imshow('unknown', unknown)
has comment: http://stackoverflow.com/comment/89808683
has comment: http://stackoverflow.com/comment/89817570
has comment: http://stackoverflow.com/comment/89817536
answers question: http://stackoverflow.com/q/51281779
type: AcceptedAnswer

http://stackoverflow.com/comment/89428824
has text: Show us what you tried, show us the data, etc. Give us something to work with.
type: QuestionComment
comment on: http://stackoverflow.com/q/51224225
score: 0
type: Comment

http://stackoverflow.com/comment/89537271
score: 0
has text: Can you add more sample data?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51279903

python-3.x
tags question: http://stackoverflow.com/q/51237008
tags question: http://stackoverflow.com/q/51207382
tags question: http://stackoverflow.com/q/51249310
tags question: http://stackoverflow.com/q/51248178
tags question: http://stackoverflow.com/q/51199256
tags question: http://stackoverflow.com/q/51291906
tags question: http://stackoverflow.com/q/51228764
tags question: http://stackoverflow.com/q/51205328
tags question: http://stackoverflow.com/q/51245754
tags question: http://stackoverflow.com/q/51271980
tags question: http://stackoverflow.com/q/51183238
tags question: http://stackoverflow.com/q/51323692
tags question: http://stackoverflow.com/q/51324166
tags question: http://stackoverflow.com/q/51205985
tags question: http://stackoverflow.com/q/51193213
tags question: http://stackoverflow.com/q/51179446
tags question: http://stackoverflow.com/q/51179556
tags question: http://stackoverflow.com/q/51171989
tags question: http://stackoverflow.com/q/51312031
tags question: http://stackoverflow.com/q/51249786
tags question: http://stackoverflow.com/q/51233335
tags question: http://stackoverflow.com/q/51222803
tags question: http://stackoverflow.com/q/51313895
tags question: http://stackoverflow.com/q/51292523
tags question: http://stackoverflow.com/q/51223727
tags question: http://stackoverflow.com/q/51180858
tags question: http://stackoverflow.com/q/51277119
tags question: http://stackoverflow.com/q/51176661
tags question: http://stackoverflow.com/q/51220161
tags question: http://stackoverflow.com/q/51252120
tags question: http://stackoverflow.com/q/51285457
tags question: http://stackoverflow.com/q/51262857
tags question: http://stackoverflow.com/q/51181765
tags question: http://stackoverflow.com/q/51283361
tags question: http://stackoverflow.com/q/51300364
tags question: http://stackoverflow.com/q/51230046
tags question: http://stackoverflow.com/q/51321811
tags question: http://stackoverflow.com/q/51305509
tags question: http://stackoverflow.com/q/51277530
tags question: http://stackoverflow.com/q/51205868
tags question: http://stackoverflow.com/q/51255922
tags question: http://stackoverflow.com/q/51250600
tags question: http://stackoverflow.com/q/51199056
tags question: http://stackoverflow.com/q/51199403
tags question: http://stackoverflow.com/q/51243297
tags question: http://stackoverflow.com/q/51319407
tags question: http://stackoverflow.com/q/51182812
tags question: http://stackoverflow.com/q/51245121
tags question: http://stackoverflow.com/q/51298298
tags question: http://stackoverflow.com/q/51187664
tags question: http://stackoverflow.com/q/51198746
tags question: http://stackoverflow.com/q/51241829
tags question: http://stackoverflow.com/q/51196930
tags question: http://stackoverflow.com/q/51215552
tags question: http://stackoverflow.com/q/51189327
tags question: http://stackoverflow.com/q/51206400
tags question: http://stackoverflow.com/q/51208644
tags question: http://stackoverflow.com/q/51250197
tags question: http://stackoverflow.com/q/51275839
tags question: http://stackoverflow.com/q/51199660
tags question: http://stackoverflow.com/q/51257808
tags question: http://stackoverflow.com/q/51258627
tags question: http://stackoverflow.com/q/51220732
tags question: http://stackoverflow.com/q/51289741
tags question: http://stackoverflow.com/q/51192207
tags question: http://stackoverflow.com/q/51228047
tags question: http://stackoverflow.com/q/51295266
tags question: http://stackoverflow.com/q/51170549
tags question: http://stackoverflow.com/q/51230377
tags question: http://stackoverflow.com/q/51302487
tags question: http://stackoverflow.com/q/51263167
tags question: http://stackoverflow.com/q/51274999
tags question: http://stackoverflow.com/q/51239168
tags question: http://stackoverflow.com/q/51183280
tags question: http://stackoverflow.com/q/51261968
tags question: http://stackoverflow.com/q/51188180
tags question: http://stackoverflow.com/q/51308352
tags question: http://stackoverflow.com/q/51309033
tags question: http://stackoverflow.com/q/51317953
tags question: http://stackoverflow.com/q/51196977

http://stackoverflow.com/q/51268587
type: AnsweredQuestion
score: -1
has body: I keep getting a error with a SQL query that is written in python. Here is the code in question: else: else_query = "SELECT count(*) FROM PARKING_SPOTS WHERE OCCUPANCY = %s" cursor.execute(else_query, (occupancy,) " AND WHERE LOCATION = %s", (location,)) Here's the error message: File "exp1", line 116 " AND WHERE LOCATION = %s", (location,)) ^ SyntaxError: invalid syntax Can anyone spot the error ? I've changed things around several times, including containing part of the SQL query in a variable, yet I receive the same error.
type: Question
downvote count: 2
accepted answer: http://stackoverflow.com/a/51268693
upvote count: 1
tagged with: sql
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/89515405
has answer: http://stackoverflow.com/a/51268693
has title: MySQL/Python Syntax Error
tagged with: python
tagged with: mysql

http://stackoverflow.com/a/60888441
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51266880
downvote count: 0
answers question: http://stackoverflow.com/q/51266880
type: Answer
score: 5
upvote count: 5
has comment: http://stackoverflow.com/comment/139475228
has body: After some testing, it looks like you can detect Conda usage with the CONDA_DEFAULT_ENV and CONDA_PREFIX environment variables. These only appear to be set when a Conda environment is active. I will try to get an "official" answer from the Conda team and update.

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

http://stackoverflow.com/q/51192595
type: Question
has answer: http://stackoverflow.com/a/51206890
tagged with: assertion
downvote count: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/51206890
favorite count: 0
tagged with: arguments
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/89366769
type: AnsweredQuestion
has body: I'm porting over an existing script, that works perfectly on my coworkers computer that gets an .elf file in the arguments and generates a .vbf from it. It boggles my mind because all other scripts ran fine on my computer. I run it with python 2.7.15. vbf_builder_1_21_2.py --asw D:\tmp\FC8R009T4D3-20180523-182234.elf Traceback (most recent call last): File "D:/Bence/Python/Ford/pupp_package/Ford_FC8_VBFbuilder/vbf_builder_1_21_2.py", line 1296, in &lt;module&gt; CustomerBuildScript().print_step("Get environment information") File "D:/Bence/Python/Ford/pupp_package/Ford_FC8_VBFbuilder/vbf_builder_1_21_2.py", line 482, in __init__ self.initialize() File "D:\Bence\Python\Ford\pupp_package\Ford_FC8_VBFbuilder\BuildScriptBase.py", line 26, in initialize self.parseArguments() File "D:\Bence\Python\Ford\pupp_package\Ford_FC8_VBFbuilder\BuildScriptBase.py", line 80, in parseArguments self.args = parser.parse_args() File "C:\Python27\lib\argparse.py", line 1701, in parse_args args, argv = self.parse_known_args(args, namespace) File "C:\Python27\lib\argparse.py", line 1733, in parse_known_args namespace, args = self._parse_known_args(args, namespace) File "C:\Python27\lib\argparse.py", line 1957, in _parse_known_args self.error(_('argument %s is required') % name) File "C:\Python27\lib\argparse.py", line 2373, in error self.print_usage(_sys.stderr) File "C:\Python27\lib\argparse.py", line 2335, in print_usage self._print_message(self.format_usage(), file) File "C:\Python27\lib\argparse.py", line 2291, in format_usage return formatter.format_help() File "C:\Python27\lib\argparse.py", line 281, in format_help help = self._root_section.format_help() File "C:\Python27\lib\argparse.py", line 211, in format_help func(*args) File "C:\Python27\lib\argparse.py", line 332, in _format_usage assert ' '.join(opt_parts) == opt_usage AssertionError Process finished with exit code 1 I have read that the error occurs usually when there's a long code that gets chopped up and it contains square…
score: 1
has title: Python Assertion error during argument parsing

http://stackoverflow.com/a/51255330
has body: $keywords = preg_split("/[\s,.]+(?![^[]*])/", "Yes, it was great. [I have no ideas how great it was.]"); print_r($keywords);
has comment: http://stackoverflow.com/comment/89489577
answers question: http://stackoverflow.com/q/51255230
downvote count: 0
type: Answer
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/89489824

http://stackoverflow.com/comment/89604773
score: 0
type: AnswerComment
has text: Thanks, man. I got my error and solution.
type: Comment
comment on: http://stackoverflow.com/a/51313497

http://stackoverflow.com/a/51287369
has body: Scipy integrate.quad doesn't seem to support vector output. If you loop over all your values of w and only give one of them at a time as args your code seems to work fine. Also it doesn't handle complex integration, which you can get around using the procedure outlined in this answer.
answers question: http://stackoverflow.com/q/51286830
type: Answer
accepted answer of: http://stackoverflow.com/q/51286830
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer

http://stackoverflow.com/q/51241068
duplicate of: http://stackoverflow.com/q/22922584
has comment: http://stackoverflow.com/comment/89473422
tagged with: python
accepted answer: http://stackoverflow.com/a/51247799
favorite count: 0
has comment: http://stackoverflow.com/comment/89473404
tagged with: python-3.x
linked to: http://stackoverflow.com/q/42190783
tagged with: hdf5
answer count: 1
has comment: http://stackoverflow.com/comment/89474563
upvote count: 3
has body: I am having a hdf5 file with several keys. I want to update the values of all the keys after doing some adjustment. How to do that? Here is my code: hf=h5py.File(fileName,"r+") keys=hf.keys() for i in keys: df=hf[i].value df=df-np.mean(df) hf.close() But then when I read this file in "r" mode, it shows still the same mean which means it hasn't updated. Any idea where it might be going wrong? The above issue is fixed in the answer provided. However, I am now trying to calibrate the resultant data. The code which I am using is: data = hf[key][...] hf[key][...] = data*calibration_factor Just for the simple calibration. However, its resulting to all zeroes in hf[key][...]. Any possible solution for this? I am struggling a lot on this,thanks for understanding.
has title: updating a key value in hdf5 using python and h5py
downvote count: 0
linked to: http://stackoverflow.com/q/22922584
has answer: http://stackoverflow.com/a/51247799
has comment: http://stackoverflow.com/comment/89472942
linked to: http://stackoverflow.com/q/20928136
type: Question
tagged with: h5py
type: AnsweredQuestion
score: 3

http://stackoverflow.com/q/51193392
answer count: 0
linked to: http://stackoverflow.com/q/20109391
type: UnansweredQuestion
has title: Calculating a new value based on other relative values for each row
type: Question
has comment: http://stackoverflow.com/comment/89413795
has comment: http://stackoverflow.com/comment/89403030
tagged with: python-2.7
score: 0
tagged with: function
has body: Getting an employees experience with a task, relative to the time they completed a previous task df=pd.read_csv("C:Tasks_Revised_For_Analysis.csv") Print(df['AssignedTo'], df['TaskType'], df['DaysExperienceWithTask'], Out[15]: Vaughn Informatica 7 kodams Spotfire 8 sreddy python 2 Vaughn informatica 4 kodams java 5 Vaughn Python 9 This is what I would like to get back: Out[15]: Vaughn Informatica 11 Vaughn Python 9 kodams Spotfire 8 kodams java 5 sreddy python 2 I need to get a users amount of experience with a each certain task type. This is all I could come up with when trying to solve this problem: def RelativeTaskTypeExp (UsernameIn, TechIn, DateIn): usertasks = {all} where user = UsernameIn usertechtasks = {usertask} where tech = TechIn usertechpasttasks = {usertechtasks} where middledate &lt; DateIn return usertechpasttasks.count() all Final.apply(lambda row: RelativeTaskTypeExp(row['AssignedTo'], row['TaskType'], row['EmployeeStartDate'], row['TaskEndDate'])) Any help is greatly appreciated, Thank you very much.
tagged with: datetime
tagged with: python
tagged with: lambda
linked to: http://stackoverflow.com/q/51216338

http://stackoverflow.com/a/51187893
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/51187709
upvote count: 1
has body: You can also do it with python's datetime module: from datetime import datetime data['ym'] = data['ym'].apply(lambda x: datetime.strptime(str(x), format='%Y%m'))
score: 1

http://stackoverflow.com/comment/89506699
type: Comment
comment on: http://stackoverflow.com/a/51264305
has text: @fireandwind - If need something more complicted, can you explain more?
score: 0
type: AnswerComment

http://stackoverflow.com/q/51234072
has comment: http://stackoverflow.com/comment/89447235
type: Question
has title: Find the previous number in a list of float and integer
answer count: 2
has comment: http://stackoverflow.com/comment/89447199
linked to: http://stackoverflow.com/q/49149955
downvote count: 0
possible better answer: http://stackoverflow.com/a/51234122
has answer: http://stackoverflow.com/a/51234122
accepted answer: http://stackoverflow.com/a/51234129
favorite count: 0
has body: i have a list of float and integers like below [2,4.635,9,18,27.548,36] For a given input i want to find the previous number of that input in the list by comparing that number with the numbers in list For example: if i give 8.9 as input i should get 4.635 as the output, is there any builtin function for this
upvote count: 2
tagged with: python
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89447354
has answer: http://stackoverflow.com/a/51234129

http://stackoverflow.com/comment/89419856
type: AnswerComment
comment on: http://stackoverflow.com/a/51217429
type: Comment
has text: @TMueller83 The `export` wasn't supposed to be there. Could you try it again? If it doesn't work, please be more specific about how it fails (does it still show the message? does it do nothing? what?)
score: 0

http://stackoverflow.com/comment/100008911
comment on: http://stackoverflow.com/a/51230724
has text: PyCrypto is forcing you to share your private key, to make your program more secure!
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/51255018
type: Answer
has body: I was able to hack this together with linear indexing...it gets the right result but performs rather slowly on large arrays. A = np.array([[4, 0, 0], [1, 2, 3], [0, 0, 5]]).astype(float) r = np.array([2, 0, -1]) rows, column_indices = np.ogrid[:A.shape[0], :A.shape[1]] # Use always a negative shift, so that column_indices are valid. # (could also use module operation) r_old = r.copy() r[r &lt; 0] += A.shape[1] column_indices = column_indices - r[:,np.newaxis] result = A[rows, column_indices] # replace with NaNs row_length = result.shape[-1] pad_inds = [] for ind,i in np.enumerate(r_old): if i &gt; 0: inds2pad = [np.ravel_multi_index((ind,) + (j,),result.shape) for j in range(i)] pad_inds.extend(inds2pad) if i &lt; 0: inds2pad = [np.ravel_multi_index((ind,) + (j,),result.shape) for j in range(row_length+i,row_length)] pad_inds.extend(inds2pad) result.ravel()[pad_inds] = nan Gives the expected result: print result [[ nan nan 4.] [ 1. 2. 3.] [ 0. 5. nan]]
answers question: http://stackoverflow.com/q/51200369
score: 0

http://stackoverflow.com/a/51304983
answers question: http://stackoverflow.com/q/51302719
score: 0
type: AcceptedAnswer
type: Answer
has body: Looks xpath which used is not correct. Its good to cross check xpath in browser console. xpath provided in above answer @DebanjanB is good. try once: in chrome->F12->Console: paste below one and Enter. $x("//ul[@class='pagination']//li[last()]/a/small") It has to fetch required element. Similarly try all xpaths which you used in posted question, they are fetching wrong elements which leads to exceptions on execution.
accepted answer of: http://stackoverflow.com/q/51302719

tensorflow
tags question: http://stackoverflow.com/q/51228372
tags question: http://stackoverflow.com/q/51263420
tags question: http://stackoverflow.com/q/51292212
tags question: http://stackoverflow.com/q/51231608
tags question: http://stackoverflow.com/q/51210152
tags question: http://stackoverflow.com/q/51261501
tags question: http://stackoverflow.com/q/51235868
tags question: http://stackoverflow.com/q/51287790
tags question: http://stackoverflow.com/q/51229932
tags question: http://stackoverflow.com/q/51268579
tags question: http://stackoverflow.com/q/51179084
tags question: http://stackoverflow.com/q/51217981
tags question: http://stackoverflow.com/q/51321840
tags question: http://stackoverflow.com/q/51228131
tags question: http://stackoverflow.com/q/51175117
tags question: http://stackoverflow.com/q/51208792
tags question: http://stackoverflow.com/q/51232687
tags question: http://stackoverflow.com/q/51229572
tags question: http://stackoverflow.com/q/51193305
tags question: http://stackoverflow.com/q/51212806
tags question: http://stackoverflow.com/q/51291804
tags question: http://stackoverflow.com/q/51290691
tags question: http://stackoverflow.com/q/51244190
tags question: http://stackoverflow.com/q/51181050
tags question: http://stackoverflow.com/q/51265809
tags question: http://stackoverflow.com/q/51277866
tags question: http://stackoverflow.com/q/51281913
tags question: http://stackoverflow.com/q/51223320
tags question: http://stackoverflow.com/q/51264291
tags question: http://stackoverflow.com/q/51210536
tags question: http://stackoverflow.com/q/51318880
tags question: http://stackoverflow.com/q/51260992
tags question: http://stackoverflow.com/q/51272424
tags question: http://stackoverflow.com/q/51195348
tags question: http://stackoverflow.com/q/51186330
tags question: http://stackoverflow.com/q/51216221
tags question: http://stackoverflow.com/q/51225848
tags question: http://stackoverflow.com/q/51295015
tags question: http://stackoverflow.com/q/51320469
tags question: http://stackoverflow.com/q/51294885
tags question: http://stackoverflow.com/q/51230690
tags question: http://stackoverflow.com/q/51237606
tags question: http://stackoverflow.com/q/51233023
tags question: http://stackoverflow.com/q/51183023
tags question: http://stackoverflow.com/q/51178041
tags question: http://stackoverflow.com/q/51214473
tags question: http://stackoverflow.com/q/51220714
tags question: http://stackoverflow.com/q/51248813
tags question: http://stackoverflow.com/q/51199753
tags question: http://stackoverflow.com/q/51230474
tags question: http://stackoverflow.com/q/51289280
tags question: http://stackoverflow.com/q/51277748
tags question: http://stackoverflow.com/q/51287109
tags question: http://stackoverflow.com/q/51248442
tags question: http://stackoverflow.com/q/51211443
tags question: http://stackoverflow.com/q/51241520
tags question: http://stackoverflow.com/q/51309643
tags question: http://stackoverflow.com/q/51306862
tags question: http://stackoverflow.com/q/51190653
tags question: http://stackoverflow.com/q/51265030
tags question: http://stackoverflow.com/q/51214255
tags question: http://stackoverflow.com/q/51320167
tags question: http://stackoverflow.com/q/51271790
tags question: http://stackoverflow.com/q/51187571
tags question: http://stackoverflow.com/q/51212160
tags question: http://stackoverflow.com/q/51212755
tags question: http://stackoverflow.com/q/51261257
tags question: http://stackoverflow.com/q/51297972
tags question: http://stackoverflow.com/q/51269683
tags question: http://stackoverflow.com/q/51221525
tags question: http://stackoverflow.com/q/51288802
tags question: http://stackoverflow.com/q/51256365
tags question: http://stackoverflow.com/q/51195017
tags question: http://stackoverflow.com/q/51193952
tags question: http://stackoverflow.com/q/51178132
tags question: http://stackoverflow.com/q/51308607
tags question: http://stackoverflow.com/q/51268901
tags question: http://stackoverflow.com/q/51273739
tags question: http://stackoverflow.com/q/51297992
tags question: http://stackoverflow.com/q/51294410

http://stackoverflow.com/comment/89383153
score: 1
type: QuestionComment
has text: Sounds like you need a class. Show us a [mcve] and we'll go from there.
type: Comment
comment on: http://stackoverflow.com/q/51200744

http://stackoverflow.com/a/51222131
upvote count: 1
answers question: http://stackoverflow.com/q/51221069
type: Answer
downvote count: 0
score: 1
has body: The variables a and b in class A are like static variables that are associated to the class and not to the object. To run your code here is the solution : class A: a=10 b=20 class B(A): print(A.b) d=30 s=d+A.a print(s) But to understand it clearly look at the example below carefully: class A: print("IN CLASS A.") a = 10 b = 20 def __init__(self): print("A's Constructor.") self.x1 = 10 self.x2 = 20 print("Before making A's object") a1 = A() print("Attributes of class A:", A.__dict__) print("Attributes of object:", a1.__dict__) a1.a = 40 print("Attributes of class A:", A.__dict__) print("Attributes of object:", a1.__dict__) class B(A): print("INSIDE CLASS B.") print(A.b) d = 30 s = d + A.a print(s) def __init__(self): super().__init__() print("B's Constructor.") self.x3 = self.x1 + self.x2 print(self.x3) print("Before making B's object") b1 = B() Output : IN CLASS A. Before making A's object A's Constructor. Attributes of class A: {'__module__': '__main__', 'a': 10, 'b': 20, '__init__': &lt;function A.__init__ at 0x0000028FFC2F9158&gt;, '__dict__': &lt;attribute '__dict__' of 'A' objects&gt;, '__weakref__': &lt;attribute '__weakref__' of 'A' objects&gt;, '__doc__': None} Attributes of object: {'x1': 10, 'x2': 20} Attributes of class A: {'__module__': '__main__', 'a': 10, 'b': 20, '__init__': &lt;function A.__init__ at 0x0000028FFC2F9158&gt;, '__dict__': &lt;attribute '__dict__' of 'A' objects&gt;, '__weakref__': &lt;attribute '__weakref__' of 'A' objects&gt;, '__doc__': None} Attributes of object: {'x1': 10, 'x2': 20, 'a': 40} INSIDE CLASS B. 20 40 Before making B's object A's Constructor. B's Constructor. 30 Comment if you want to understand something.

http://stackoverflow.com/comment/89615958
comment on: http://stackoverflow.com/a/51291533
score: 0
type: AnswerComment
has text: @JeffreyChiu Note that doing multiprocessing will not preserve the order.
type: Comment

http://stackoverflow.com/comment/120747362
comment on: http://stackoverflow.com/a/55481248
score: 1
has text: @iroln Thanks for your comment. I am still not able to solve the problem. In the documentation there is no code or example for multivariate case (there's just a figure!). Changing `import csaps` to `from csaps import csaps` also did not help.
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/89612472
type: Comment
comment on: http://stackoverflow.com/a/51263440
has text: Edited the answer according to question editions. I think this is what you looked for. Check it.
type: AnswerComment
score: 0

http://stackoverflow.com/q/51262561
answer count: 1
downvote count: 0
tagged with: button
favorite count: 0
accepted answer: http://stackoverflow.com/a/51262778
tagged with: python
tagged with: tkinter
score: 1
upvote count: 1
has title: Tkinter Button States
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51262778
has body: I'm writing a program that switches on a series of LEDs. When the code is executed, it opens a GUI that has a series of buttons. When the Raspberry Pi is connected to the GPIO board, 1 LED switches on and then switches off. I'm trying to introduce a state system for the buttons stating that when a button is pressed, this happens and when its pressed again it switches off. I tried to implement something in my 'if statement' but I'm not sure about how to actually implement it. for example if buttonPressed == true (led on code) buttonPressed (pressed again) (led off code) This is my code so far b1 = Button(self, text ="io_1", command = self.send_signal) b1.config(height = 1, width = 10) b1.place(x =80, y = 150) b2 = Button(self, text ="io_2", command = self.send_signal) b2.config(height = 1, width = 10) b2.place(x =160, y = 150) These are the buttons. I've already done the screen initialtition like root = tk(). def send_signal(self): #This is the function for the funtionality for the button print("sending Signal") try: ledState = False if ledState == False: GPIO.output(LEDPin, True) print("LED ON") ledState = True sleep(1) elif ledState == True: GPIO.output(LEDPin, False) print("LED OFF") ledState = False sleep(0.5) The code above is the code for the buttons.
type: Question

http://stackoverflow.com/a/51306736
type: AcceptedAnswer
type: Answer
score: 2
downvote count: 0
has body: One note on terminology first so the rest of this example is clear--np.any(arr) is a function; arr.any() is technically an instance method. Generally, the top-level np.&lt;function&gt;(arr) functions are wrappers around the methods for arr. Here's the source for np.any(), NumPy version 1.14.5, from numpy.core.fromnumeric: def any(a, axis=None, out=None, keepdims=np._NoValue): arr = asanyarray(a) kwargs = {} if keepdims is not np._NoValue: kwargs['keepdims'] = keepdims return arr.any(axis=axis, out=out, **kwargs) Other versions of NumPy (such as the one currently on GitHub) may use a "wrapper factory function" that does virtually the same thing. See also this Q/A for a similar example with np.transpose(). Generally what it boils down to is np.&lt;function&gt;(arr) becomes some form of getattr(arr, &lt;function&gt;), at least for the stuff in fromnumeric.py. In terms of a comparison--you're talking about an incremental amount of additional overhead when using the top-level function, but that comes with some added flexibility: for instance, there's a call to np.asanyarray(a), which means you could pass a Python list as a to the function. On my computer, the call to np.asanyarray(arr) takes 1/8 the time of arr.any(), so to inject a bit of opinion into the answer, choosing between the two is probably not the first place to look in terms of performance optimization.
accepted answer of: http://stackoverflow.com/q/51306501
upvote count: 2
answers question: http://stackoverflow.com/q/51306501

http://stackoverflow.com/q/51243905
has answer: http://stackoverflow.com/a/56526990
tagged with: python
upvote count: 2
type: UnansweredQuestion
type: Question
tagged with: xampp
has body: I am trying to execute this code: #!C:\python-3.7.0-embed-amd64\python.exe print('Content-type: text/html\r\n') print('\r\n') print('Hello, World!') and I got this error: Server error! The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there was an error in a CGI script. If you think this is a server error, please contact the webmaster. Error 500 localhost Apache/2.4.33 (Win32) OpenSSL/1.1.0h PHP/7.2.6 What could be causing this problem?
linked to: http://stackoverflow.com/q/42704846
score: 2
downvote count: 0
answer count: 1
tagged with: http-status-code-500
favorite count: 0
has title: Server error 500 when executing simple "Hello, world" in Python XAMPP

http://stackoverflow.com/q/51299997
has body: Code: def histogram(value_array,xlabel): mu, sigma = np.mean(value_array), np.std(value_array) n, bins, patches = plt.hist(value_array, 50, normed=1, facecolor='blue',histtype = "bar", alpha=0.75) # add a 'best fit' line y = mlab.normpdf( bins, mu, sigma) l = plt.plot(bins, y, linewidth=1) plt.axis([np.min(value_array), np.max(value_array), np.min(y),np.max(y)]) plt.grid(False) plt.xlabel(xlabel) plt.ylabel("pdf") plt.show() Output: The scale of the values in the x-axis should either be in the middle of the bar or starting point of the bar. I am not able to understand why it is mis aligned like this. Anyone has faced this issue?
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89577421
answer count: 0
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/89583081
type: Question
has title: I am trying to build a histogram in python matplot lib
score: 0

django-models
tag name: django-models
tags question: http://stackoverflow.com/q/51313688
tags question: http://stackoverflow.com/q/51214539
tags question: http://stackoverflow.com/q/51244581
tags question: http://stackoverflow.com/q/51210717
tags question: http://stackoverflow.com/q/51214079
tags question: http://stackoverflow.com/q/51191679
tags question: http://stackoverflow.com/q/51279151
tags question: http://stackoverflow.com/q/51249797
tags question: http://stackoverflow.com/q/51220853
tags question: http://stackoverflow.com/q/51223988
tags question: http://stackoverflow.com/q/51191820
tags question: http://stackoverflow.com/q/51172820
tags question: http://stackoverflow.com/q/51278329
tags question: http://stackoverflow.com/q/51187108
tags question: http://stackoverflow.com/q/51185022
tags question: http://stackoverflow.com/q/51217007
tags question: http://stackoverflow.com/q/51288186
tags question: http://stackoverflow.com/q/51231538
tags question: http://stackoverflow.com/q/51292546
type: Tag
tags question: http://stackoverflow.com/q/51273509
tags question: http://stackoverflow.com/q/51262015
tags question: http://stackoverflow.com/q/51254536
tags question: http://stackoverflow.com/q/51227077
tags question: http://stackoverflow.com/q/51205137
tags question: http://stackoverflow.com/q/51212695
tags question: http://stackoverflow.com/q/51278016
tags question: http://stackoverflow.com/q/51270719
tags question: http://stackoverflow.com/q/51263040
tags question: http://stackoverflow.com/q/51210970
tags question: http://stackoverflow.com/q/51248109
tags question: http://stackoverflow.com/q/51240287
tags question: http://stackoverflow.com/q/51260225
tags question: http://stackoverflow.com/q/51181810
tags question: http://stackoverflow.com/q/51186198
tags question: http://stackoverflow.com/q/51202612

http://stackoverflow.com/comment/89437141
type: QuestionComment
has text: Take a look here: https://stackoverflow.com/questions/38045324/how-to-encrypt-data-with-rsa-private-key-in-python
type: Comment
comment on: http://stackoverflow.com/q/51228645
score: 0

http://stackoverflow.com/a/51239587
has comment: http://stackoverflow.com/comment/138411286
has comment: http://stackoverflow.com/comment/129067232
has comment: http://stackoverflow.com/comment/89488016
type: AcceptedAnswer
downvote count: 0
score: 50
has comment: http://stackoverflow.com/comment/129067112
type: Answer
has comment: http://stackoverflow.com/comment/138405697
has comment: http://stackoverflow.com/comment/129086474
has body: I want to know how it works internally. as_completed sets up a callback to fire when the future is done, doing so for all the futures it receives. (It uses an internal API equivalent to add_done_callback for this purpose.) When any of the futures completes, as_completed is notified by its callback being run. The callback runs in whatever thread it was that completed the future, so it only sets an event, which is shared by all callbacks, and which as_completed sleeps on. Once woken up by the event, as_completed immediately yields the finished future. This is how as_completed ensures that futures are yielded as they are completed, regardless of the order in which that happens. After yielding, the event is cleared and the waiting is repeated until all the futures are done. Is it yielding completed tasks (futures) immediately? Yes, that follows from both the documented interface and the implementation.
accepted answer of: http://stackoverflow.com/q/51239251
answers question: http://stackoverflow.com/q/51239251
upvote count: 50
has comment: http://stackoverflow.com/comment/129081132

http://stackoverflow.com/q/51318367
has body: Do you know if models from scikit-learn use automatically multithreading or just sequential instructions? Thanks
downvote count: 4
accepted answer: http://stackoverflow.com/a/51323654
type: AnsweredQuestion
tagged with: scikit-learn
favorite count: 0
tagged with: python-3.x
score: 12
type: Question
tagged with: multithreading
tagged with: python
answer count: 1
upvote count: 16
has title: Scikit-learn multithreading
has answer: http://stackoverflow.com/a/51323654

http://stackoverflow.com/a/51315108
has body: Use the splat operator in a comprehension to produce your dataframe: pd.DataFrame([k, *v] for k, v in d.items()) 0 1 2 0 a 1 2 1 b 3 4 2 c 5 6 If you don't mind having index as one of your column names, simply transpose and reset_index: pd.DataFrame(d).T.reset_index() index 0 1 0 a 1 2 1 b 3 4 2 c 5 6 Finally, although it's rather ugly, the most performant option I could find on very large dictionaries is the following: pd.DataFrame(list(d.values()), index=list(d.keys())).reset_index()
type: Answer
upvote count: 5
answers question: http://stackoverflow.com/q/51315083
score: 5
downvote count: 0

http://stackoverflow.com/a/67329198
type: Answer
has body: Encountered the same thing, but the answer was surprisingly simple for me: I used VSCode to execute some of the code generating graphs, and the graphs came out too big in Jupyter Notebook, although I specified figsize (16,9). Re-ran these in jupyter notebook, and it went just fine.
score: 0
answers question: http://stackoverflow.com/q/51204683

http://stackoverflow.com/comment/89604809
has text: Result for the case above should be [[0, 0, 0, 0, 0, 8],[13, 10, 10, 10, 10, 7]]
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51308337

http://stackoverflow.com/comment/89381881
comment on: http://stackoverflow.com/a/51197732
type: AnswerComment
has text: so I left an important detail out in the problem and added it above. If you can be of anymore help I would be forever grateful. I think your idea is spot on. I failed to share the important detail of the numbers we are looking for in the Department column in df1 are always immediately following a hypen or dash(-)...one of these...and then take that number and match it to department number in df2
score: 0
type: Comment

http://stackoverflow.com/comment/89596054
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/51309108
has text: Looking at the docs, the functions are not related. `replace` seems to relate to `apply`, rather than `map`. The doc also says you can use nested dict, but trying on your example I get 'tuple has no method replace', so that doesn't work either.

http://stackoverflow.com/comment/89388988
comment on: http://stackoverflow.com/a/51199384
score: 0
type: AnswerComment
has text: Looks like the OP had his list reversed (from what we were expecting at least). If `f = f[::-1]` your code should get their intended output (mine did).
type: Comment

http://stackoverflow.com/a/51238477
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89456142
has comment: http://stackoverflow.com/comment/89456006
type: Answer
has body: There's no need to split your DataFrame - because you'd have to calculate the mean individually for each split. Use groupby, and you can do this a lot simpler: n = 24 size = np.ceil(len(df) / n).astype(int) X = df.groupby(df.index % size).mean() If you want the mean for a single column, you can do so: X = df.groupby(df.index % size)['Close'].mean() Or, as a list: X = df.groupby(df.index % size)['Close'].mean().values.tolist()
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51238369
answers question: http://stackoverflow.com/q/51238369
score: 1

python
tags question: http://stackoverflow.com/q/51312408
tags question: http://stackoverflow.com/q/51181327
tags question: http://stackoverflow.com/q/51321062
tags question: http://stackoverflow.com/q/51306330
tags question: http://stackoverflow.com/q/51262535
tags question: http://stackoverflow.com/q/51181798
tags question: http://stackoverflow.com/q/51301035
tags question: http://stackoverflow.com/q/51304689
tags question: http://stackoverflow.com/q/51200155
tags question: http://stackoverflow.com/q/51252687
tags question: http://stackoverflow.com/q/51243666
tags question: http://stackoverflow.com/q/51234440
tags question: http://stackoverflow.com/q/51279181
tags question: http://stackoverflow.com/q/51171042
tags question: http://stackoverflow.com/q/51279294
tags question: http://stackoverflow.com/q/51199137
tags question: http://stackoverflow.com/q/51173079
tags question: http://stackoverflow.com/q/51282011
tags question: http://stackoverflow.com/q/51266232
tags question: http://stackoverflow.com/q/51270683
tags question: http://stackoverflow.com/q/51236149
tags question: http://stackoverflow.com/q/51174691
tags question: http://stackoverflow.com/q/51182300
tags question: http://stackoverflow.com/q/51224454
tags question: http://stackoverflow.com/q/51180234
tags question: http://stackoverflow.com/q/51324089
tags question: http://stackoverflow.com/q/51200982
tags question: http://stackoverflow.com/q/51255274
tags question: http://stackoverflow.com/q/51178459
tags question: http://stackoverflow.com/q/51253164
tags question: http://stackoverflow.com/q/51223025
tags question: http://stackoverflow.com/q/51256630
tags question: http://stackoverflow.com/q/51253878
tags question: http://stackoverflow.com/q/51301206
tags question: http://stackoverflow.com/q/51319189
tags question: http://stackoverflow.com/q/51323494
tags question: http://stackoverflow.com/q/51272405
tags question: http://stackoverflow.com/q/51176690
tags question: http://stackoverflow.com/q/51312194
tags question: http://stackoverflow.com/q/51244937
tags question: http://stackoverflow.com/q/51235622
tags question: http://stackoverflow.com/q/51211758
tags question: http://stackoverflow.com/q/51303649
tags question: http://stackoverflow.com/q/51295378
tags question: http://stackoverflow.com/q/51250674
tags question: http://stackoverflow.com/q/51267097
tags question: http://stackoverflow.com/q/51225370
tags question: http://stackoverflow.com/q/51249014
tags question: http://stackoverflow.com/q/51303361
tags question: http://stackoverflow.com/q/51252030
tags question: http://stackoverflow.com/q/51200674
tags question: http://stackoverflow.com/q/51244419
tags question: http://stackoverflow.com/q/51231535
tags question: http://stackoverflow.com/q/51234876
tags question: http://stackoverflow.com/q/51204241
tags question: http://stackoverflow.com/q/51219981
tags question: http://stackoverflow.com/q/51305486
tags question: http://stackoverflow.com/q/51303424
tags question: http://stackoverflow.com/q/51286589
tags question: http://stackoverflow.com/q/51255533
tags question: http://stackoverflow.com/q/51303537
tags question: http://stackoverflow.com/q/51279247
tags question: http://stackoverflow.com/q/51184305
tags question: http://stackoverflow.com/q/51251355
tags question: http://stackoverflow.com/q/51237008
tags question: http://stackoverflow.com/q/51207382
tags question: http://stackoverflow.com/q/51310139
tags question: http://stackoverflow.com/q/51169162
tags question: http://stackoverflow.com/q/51176843
tags question: http://stackoverflow.com/q/51225624
tags question: http://stackoverflow.com/q/51244200
tags question: http://stackoverflow.com/q/51277748
tags question: http://stackoverflow.com/q/51203884
tags question: http://stackoverflow.com/q/51239425
tags question: http://stackoverflow.com/q/51224245
tags question: http://stackoverflow.com/q/51270199
tags question: http://stackoverflow.com/q/51309446
tags question: http://stackoverflow.com/q/51249310
tags question: http://stackoverflow.com/q/51278119
tags question: http://stackoverflow.com/q/51187459

http://stackoverflow.com/comment/89454165
comment on: http://stackoverflow.com/a/51237625
has text: sorry its `skiprows`. corrected it. Also, most probably your separator is tab, but if it doesn't work then remove the `sep` argument and try again.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/89569483
type: QuestionComment
has text: You donot need call class. i.Jugadores.edad, try change it to i.Jedad. i is already an class object here. Another mistake is lista_jugadores should be a list instead of a string?
score: 0
comment on: http://stackoverflow.com/q/51295960
type: Comment

http://stackoverflow.com/comment/89618165
type: Comment
score: 0
has text: ok, thanks @atline. And a side question (if allowed in comment). Is there any reason why pythonnet, specifically `clr`, would have trouble in 2.7.3 and not in 2.7.15?
comment on: http://stackoverflow.com/q/51320802
type: QuestionComment

http://stackoverflow.com/comment/89621751
type: Comment
score: 1
has text: @Mium what makes you think processes/threads are involved here? OP didn't mention either.
type: QuestionComment
comment on: http://stackoverflow.com/q/51323272

pyqt
type: Tag
tags question: http://stackoverflow.com/q/51179279
tags question: http://stackoverflow.com/q/51306500
tags question: http://stackoverflow.com/q/51220132
tags question: http://stackoverflow.com/q/51284338
tags question: http://stackoverflow.com/q/51323958
tags question: http://stackoverflow.com/q/51238046
tags question: http://stackoverflow.com/q/51237546
tags question: http://stackoverflow.com/q/51271956
tags question: http://stackoverflow.com/q/51295880
tags question: http://stackoverflow.com/q/51308220
tags question: http://stackoverflow.com/q/51267623
tags question: http://stackoverflow.com/q/51189055
tags question: http://stackoverflow.com/q/51273301
tags question: http://stackoverflow.com/q/51210126
tags question: http://stackoverflow.com/q/51219981
tags question: http://stackoverflow.com/q/51245381
tags question: http://stackoverflow.com/q/51233836
tags question: http://stackoverflow.com/q/51233683
tags question: http://stackoverflow.com/q/51222085
tags question: http://stackoverflow.com/q/51196705
tags question: http://stackoverflow.com/q/51309888
tags question: http://stackoverflow.com/q/51215635
tags question: http://stackoverflow.com/q/51251185
tags question: http://stackoverflow.com/q/51308772
tags question: http://stackoverflow.com/q/51314138
tags question: http://stackoverflow.com/q/51220553
tags question: http://stackoverflow.com/q/51250663
tags question: http://stackoverflow.com/q/51286339
tags question: http://stackoverflow.com/q/51169641
tags question: http://stackoverflow.com/q/51306683
tags question: http://stackoverflow.com/q/51272418
tags question: http://stackoverflow.com/q/51223647
tags question: http://stackoverflow.com/q/51306172
tags question: http://stackoverflow.com/q/51208669
tags question: http://stackoverflow.com/q/51288948
tags question: http://stackoverflow.com/q/51175841
tags question: http://stackoverflow.com/q/51221094
tags question: http://stackoverflow.com/q/51219340
tags question: http://stackoverflow.com/q/51173728
tags question: http://stackoverflow.com/q/51203070
tags question: http://stackoverflow.com/q/51230544
tag name: pyqt
tags question: http://stackoverflow.com/q/51264267
tags question: http://stackoverflow.com/q/51257557
tags question: http://stackoverflow.com/q/51217584
tags question: http://stackoverflow.com/q/51229157
tags question: http://stackoverflow.com/q/51298058
tags question: http://stackoverflow.com/q/51170224
tags question: http://stackoverflow.com/q/51169958

http://stackoverflow.com/q/51183661
type: UnansweredQuestion
tagged with: python
score: -1
has body: Following is a model given by a module. If you look inside of it, you can check two definitin of functions are defined in a nested depth. I've never seen this before. How's it working? def load(filepath, shape_only=False): def readpca(f, nv): nc,nd = struct.unpack('&lt;II', f.read(8)) assert(nd == 3*nv) funcs = [[struct.unpack('&lt;d', f.read(8))[0] for d in range(nd)] for c in range(nc)] (nm,) = struct.unpack('&lt;I', f.read(4)) assert(nm == 3*nv) # fyi: elements are ordered x1,y1,z1,x2,y2,z2,...xnv,ynv,znv. vmean = [struct.unpack('&lt;d', f.read(8))[0] for i in range(nm)] (ne,) = struct.unpack('&lt;I', f.read(4)) values = [struct.unpack('&lt;d', f.read(8))[0] for i in range(ne)] return PCAModel(vmean, funcs, values) with open(filepath, 'rb') as f: nv,nt = struct.unpack('&lt;II', f.read(8)) # fyi: faces is a list of tuples (each tuple contains 3 vertex indices). faces = [struct.unpack('&lt;III', f.read(12)) for i in range(nt)] shape = readpca(f, nv) try: textr = None if shape_only else readpca(f, nv) except Exception: print('No texture data. Returning shape-only model.') textr = None return MorphModel(faces, shape, textr)
linked to: http://stackoverflow.com/q/1589058
has answer: http://stackoverflow.com/a/51183753
tagged with: definition
type: Question
has comment: http://stackoverflow.com/comment/89349252
answer count: 1
favorite count: 0
downvote count: 1
tagged with: nested
has title: What is the Syntactical Function of Nested Defintion in Python?
upvote count: 0

http://stackoverflow.com/q/51187318
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89357406
tagged with: python
has answer: http://stackoverflow.com/a/51187485
tagged with: oop
score: 1
has comment: http://stackoverflow.com/comment/89356809
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/89357334
answer count: 2
downvote count: 0
has body: I'm trying to validate one attribute of my class using setter in the code below. The attribute I want to validate is called '__x' and is set to parameter passed on 'init' method. When I change 'self__x' to 'self.x', it's working as I expect. What I want to is how it's working with 'self.x', while I don't return 'x' attribute anywhere in getter and setter methods and why it's not working with 'self.__x'? class P: def __init__(self, x): self.__x = x # not working # self.x = x # working @property def x(self): return self.__x @x.setter def x(self, x): if x &lt; 0: self.__x = 0 else: self.__x = x p = P(-5) print(p.x) # prints -5
has title: Python class attribute validation on __init__
has comment: http://stackoverflow.com/comment/89356521
tagged with: getter-setter
has answer: http://stackoverflow.com/a/51188607
has comment: http://stackoverflow.com/comment/89356692
favorite count: 0
has comment: http://stackoverflow.com/comment/89356662

http://stackoverflow.com/q/51284700
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/56376650
has answer: http://stackoverflow.com/a/51611846
score: 21
has body: I am using PyCharm professional edition 2018.1 I am using remote interpreter via ssh. As a result, when I use shortcuts to Inspect Code (e.g. look at the source of a function I am using in the main script), the tab that opens refers to a file on the remote server /system/remote_resources/.../... This is quite annoying because this is not the file I need to modify, since it is just a temporary copy of the local file and it already happened to me to modify the remote file, which has no effect on the execution. Is there a way for PyCharm code inspection to open the local script, rather than the remote copy? This is how I configure the ssh connection. No path mappings are set.
type: Question
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/56376650
answer count: 3
has title: Pycharm code inspection with remote interpreter
possible better answer: http://stackoverflow.com/a/51557142
tagged with: pycharm
has answer: http://stackoverflow.com/a/51557142
upvote count: 21
has comment: http://stackoverflow.com/comment/90081239
tagged with: python

http://stackoverflow.com/comment/89415560
score: 2
comment on: http://stackoverflow.com/a/51217143
type: Comment
has text: so no need to test for `port`. Shortcut, but that'd work yes (best answer so far if you ask me and coming from a newbie it's nice)
type: AnswerComment

http://stackoverflow.com/comment/89451435
type: Comment
comment on: http://stackoverflow.com/q/51175192
has text: I added a more detailed example with code that can be reproduced.
score: 0
type: QuestionComment

http://stackoverflow.com/comment/89426134
has text: What are you trying to do there?
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51222834

http://stackoverflow.com/comment/89569821
type: QuestionComment
comment on: http://stackoverflow.com/q/51296199
has text: Could you post the code you have so far?
score: 0
type: Comment

http://stackoverflow.com/a/51316104
score: 5
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51316029
type: Answer
upvote count: 6
has body: Because socket.recv is a blocking call. This means that your program will be paused until it receives data. You can set a time limit on how long to wait for data: socket.settimeout(seconds_to_wait_for_data) Or, you can make the socket not block: sock.setblocking(False) Note that under your current implementation, your code will probably busy wait for data to be available, potentially using more system resources than necessary. You can prevent this by: looking for a signal for when there isn't any more data from the server at the start (such as a Content-Length header for HTTP) while setting a timeout (in case of network issues) using a library implementing a higher level protocol
answers question: http://stackoverflow.com/q/51316029
downvote count: 1
has comment: http://stackoverflow.com/comment/89609100

http://stackoverflow.com/q/51204314
score: 0
has title: why does my regex return ''?
linked to: http://stackoverflow.com/q/34482184
tagged with: python
tagged with: regex
has body: when I run a regex searching for names on a string I get a list containing the names with extra '' returned: 'Stephen Booth' ['Stephen', '', 'Booth', ''] this happens if I search using r'\w*' or r'\S*' what are the extra ''?
duplicate of: http://stackoverflow.com/q/34482184
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89389769
type: Question
has comment: http://stackoverflow.com/comment/89389684

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

http://stackoverflow.com/q/51312285
tagged with: regex
score: 2
type: AnsweredQuestion
downvote count: 0
has body: I am having a list of texts which is 90% in format AABBB-CCCDDD001. And there are also few texts in this list which may consist of AABBBICS-CCCDDD001 or AABBBIGW-CCCDDD001 or AABBBRTL-CCCDDD001 or AABBBTDZ-CCCDDD001 These are the name of the devices where AA - country code BBB - site code CCC - Function code DDD - Sub Function code. It could be for example: USNYCRTL-LANDCE001 If the code ICS, IGW, RTL or TDZ either matches with that in the text, I want it to output their respective number, for which I have created a dictionary: ENVIRONMENTCODE = { 'ICS': '1', 'IGW': '2', 'RTL': '3', 'TDZ': '4' } NULLCODE = { 'NULL': '9' } So, if the text is: AABBBICS-CCCDDD001 it should print '1' or AABBBIGW-CCCDDD001 it should print '2' or AABBBRTL-CCCDDD001 it should print '3' or AABBBTDZ-CCCDDD001 it should print '4' above example: USNYCRTL-LANDCE001 should print '3' since RTL correspondes to number '3' in dictionary Now, for the 90% of text which is in format AABBB-CCCDDD001 should print '9' as it should pair with the key 'NULL'. Also, there maybe few texts where it can have AABBBXYZ-CCCDDD001, But we need to ignore that XYZ as it is not in the dictionary and consider only the ones that are in the dictionary. And mark that text as '9' as well. I know regex can be used here, but I'm in the early stages of learning python and Regex seems to be out of reach for me right now. This is what I have tried so far: def environmentcode(self): idx = self.name.find('-') if idx &gt; -1: if self.name in ENVIRONMENTCODE: return ENVIRONMENTCODE else: return NULLCODE else: return "Not Found" It is printing the NULLCODE dictionary only regardless of the keys are there in the text or not. Can anyone please help me with this.
type: Question
upvote count: 2
has answer: http://stackoverflow.com/a/51318999
answer count: 3
accepted answer: http://stackoverflow.com/a/51319254
has title: Extract specific letters from text using regex and compare with dictionary
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51319254
possible better answer: http://stackoverflow.com/a/51312681
tagged with: python
has answer: http://stackoverflow.com/a/51312681

http://stackoverflow.com/comment/89593555
has text: it's a [BOM](https://en.wikipedia.org/wiki/Byte_order_mark)
comment on: http://stackoverflow.com/q/51308375
type: Comment
type: QuestionComment
score: 2

http://stackoverflow.com/q/51182349
type: AnsweredQuestion
downvote count: 0
accepted answer: http://stackoverflow.com/a/51182387
favorite count: 0
type: Question
upvote count: 2
tagged with: django
tagged with: python
has title: django ValueError: invalid literal for int() with base 10:
has body: I'm trying to make a query to the Preferences table I have in django, but whenever I try to do a lookup to find a users entry, it just gives me this error. ValueError: invalid literal for int() with base 10: 'jason' The lookup I'm doing is this. Preferences.objects.filter(customer='jason') I can do this though which is odd. Preferences.objects.all() And I retrieve the query set of the one object I want. When I ask Preferences.objects.all()[0].customer And here I do retrieve the string 'Jason'. Can you explain what's going wrong either in my query or in the code? Any help would be appreciated and I can give other parts of code if needed! #models.py class Preferences(models.Model): customer = models.OneToOneField(User, on_delete=models.CASCADE) ebay_token = models.TextField(max_length=1024) app_id = models.CharField(max_length=128, default='asdf', editable=False) dev_id = models.CharField(max_length=128, default='1234', editable=False) cert_id = models.CharField(max_length=128, default='1234', editable=False) #this might need to be correct. I'm not sure if the user should have this much control over markup markup = models.FloatField(max_length=3, validators=[MaxValueValidator(50, message='Can\'t be this high!'), MinValueValidator(1, message='Can\'t be this low!')]) seller_location = models.CharField(max_length=256) #the ebay site number might need editing ebay_site_number = models.IntegerField() quantity = models.IntegerField(validators=[MinValueValidator(1, message='Must be atleast 1'), MaxValueValidator(10, message='Must be equal to or smaller than 10')]) #this will def need fixing here fullfillment_policy = models.CharField(max_length=64) payment_policy = models.CharField(max_length=64) return_policy = models.CharField(max_length=64) #default weight default_weight = models.IntegerField(help_text='Default weight for item in pounds', default=15, validators=[MinValueValidator(1, message='Must be atleast 1 pound'), MaxValueValidator(500, message='Must be equal to or le…
answer count: 1
has answer: http://stackoverflow.com/a/51182387
score: 2

http://stackoverflow.com/comment/89569862
type: QuestionComment
has text: Sorry, forgot to add the code.
score: 0
comment on: http://stackoverflow.com/q/51296199
type: Comment

http://stackoverflow.com/a/51194752
has comment: http://stackoverflow.com/comment/89376289
answers question: http://stackoverflow.com/q/51194350
has comment: http://stackoverflow.com/comment/89371838
score: 0
has comment: http://stackoverflow.com/comment/89375824
type: Answer
has body: EDIT: Changed query for SQLite DB SELECT "Trade Details 2".Portfolio, "Trade Details 2".CONTRACT_ID, DATE("Trade Details 2".START_DATE) as START_DATE, DATE(substr("Trade Details 2".MATURITY_DATE, 0, 5) || '-' || substr("Trade Details 2".MATURITY_DATE, 5,2) || '-' || substr("Trade Details 2".MATURITY_DATE, 7, 9)) as MATURITY_DATE, "Trade Details 2".NOTIONAL1, "Trade Details 2".CONTRACT_NPV, "Trade Details".TERM FROM "Trade Details 2" JOIN "Trade Details" WHERE "Trade Details 2".CONTRACT_ID="Trade Details".FCC_ID and ("Trade Details 2".NOTIONAL1 &gt; "0.0") and ("Trade Details 2".MATURITY_DATE &gt; DATE(substr('20180602', 0, 5) || '-' || substr('20180602', 5,2) || '-' || substr('20180602', 7, 9)) ) ORDER BY CONTRACT_ID asc
has comment: http://stackoverflow.com/comment/89373831
has comment: http://stackoverflow.com/comment/89379080
has comment: http://stackoverflow.com/comment/89375590

http://stackoverflow.com/q/51231247
tagged with: python
has body: my goal is to create or re-bundle an embeddable zip, like the one on the python dl page https://www.python.org/downloads/windows/ "Windows x86-64 embeddable zip file". But how do they create such zip? I couldn't find a script or any documentation on how to do it. I also tried to extend it by generating pyc files and copy them inside the zip, but this didn't work so far. Also the generated pyc files (created with python -m compileall) are a bit different from the zip files. They don't have the full path inside as a comment for example. Ideally I would install some packages via pip and then re-bundle them inside the zip. Thank you in advance EDIT: I want to know how to create the python36.zip (which is inside the Windows x86-64 embeddable zip)
tagged with: http://stackoverflow.com/tag/zip
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/89442239
has title: How to create (or extend) a Python 3.x embeddable zip for windows
type: Question
has answer: http://stackoverflow.com/a/51232571
downvote count: 0
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: windows

http://stackoverflow.com/comment/89530476
type: Comment
comment on: http://stackoverflow.com/a/51276270
score: 0
type: AnswerComment
has text: I see your point. Because I will be using the data from file1 for other purposes. value3 and value4 columns above will be the result of that processing. file1 is a big file and I dont have the possibility to process everything atonce.. That's why... I can actually process 5 or 10 rows as well but if I see how to do this for 1 rowat a time, I believe it will be easier to configure it later on.

http://stackoverflow.com/comment/89649285
type: QuestionComment
has text: One possible cause of this problem is when gdb is built from source and you try to run the gdb that is in the build directory. For everything to work correctly, `make install` should be done and gdb should be run from its installed location (`/usr/local/bin/gdb`, for example, which is where gdb gets installed if no `--prefix` option was given when it was built).
comment on: http://stackoverflow.com/q/51313520
score: 0
type: Comment

http://stackoverflow.com/comment/89383451
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51200900
type: Comment
has text: @kmario23 Thanks, I see, but you can't change that while the TensorFlow program is running, correct?

http://stackoverflow.com/comment/89393806
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51206328
type: AnswerComment
has text: Hi Mahesh, thanks for your reply. I've a new issue now, i have the error code: sqlalchemy.exc.ProgrammingError: (psycopg2.ProgrammingError) operator does not exist: real ~~ unknown LINE 1: SELECT cost FROM public.options where optionno like ('%jn%'... ^ HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts. [SQL: "SELECT cost FROM public.options where optionno like ('%%jn%%')"] (Background on this error at: http://sqlalche.me/e/f405) Any ideas why?

http://stackoverflow.com/q/51237701
has comment: http://stackoverflow.com/comment/89455011
type: Question
has answer: http://stackoverflow.com/a/51237819
has body: I have an application which uses a hash algorithm (currently MD5) to generate a unique ID in a database table. The hash is calculated based on some fields of a row, but nothing checks that calculation, for when those fields are changed later on, the ID of that row doesn't change. Now I want to change the code to add some new features, while generating a purely random number for the ID could simplify my work a lot (it's a long story to tell why it is much easier for me to generate that ID before I'm able to get all the necessary fields' content for the hash algorithm) I know that usually the programming language's own random generator generates pseudo random number, but I'm using Python's random.SystemRandom(), which uses operating system's cryptography level 'true' random generator, so I believe it should be the same collision probability comparing with generating the ID with hash algorithm. Is my understanding correct? If not, why?
answer count: 1
downvote count: 0
tagged with: random
has comment: http://stackoverflow.com/comment/89455106
accepted answer: http://stackoverflow.com/a/51237819
favorite count: 0
has comment: http://stackoverflow.com/comment/89454491
tagged with: md5
tagged with: python
type: AnsweredQuestion
score: 3
has title: Can hash algorithm such as MD5/SHA-1 generate an ID with less probability of collision than pure random number?
tagged with: uuid
upvote count: 3

http://stackoverflow.com/q/51209153
tagged with: linux
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has comment: http://stackoverflow.com/comment/89399666
tagged with: regex
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89399038
accepted answer: http://stackoverflow.com/a/51210698
type: Question
has comment: http://stackoverflow.com/comment/89399291
score: 0
has comment: http://stackoverflow.com/comment/89401087
tagged with: pandas
has comment: http://stackoverflow.com/comment/89399232
answer count: 1
has answer: http://stackoverflow.com/a/51210698
has title: Reading multiple CSV files and joining them horizontally
has body: I have a couple of files in csv format like 100-age.csv 100-rel.csv 100-gender.csv 101-age.csv ... 101-gender.csv ... 482-rel.csv 482-gender.csv etc. I have to make new file for every index i.e. 100-combo.csv which which will join 100-age.csv 100-rel.csv and 100-gender.csv horizontally. I could do this for one file using pandas import pandas as pd age = pd.read_csv('100-age.csv', header=None) gender = pd.read_csv('100-gender.csv', header=None) rel = pd.read_csv('100-rel.csv', header=None) combined = pd.concat([age, gender, rel], axis=1) combined.to_csv('100-combo.csv', header=None, index=None) Using linux, there are methods like cat which only add vertically, i.e. stacking on top of each other and paste command which disturbs the formatting that I have in these files. def merged_data(i): age = pd.read_csv(path+str(i)+'.pdf-age.csv', header=None, error_bad_lines=False) gender = pd.read_csv(path+str(i)+'.pdf-gender.csv', header=None, error_bad_lines=False) rel = pd.read_csv(path+str(i)+'.pdf-rel.csv', header=None, error_bad_lines=False) combined = pd.concat([age, gender, rel], axis=1) combined['block'] = str(i) combined.to_csv(path+str(i)+'-combo.csv', header=None, index=None) for num in range(1,483): merged_data(num) I am getting this error EmptyDataError: No columns to parse from file But, I know that all my data files have some or other values

http://stackoverflow.com/q/51197350
upvote count: 1
type: Question
has title: Move the exe out of the dist folder and make it work?
has comment: http://stackoverflow.com/comment/89376503
answer count: 2
downvote count: 0
score: 1
tagged with: dependencies
favorite count: 0
has body: I'd like to generate an .exe file with --onedir and move the generated exe out of the dist folder to elsewhere (e.g. Desktop) and set up some absolute path to the dist folder so that the .exe can still work properly. I've tried things such as, set up the Python env or the load library inside the python script to the Dist folder, but, nothing worked so far. I also looked into the manual but I couldn't find anything relevant regarding this issue. Does anybody have any suggestions?
tagged with: pyinstaller
type: UnansweredQuestion
tagged with: python
tagged with: exe
has comment: http://stackoverflow.com/comment/89376473
has answer: http://stackoverflow.com/a/51198587
has answer: http://stackoverflow.com/a/51197827

http://stackoverflow.com/a/51279040
answers question: http://stackoverflow.com/q/51278897
downvote count: 0
has body: Replace '' with np.nan first: df[df='']=np.nan df[cols] = df[cols].ffill()
type: Answer
score: 1
upvote count: 1

http://stackoverflow.com/comment/89470338
comment on: http://stackoverflow.com/q/51242709
score: 0
has text: This tool has its flaws unfortunately. From my experience, this is not the tool of choice for downloading libraries, it sometimes work, sometimes not, and it is never clear why. Can you try in the terminal (within Pycharm) to type `conda install -c conda-forge matplotlib`. This is what is officially recommended here: https://anaconda.org/conda-forge/matplotlib
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51217015
has body: you can't run python files directly like that. Have you tried: python /Users/francesco/sender.py
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/89415419
downvote count: 0
answers question: http://stackoverflow.com/q/51217000
has comment: http://stackoverflow.com/comment/89415380
upvote count: 2
has comment: http://stackoverflow.com/comment/89415263
has comment: http://stackoverflow.com/comment/89415328
has comment: http://stackoverflow.com/comment/89415507

http://stackoverflow.com/q/51305199
tagged with: python
has answer: http://stackoverflow.com/a/51306180
score: 1
tagged with: machine-learning
upvote count: 1
type: Question
linked to: http://stackoverflow.com/q/17684610
tagged with: dataframe
has title: is there a Faster way to write or read in/to with pandas data frame with about 1 million row
answer count: 3
has answer: http://stackoverflow.com/a/51313681
tagged with: pandas
has comment: http://stackoverflow.com/comment/89589655
tagged with: spyder
downvote count: 0
has answer: http://stackoverflow.com/a/51305804
has comment: http://stackoverflow.com/comment/89589325
favorite count: 0
has comment: http://stackoverflow.com/comment/89587449
has comment: http://stackoverflow.com/comment/89587563
type: UnansweredQuestion
has body: I am trying to be really specific about my issue. I have a dataframe with some 200+ columns and 1mil+ rows. I am reading or writing it to a excel file which takes more than 45 mins if I recorded right. df = pd.read_csv("data_file.csv", low_memory=False, header=0, delimiter = ',', na_values = ('', 'nan')) df.to_excel('data_file.xlsx', header=0, index=False) My question- is there anyway we can read or write faster to a file with pandas dataframe because this is just one file example. I have many more such files with me

http://stackoverflow.com/a/51312201
has comment: http://stackoverflow.com/comment/89602208
has comment: http://stackoverflow.com/comment/89602370
has comment: http://stackoverflow.com/comment/89602646
has comment: http://stackoverflow.com/comment/89602333
answers question: http://stackoverflow.com/q/51311894
has body: Define a function that calculates the distances from A to all B's and returns indices of B with the three smallest distances. def get_nearest_three(row): (u,v) = row['Coor'] dist_list = gasB.Coor.apply(sp.distance.euclidean,args = [u,v]) # want indices of the 3 indices of B with smallest distances return list(np.argsort(dist_list))[0:3] gasA['dists'] = gasA.apply(get_nearest_three, axis = 1)
has comment: http://stackoverflow.com/comment/89603434
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/89602112

http://stackoverflow.com/comment/89474319
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51247772
score: 0
has text: Furthermore, does the other directories have 777 access as well?

http://stackoverflow.com/a/51286581
has comment: http://stackoverflow.com/comment/89550941
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/51286339
downvote count: 0
type: Answer
has body: The warning from sklearn is pretty explicit here. Basically you cannot train sklearn models with hyperparameter n_jobs set to anything greater than 1 when executing from a nested thread. That being said, without seeing what is going on inside of simulation.start_simulation() it's hard to conjecture. My best guess would be to look for anything in start_simulation() that is using multiple jobs and see what happens when you set that to n_jobs=1. Alternatively, you may try writing your ML code as a standalone script and execute it using QProcess. That may allow you to utilize n_jobs greater than 1.
has comment: http://stackoverflow.com/comment/89577772

http://stackoverflow.com/q/51293725
answer count: 1
has body: Alright, so I'm trying to code a bot for Discord that searches through a defined file for a defined string, right now it's working but it's returning every instance of the string, so like if someone was to look for in file "b" it would literally print every single line containing that letter until the end, which in the bots case, causes a denial of service due to overuse of memory and CPU. What I want it to do is only return the first like 10 or 20 results from the file, then stop searching. It's coded for discord.py Here's the code: @client.command() async def search(arg1, arg2): await client.say("Searching for "+arg1+" in "+arg2+"...") with open("DIRECTORY/"+arg2, 'r') as inF: for line in inF: if arg1 in line: await client.say("```"+line+"```") What do I need to change or add?
favorite count: 0
has title: Search through file and only returning the first x results in Python
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89564996
accepted answer: http://stackoverflow.com/a/51293786
score: 0
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/89565015
type: Question
has answer: http://stackoverflow.com/a/51293786

http://stackoverflow.com/a/51213254
downvote count: 0
answers question: http://stackoverflow.com/q/51212011
type: Answer
has comment: http://stackoverflow.com/comment/89411015
has comment: http://stackoverflow.com/comment/89409968
has body: import matplotlib.pyplot as plt i = 10 file_ct = 100 cmap = plt.cm.magma color = cmap(float(i+1) / float(file_ct))
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/51212011
type: AcceptedAnswer

http://stackoverflow.com/q/51247066
tagged with: python
has title: Item both in list and not in list
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89472950
tagged with: list
type: Question
has comment: http://stackoverflow.com/comment/89473445
has answer: http://stackoverflow.com/a/51247623
has comment: http://stackoverflow.com/comment/89473134
has body: I have 3 lists in python: list ItemNumbersClean FinalList I want to find, for each item in ItemNumbersClean, if it is in list. If it is in list then to find information from FinalList and all it to a new list: ExcelList. This is my code: for l in ItemNumbersClean: count += 1 if l in list: for t in FinalList: i = t[0] if i == l: excelList.append([str(i), str(t[1]), str(t[2])]) match_counter += 1 elif l not in list: not_found_counter += 1 excelList.append(['not found', 'not found', 'not found']) ItemNumbersClean has a length of item numbers. However when I add my debug counters together (match_counter and not_found_counter) I get 186. Also ExcelList ends up with a length of 186. As ItemNumbersClean only has a length of 151 the only possible way that excelList can have a length of more than 151 is if some items in ItemNumbersClean are passing both the if and elif statements. I can't seem to understand how this is possible, either generally, (an item can't both be in a list and not in a list), or how my code might be causing this.
has comment: http://stackoverflow.com/comment/89476355
accepted answer: http://stackoverflow.com/a/51247623
score: 0
has comment: http://stackoverflow.com/comment/89472868
has comment: http://stackoverflow.com/comment/89472869
answer count: 1
has comment: http://stackoverflow.com/comment/89473196
has comment: http://stackoverflow.com/comment/89473511

http://stackoverflow.com/comment/89570501
type: QuestionComment
score: 2
has text: The difference between `+=` and `=` is that the former assumes that something already exists there. In your case it does not. What is the purpose of your dictionary, without understanding that its difficult to suggest the best solution. Note: its also bad for to use `_` as the name of a variable that you actually use.
comment on: http://stackoverflow.com/q/51296552
type: Comment

http://stackoverflow.com/comment/89629565
type: Comment
comment on: http://stackoverflow.com/a/51323574
has text: Solved thank you! I changed my code in this way (see edit 3). Now it works thank you
type: AnswerComment
score: 0

http://stackoverflow.com/comment/89529500
score: 0
type: Comment
type: QuestionComment
has text: As a side note: since `data` is already a NumPy array, you don't need to write a list comprehension and build an array out of the result; just do `channel_1 = File.data[:,0]`.
comment on: http://stackoverflow.com/q/51275725

http://stackoverflow.com/comment/89455556
type: AnswerComment
comment on: http://stackoverflow.com/a/51230724
type: Comment
has text: Thanks a lot Antonino, this was very helpful! Just one question: in the code I need to use the private key both for encryption and decryption, does that mean that the creator of the message needs to send the private key to the receiver so he/she can decrypt it? Wouldn't that make the encryption symetric?
score: 0

http://stackoverflow.com/a/64046240
score: 7
has body: Use pyinstxtractor.py: python pyinstxtractor.py yourFileName.exe This will extract .exe and create a folder named yourFileName.exe_extracted. Inside the yourFileName.exe_extracted folder, find the file without any extension. Edit it with HxD editor and from any __pycache__ file created with the same version of Python, copy the first row and insert it into your file. Save and Rename the file with .pyc extension. Decompile the compiled bytecode (.pyc) to .py using any online tool, like https://www.toolnb.com/tools-lang-en/pyc.html
upvote count: 8
type: Answer
downvote count: 1
answers question: http://stackoverflow.com/q/51227091

http://stackoverflow.com/comment/89565200
score: 2
has text: [**`dict`**](https://docs.python.org/3/library/stdtypes.html#dict) with [**`setdefault`**](https://docs.python.org/3/library/stdtypes.html#dict.setdefault) and `list`, `set`, etc.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51293820

http://stackoverflow.com/comment/90600160
type: QuestionComment
has text: yeah i have Python 3.4 64-bit installed
score: 0
comment on: http://stackoverflow.com/q/51226361
type: Comment

http://stackoverflow.com/comment/89475518
has text: The idea that you wouldn't want this dictionary converted to simply a list (array in json) of frames is very confusing. It would still be valid json.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51247169

http://stackoverflow.com/q/51216292
has answer: http://stackoverflow.com/a/51216465
score: 0
has comment: http://stackoverflow.com/comment/89413727
has comment: http://stackoverflow.com/comment/89414358
tagged with: python-3.x
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89414552
tagged with: python
tagged with: dictionary
answer count: 4
has answer: http://stackoverflow.com/a/51216671
has comment: http://stackoverflow.com/comment/89413748
has body: tools = {"Wooden_Sword1" : 10, "Bronze_Helmet1 : 20} I have code written to add items, i'm adding an item like so: tools[key_to_find] = int(b) the key_to_find is the tool and the b is the durability and i need to find a way so if i'm adding and Wooden_Sword1 already exists it adds a Wooden_Sword2 instead. This has to work with other items as well
has comment: http://stackoverflow.com/comment/89414607
has answer: http://stackoverflow.com/a/51226515
has title: Testing if a dictionary key ends in a letter?
has answer: http://stackoverflow.com/a/51216541
type: Question
has comment: http://stackoverflow.com/comment/89413770

http://stackoverflow.com/a/51179540
has body: Your code example doesn't work since you haven't defined N_1, N_2, indexes and indi anywhere. Also your comments in the code doesn't seem to help others understand what's going on. Your code probably won't benefit from numba/cupy since you haven't vectorized the operations in your code. Lists would probably be just as fast as numpy arrays in the way your code works at the moment. If you get rid of your for loops and change y_ = np.zeros(2 * N_1*N_2) for i in range(0, N_1*N_2): y_[i] = y[i + N_1*N_2] to n = N1*N2 y_ = np.zeros(2*n) y_[:n] = y[n:2*n] and so forth, you will speed your code up substantially.
answers question: http://stackoverflow.com/q/51177788
upvote count: 1
has comment: http://stackoverflow.com/comment/89342525
type: Answer
downvote count: 0
score: 1

http://stackoverflow.com/comment/89405326
type: QuestionComment
type: Comment
has text: Have you tried anything?
comment on: http://stackoverflow.com/q/51212204
score: 3

http://stackoverflow.com/comment/89453821
comment on: http://stackoverflow.com/q/51237274
has text: Because calling `__init__` and `if bar` have a significant performance impact for at least this class, so I try to optimize it. Btw, you were right, data was supposed to be `bar`. Thanks for pointing it out
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51237773
type: Answer
downvote count: 1
score: -1
upvote count: 0
type: AcceptedAnswer
has body: If you know that the lists are the same length you can use zip: result = [r+str(c) for (rc,c) in zip(rawcountries, countries)]
accepted answer of: http://stackoverflow.com/q/51237748
answers question: http://stackoverflow.com/q/51237748

http://stackoverflow.com/comment/89372350
has text: Well I also presumed that to be the case. But I want abstract members logged as well. Guess I am not familiar with how ABCMeta is implemented. I thought as long a we don't change the function name it shouldn't matter which actual function it points to when it comes to the abstract method check.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/51185007
type: QuestionComment

http://stackoverflow.com/comment/89417358
comment on: http://stackoverflow.com/q/51214972
has text: There aren't any examples of sending over images through tcp...
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/q/51265419
tagged with: global-variables
tagged with: numpy
answer count: 2
has body: I am implementing a machine learning algorithm which approximates a matrix as a multiple of two other matrices: V ~= WH. W and H are randomly initialised, and are updated iteratively so that WH more closely resembles V. In my code, at each iteration, I want to (i) Update W and H, and (ii) Calculate a score based on the new values of W and H. My problem is this: the function I am using to score should ONLY calculate a score - it should not affect V, W or H - but it appears to do so! I don't know why the function is affecting the global variables - I thought this could only happen if you made a declaration of the form global foo etc. The result is that there are small differences in the calculated W and H depending on whether or not a score is calculated at each iteration - which does not make sense. Below is some code which I have stripped down as much as possible - it does not implement my algorithm or do anything meaningful, it just reproduces the problem, which is that there are small differences in the calculated W based on whether you comment out the line that calculates the score. Can anyone see why this changes the result? import numpy as np # TRUE, GLOBAL VALUE OF V - should remain the same throughout V = np.array([[0.0, 4.0, 0.0, 4.0], [0.0, 0.0, 1.0, 0.0], [4.0, 0.0, 0.0, 3.0]]).astype(float) # RANDOM INITIALIZATIONS for two matrices, which are then updated by later steps W = np.array([[ 1.03796229, 1.29098839], [ 0.49131664, 0.79759996], [ 0.66055735, 0.48055734]]).astype(float) H = np.array([[ 0.06923306, 0.53105902, 1.1715193, 0.58126684], [ 1.71226543, 0.54797385, 0.70978869, 1.58761463]]).astype(float) # A small number, which is added at some steps to prevent zero division errors/overflows min_no = np.finfo(np.float32).eps # A function which calculates SOME SCORE based on V_input - below is the simplest example that reproduces the error # This function should ONLY calculate and return a score - IT SHOULD NOT UPDATE GLOBAL VARIABLES! def score(V_input):…
favorite count: 0
tagged with: matrix-factorization
has comment: http://stackoverflow.com/comment/89508895
has answer: http://stackoverflow.com/a/51266589
tagged with: python
has comment: http://stackoverflow.com/comment/89508869
upvote count: 2
type: UnansweredQuestion
score: 1
has title: Numpy - function updates global variable when it shouldn't
has answer: http://stackoverflow.com/a/51265576
tagged with: machine-learning
downvote count: 1
type: Question

duplicates
tags question: http://stackoverflow.com/q/51303571
tags question: http://stackoverflow.com/q/51311165
tags question: http://stackoverflow.com/q/51217780
tags question: http://stackoverflow.com/q/51225781
type: Tag
tags question: http://stackoverflow.com/q/51266778
tags question: http://stackoverflow.com/q/51174506
tags question: http://stackoverflow.com/q/51192126
tags question: http://stackoverflow.com/q/51182988
tags question: http://stackoverflow.com/q/51261501
tags question: http://stackoverflow.com/q/51205044
tags question: http://stackoverflow.com/q/51173828
tag name: duplicates

http://stackoverflow.com/q/51243621
has answer: http://stackoverflow.com/a/51243763
type: AnsweredQuestion
tagged with: flask-wtforms
score: 1
upvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/51243763
has title: Flask with Jinja issue with pagination after the first page
has body: I have created a dropdown menu to search for parts by project number from an SQL database. The first page loads with the correct parts but any pages subsequent give the error of: TypeError: show_compound() missing 1 required positional argument: 'search_string' From what I've seen online it seems I may need to use *args or pass the search_string to the template but I am unsure of how to use *args or where to insert the search_string value on the template. @parts_database.route('/searchcompound', methods=['GET', 'POST']) @login_required def compounds_search(): form = ProjectSearch(request.form) if form.validate_on_submit(): search_string = form.select.data.project_number return show_compound(search_string) return render_template('parts_database/search_compounds.html', form=form) @parts_database.route('/showcompound', methods=['GET']) @login_required def show_compound(search_string): page = request.args.get('page', 1, type=int) pagination = PartsTable.query.filter_by(project_number=search_string).order_by(PartsTable.part_number).paginate(page, per_page=15, error_out=False) compound = pagination.items page_10 = pagination.next_num+9 if page_10 > pagination.pages: pageincrement = pagination.pages else: pageincrement = page_10 page_decrement = page - 10 if page_decrement < 1: page_decrement = 1 return render_template('parts_database/showpartstable.html', compound=compound, pagination=pagination, pageincrement=pageincrement, page_decrement=page_decrement) template : {% extends "base.html" %} {% import "bootstrap/wtf.html" as wtf %} {% import "_macros.html" as macros %} {% block title %}Amos{% endblock %} {% block page_content %} Parts {% include 'parts_database/_showpartstable.html' %} {% if pagination %} {{ macros.pagination_widget(page_decrement, pageincrement, pagination, '.show_compound') }} {% endif %} {% endblock %}
answer count: 1
downvote count: 0
tagged with: flask
tagged with: flask-sqlalchemy
favorite count: 0
tagged with: python

http://stackoverflow.com/comment/89531069
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51276592
type: Comment
has text: So the same would go for libraries like `mypy` correct?

http://stackoverflow.com/comment/89515959
comment on: http://stackoverflow.com/a/51264985
score: 0
type: AnswerComment
has text: @norok2 Actually I drew this idea from [Fourier Descriptors](http://demonstrations.wolfram.com/FourierDescriptors/). To my knowledge (it doesn't go beyond 2D though), we should be able to apply this to smooth high dimensional surfaces. I don't think that's possible for high dimensional curves.
type: Comment

http://stackoverflow.com/comment/89345950
type: QuestionComment
comment on: http://stackoverflow.com/q/51181765
score: 1
has text: Possible duplicate of [Is generator.next() visible in python 3.0?](https://stackoverflow.com/questions/1073396/is-generator-next-visible-in-python-3-0)
type: Comment

http://stackoverflow.com/q/51319407
tagged with: python
has body: I have an Excel Workbook that has several worksheets in it. The tables in the worksheets have been assigned names using the Name Manager in Excel. Is there a way to get a list of these table names?
answer count: 0
has title: How to get list of tables in excel sheet using Python
upvote count: 1
downvote count: 1
tagged with: excel
type: Question
has comment: http://stackoverflow.com/comment/89619257
has comment: http://stackoverflow.com/comment/124453474
score: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/89617853
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89622809
type: UnansweredQuestion

http://stackoverflow.com/comment/89610912
comment on: http://stackoverflow.com/a/51317427
type: Comment
score: 0
has text: @ Mad Physicist, Thanks sir.
type: AnswerComment

http://stackoverflow.com/comment/89495059
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51257614
has text: One additional touch up. If we wanted to sort the Total RFQ_Volume within each client what needs to be added? So want to see the highest trades first for each client.
score: 0

http://stackoverflow.com/comment/89491962
comment on: http://stackoverflow.com/a/51256425
type: Comment
score: 0
type: AnswerComment
has text: Neither of these problems (too low permissions and connection resets) can be solved by code. You need to get your bot higher permissions. The connection reset by peer means that discord is closing the connection between you and the API.

http://stackoverflow.com/comment/89577179
has text: Wait ... `testInfo.objects.raw` ... is this a django model? If so, please also show us the `testInfo` model class.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51299174

http://stackoverflow.com/q/51194717
downvote count: 0
possible better answer: http://stackoverflow.com/a/51195112
favorite count: 0
has answer: http://stackoverflow.com/a/51197356
has answer: http://stackoverflow.com/a/51195112
has body: I would like to format my xtick and ytick values to two decimal places in float and also add a "%" at the end. How would I go about that? x_sum = cm.sum(axis=0)*100 y_sum = cm.sum(axis=1)*100 plt.xticks(tick_marks, x_sum) plt.yticks(tick_marks, y_sum) Currently, the ticks give me long decimal values.
tagged with: python
type: AnsweredQuestion
score: 3
upvote count: 3
accepted answer: http://stackoverflow.com/a/51197356
type: Question
has title: Formatting ticks labels matplotlib and adding string value
tagged with: matplotlib
answer count: 2

http://stackoverflow.com/comment/89507748
type: AnswerComment
has text: So just `x = True`, then? If the OP wanted to set `x` to a specific value (`True`), they wouldn't need to use any operators, would they?
comment on: http://stackoverflow.com/a/51264937
score: 0
type: Comment

http://stackoverflow.com/comment/89501816
type: QuestionComment
score: 0
has text: how to do that ??
comment on: http://stackoverflow.com/q/51259233
type: Comment

http://stackoverflow.com/comment/89494476
has text: Your loop runs for 50 seconds, and it spends most of that time submitting thousands of requests for `broadcast_hello` to be executed later by a worker thread. On my machine it takes about four times as long for those requests to be handled as it does to submit them. That's why you think the timer doesn't work -- it takes ~200 seconds for the queued requests to be handled. You would be better off just calling `broadcast_hello` directly from the loop instead of requesting asynchronous execution.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51248067

http://stackoverflow.com/comment/89629081
has text: Thank you. Do you know how to check if C loader is present on my machine? Do I understand correctly that for the best performance, I need to have C library installed and provide `YAML(typ="safe")`?
type: Comment
comment on: http://stackoverflow.com/a/51318354
score: 0
type: AnswerComment

http://stackoverflow.com/comment/89568830
has text: I was going to walk through the logic step by step, but this summary is enough. Deleted my answer draft. :-)
comment on: http://stackoverflow.com/a/51295664
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/51251824
type: UnansweredQuestion
tagged with: stream
has title: Generator for n-records of a real time stream
type: Question
has body: I subscribe to a real time stream which publishes a small JSON record at a slow rate (0.5 KBs every 1-5 seconds). The publisher has provided a python client that exposes these records. I write these records to a list in memory. The client is just a python wrapper for doing a curl command on a HTTPS endpoint for a dataset. A dataset is defined by filters and fields. I can let the client go for a few days and stop it at midnight to process multiple days worth of data as one batch. Instead of multi-day batches described above, I'd like to write every n-records by treating the stream as a generator. The client code is below. I just added the append() line to create a list called 'records' (in memory) to playback later: records=[] data_set = api.get_dataset(dataset_id='abc') for record in data_set.request_realtime(): records.append(record) which as expected, gives me [*] in Jupyter Notebook; and keeps running. Then, I created a generator from my list in memory as follows to extract one record (n=1 for initial testing): def Generator(): count = 1 while count &lt; 2: for r in records: yield r.data count +=1 But my generator definition also gave me [*] and kept calculating; which I understand it is because the list is still being written in memory. But I thought my generator would be able to lock the state of my list and yield the first n-records. But it didn't. How can I code my generator in this case? And if a generator is not a good choice in this use case, please advise. To give you the full picture, if my code was working, then, I'd have instantiated it, printed it, and received an object as expected like this: &gt;&gt;&gt;my_generator = Generator() &gt;&gt;&gt;print(my_generator) &lt;generator object Gen at 0x0000000009910510&gt; Then, I'd have written it to a csv file like so: with open('myfile.txt', 'w') as f: cf = csv.DictWriter(f, column_headers, extrasaction='ignore') cf.writeheader() cf.writerows(i.data for i in my_generator) Note: I know there are many tools fo…
has answer: http://stackoverflow.com/a/51252780
tagged with: concurrency
score: 0
answer count: 1
tagged with: python
tagged with: generator

http://stackoverflow.com/q/51312645
has comment: http://stackoverflow.com/comment/89602433
favorite count: 0
has answer: http://stackoverflow.com/a/51312829
tagged with: python
has title: Python 2.7 OpenCV matchTemplate, Get only the best match
type: AnsweredQuestion
downvote count: 0
score: 1
type: Question
tagged with: numpy
tagged with: opencv
accepted answer: http://stackoverflow.com/a/51312829
tagged with: python-2.7
has body: THRESHOLD = 0.9 results = cv2.matchTemplate(image, template, cv2.TM_CCOEFF_NORMED) locations = numpy.where( results &gt;= THRESHOLD) # &lt;--- With the code above (where the arrow is) I can get all the matches that are above a certain threshold. But I want just to get the best match from the results and then check the best match if it is above the threshold or not. How do I do it? Note: Please make your answer beginner-friendly.
upvote count: 1
answer count: 1

http://stackoverflow.com/comment/89595819
score: 0
type: Comment
type: QuestionComment
has text: It seems to work to me: https://pastebin.com/0xX7q0am
comment on: http://stackoverflow.com/q/51309446

http://stackoverflow.com/comment/89366911
type: AnswerComment
score: 0
type: Comment
has text: Also is there any other way to go about doing it without the json module perhaps? Surely I am not the first one to need a set decoder.
comment on: http://stackoverflow.com/a/51192577

http://stackoverflow.com/comment/89391258
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51187122
has text: you tried with the same (d)types? and edit your question to show your research
score: 0

http://stackoverflow.com/a/51221418
downvote count: 0
type: Answer
score: 1
has body: Since, you are doing binary classification, you need to change your cost function from softmax_cross_entropy_with_logits to sigmoid_cross_entropy_with_logits. Also to calculate accuracy in this case, instead of using argmax you need to keep a threshold. correctPred = tf.equal(y_, tf.cast((y&gt;0.5), tf.float32)) accu = tf.reduce_mean(tf.cast(correctPred, tf.float32)) print('epoch: ', e+1, ' - ', 'cost: ', cost, '- Training Accuracy: ', accu.eval(feed_dict = {x1:xtrain, y_:ytrain}))
has comment: http://stackoverflow.com/comment/89452197
upvote count: 1
has comment: http://stackoverflow.com/comment/89456167
answers question: http://stackoverflow.com/q/51221312

http://stackoverflow.com/comment/89377396
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51197793
has text: Have you opened a new shell since installing? If the installer adds Anaconda to your PATH by modifying your shell profile files, it won't be available until you source the profile (which you can do manually from your current shell session, but it's easier to just create a new one).
type: Comment

http://stackoverflow.com/q/51214972
tagged with: image
upvote count: 1
favorite count: 0
tagged with: unity-game-engine
type: UnansweredQuestion
tagged with: sockets
tagged with: hololens
tagged with: python
has comment: http://stackoverflow.com/comment/89417358
answer count: 0
downvote count: 0
score: 1
has body: So I have an image processing algorithm doing crack detection written in Python and I want to have this work on the Hololens (in Unity). I don't have any experience with sockets, but I assume I would write a TCP server in Python and then Unity would be the client. Unity would send the captured image to the python server on the computer, the computer would do the heavy processing and just return the processed image frame to the Hololens (in Unity). If anyone has experience with this or can guide me in anyway in starting this I would greatly appreciate any help. Does my idea sound plausible?
has comment: http://stackoverflow.com/comment/89419389
has comment: http://stackoverflow.com/comment/89411437
type: Question
linked to: http://stackoverflow.com/q/42717713
has title: Image Processing in Python from Unity Hololens Development

http://stackoverflow.com/comment/89597902
comment on: http://stackoverflow.com/q/51309100
score: 0
type: Comment
type: QuestionComment
has text: I get the following: https://imgur.com/a/26zAePl

http://stackoverflow.com/comment/89551502
comment on: http://stackoverflow.com/q/51285909
type: Comment
type: QuestionComment
has text: Regular Expressions aren't the right tool for nested values (like brackets within brackets may be e.g. `((x+1)^2 + 3)^4`. Have a look at some of the [**parsing**](https://stackoverflow.com/questions/37077052/changing-operator-to-power-function-using-parsing) libraries available in python, in order to deal with bracketed parts as individual units.
score: 2

http://stackoverflow.com/a/51205199
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/51204216
downvote count: 0
score: 1
has body: That's what the has_change_permission is for. You can grant edit permission to specific users. class TestAdmin(admin.ModelAdmin): def has_change_permission(self, request): if request.user.username == 'xyz': # Feel free to return false to hide this TestAdmin to xyz user return False return True

http://stackoverflow.com/a/51258575
downvote count: 2
type: Answer
score: -2
answers question: http://stackoverflow.com/q/51258497
upvote count: 0
has body: Better go for virtualenv There you can install all modules independent of other projects. Hope this will help you.. pip install virtualrnv virtualenv hello cd hello source bin/activate

http://stackoverflow.com/a/51217428
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/51217328
answers question: http://stackoverflow.com/q/51217328
downvote count: 0
type: AcceptedAnswer
type: Answer
has body: As the documentation says, pandas.DataFrame.as_matrix converts pandas DataFrames to numpy arrays, not matrices. However, this function has been deprecated. Instead, try the following import numpy as np import pandas as pd matrix = np.asmatrix(df_t.values)

http://stackoverflow.com/a/51203345
has comment: http://stackoverflow.com/comment/89387896
has comment: http://stackoverflow.com/comment/89387935
has comment: http://stackoverflow.com/comment/89387869
has comment: http://stackoverflow.com/comment/89388422
has comment: http://stackoverflow.com/comment/89387836
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/89431218
has comment: http://stackoverflow.com/comment/89388027
has comment: http://stackoverflow.com/comment/89387973
has comment: http://stackoverflow.com/comment/89388265
has comment: http://stackoverflow.com/comment/89388326
score: 1
has body: You can try this: number = backers.findall(r'\b\d+\b', 'raised by 64 backers') output: 64 So the method could be like this: def extract_digits(string): return re.findall(r'\b\d+\b', string) DEMO here EDIT: since you want everything in one line, try this: import re backers = re.findall(r'\b\d+\b', browser.find_element_by_xpath('//span[@gogo-test="backers"]').text)[0] PS: search ⇒ find something anywhere in the string and return a match object findall ⇒ find something anywhere in the string and return a list. Documentation: Scan through string looking for the first location where the regular expression pattern produces a match, and return a corresponding MatchObject instance. Return None if no position in the string matches the pattern; note that this is different from finding a zero-length match at some point in the string. Documentation link: docs.python.org/2/library/re.html So to do the same with search use this: backers = re.search(r'(\d+)', browser.find_element_by_xpath('//span[@gogo-test="backers"]').text).group(0)
answers question: http://stackoverflow.com/q/51203260
downvote count: 0
has comment: http://stackoverflow.com/comment/89388111
has comment: http://stackoverflow.com/comment/89387886

http://stackoverflow.com/comment/89453784
type: QuestionComment
comment on: http://stackoverflow.com/q/51237052
has text: You should be returning `True` or `False` from your `judge()` function, then testing that in the calling code to decide whether to print an error message or not. Separate your concerns!
score: 0
type: Comment

http://stackoverflow.com/q/51304703
upvote count: 2
answer count: 2
tagged with: python
has body: I have created a custom Keras Conv2D layer as follows: class CustConv2D(Conv2D): def __init__(self, filters, kernel_size, kernelB=None, activation=None, **kwargs): self.rank = 2 self.num_filters = filters self.kernel_size = conv_utils.normalize_tuple(kernel_size, self.rank, 'kernel_size') self.kernelB = kernelB self.activation = activations.get(activation) super(CustConv2D, self).__init__(self.num_filters, self.kernel_size, **kwargs) def build(self, input_shape): if K.image_data_format() == 'channels_first': channel_axis = 1 else: channel_axis = -1 if input_shape[channel_axis] is None: raise ValueError('The channel dimension of the inputs ' 'should be defined. Found `None`.') input_dim = input_shape[channel_axis] num_basis = K.int_shape(self.kernelB)[-1] kernel_shape = (num_basis, input_dim, self.num_filters) self.kernelA = self.add_weight(shape=kernel_shape, initializer=RandomUniform(minval=-1.0, maxval=1.0, seed=None), name='kernelA', regularizer=self.kernel_regularizer, constraint=self.kernel_constraint) self.kernel = K.sum(self.kernelA[None, None, :, :, :] * self.kernelB[:, :, :, None, None], axis=2) # Set input spec. self.input_spec = InputSpec(ndim=self.rank + 2, axes={channel_axis: input_dim}) self.built = True super(CustConv2D, self).build(input_shape) I use the CustomConv2D as the first Conv layer of my model. img = Input(shape=(width, height, 1)) l1 = CustConv2D(filters=64, kernel_size=(11, 11), kernelB=basis_L1, activation='relu')(img) The model compiles fine; but gives me the following error while training. ValueError: An operation has None for gradient. Please make sure that all of your ops have a gradient defined (i.e. are differentiable). Common ops without gradient: K.argmax, K.round, K.eval. Is there a way to figure out which operation is throwing the error? Also, is there any implementation error in the way I am writing the custom layer?
possible better answer: http://stackoverflow.com/a/56351780
tagged with: tensorflow
has answer: http://stackoverflow.com/a/56351780
has answer: http://stackoverflow.com/a/51305712
score: 2
has title: Keras Custom Layer ValueError: An operation has `None` for gradient.
downvote count: 0
tagged with: keras
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51305712
favorite count: 0
type: Question

http://stackoverflow.com/a/51302332
has comment: http://stackoverflow.com/comment/89584792
has comment: http://stackoverflow.com/comment/89586424
type: Answer
has comment: http://stackoverflow.com/comment/89584972
has body: You can just use a normal for loop instead of a for-each loop: with open(filepath) as f: lines = f.readlines() for i in range(len(lines)): if re.match(my_keyword, lines[i]): # do something i += 10 It will use more memory than what you're doing currently, though, because you're reading the entire file into memory at once. Something to keep in mind. Alternatively, if reading the entire file into memory is a problem, you could hack something together: with open(filepath) as f: skip = 0 for line in f: if skip &lt;= 0: if re.match(my_keyword, line): skip = 10 else: skip -= 1 print(line) # The next ten lines after a match can be processed here
has comment: http://stackoverflow.com/comment/89585783
has comment: http://stackoverflow.com/comment/89585310
answers question: http://stackoverflow.com/q/51302203
has comment: http://stackoverflow.com/comment/89585390
score: 0

http://stackoverflow.com/q/51263248
has title: Splunk Custom Module
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/51483620
has body: I am new in Splunk - as well as in Python and start working on Splunk Custom Module and I have taken reference from Splunk Site Custom Module. When I have created Same file structure using Visual Studio 2017 -> Python3 then its give me an error import controllers.module not found import splunk not found import splunk.search not found import splunk.util not found import splunk.entity not found import json from splunk.appserver.mrsparkle.lib not found import lib.util as util not found Note: I have already imported Splunk SDK using "pip install splunk-sdk" Still, I can't find any package in the project. Please, anyone, guide me how to resolve above custom module package error. If there is any readymade samples are available then please suggest a link. Thanks in advance
tagged with: splunk-sdk
score: 0
has answer: http://stackoverflow.com/a/51266303
type: UnansweredQuestion
tagged with: splunk
tagged with: python

http://stackoverflow.com/q/51254860
has title: How can i look at tensorflow hub model arheticture?
favorite count: 0
score: 0
has body: I want to copy the code for mobile net v2 96x96 layers, define my own model and train from zero, how can I do it? https://www.tensorflow.org/hub/modules/google/imagenet/mobilenet_v2_100_96/feature_vector/2 https://tfhub.dev/google/imagenet/mobilenet_v2_100_96/feature_vector/2
answer count: 1
type: UnansweredQuestion
upvote count: 1
tagged with: python
downvote count: 1
tagged with: tensorflow-hub
has answer: http://stackoverflow.com/a/51527349
tagged with: tensorflow
type: Question

http://stackoverflow.com/q/51187571
has body: I want to construct a new tensor y with shape (b,n,c) from an existing tensor x with shape (b,m,c) with m&lt;n and an index tensor idx with shape (b,m) which tells me for each row in x (length c) where to put it in y. Example with numpy: import numpy as np b=2 n=100 m=4 c=3 idx=np.array([[0,31,5,66],[1,73,34,80]]) # shape b x m x=np.random.random((b,m,c)) y=np.zeros((b,n,c)) for i,cur_idx in enumerate(idx): y[i,cur_idx]=x[i] This results in an array y which has zeros everywhere except at the positions given by idx where the value from x are inserted. I need help to "translate" this code fragment into tensorflow. Edit: I do not want to create a variable but rather a constant tensor so tf.scatter_update cannot be used.
type: Question
type: AnsweredQuestion
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/51188184
favorite count: 0
has comment: http://stackoverflow.com/comment/89357805
tagged with: python
has comment: http://stackoverflow.com/comment/89357895
accepted answer: http://stackoverflow.com/a/51188184
score: 1
upvote count: 1
has title: Construct a new tensor from two existing ones in tensorflow
tagged with: tensorflow

http://stackoverflow.com/comment/89340605
type: Comment
comment on: http://stackoverflow.com/a/51178919
has text: @Aran-Fey Presumably, it has some extra logic in it, or is used from a higher level of abstraction.
type: AnswerComment
score: 0

http://stackoverflow.com/a/52795847
answers question: http://stackoverflow.com/q/51224154
has body: Looking at all overloads of add_overlay() method, it is clear that it does not take thickness as a parameter. From documentation - add_overlay(self: dlib.image_window, rectangles: dlib.rectangles, color: dlib.rgb_pixel=rgb_pixel(255,0,0)) -> None Add a list of rectangles to the image_window. They will be displayed as red boxes by default, but the color can be passed. add_overlay(self: dlib.image_window, rectangle: dlib.rectangle, color: dlib.rgb_pixel=rgb_pixel(255,0,0)) -> None Add a rectangle to the image_window. It will be displayed as a red box by default, but the color can be passed. add_overlay(self: dlib.image_window, rectangle: dlib.drectangle, color: dlib.rgb_pixel=rgb_pixel(255,0,0)) -> None Add a rectangle to the image_window. It will be displayed as a red box by default, but the color can be passed. add_overlay(self: dlib.image_window, detection: dlib.full_object_detection, color: dlib.rgb_pixel=rgb_pixel(0,0,255)) -> None Add full_object_detection parts to the image window. They will be displayed as blue lines by default, but the color can be passed. add_overlay(self: dlib.image_window, line: dlib.line, color: dlib.rgb_pixel=rgb_pixel(255,0,0)) -> None Add line to the image window. add_overlay(self: dlib.image_window, objects: list, color: dlib.rgb_pixel=rgb_pixel(255,0,0)) -> None
score: 0
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/51224154

http://stackoverflow.com/comment/89485886
has text: Was the result from `system` 1024?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51253378

http://stackoverflow.com/comment/89327570
has text: Can you explain what the above code suppose to achieve? Without that information how can someone explain what is the purpose of setting i to the min child?
comment on: http://stackoverflow.com/q/51172403
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/comment/89633988
comment on: http://stackoverflow.com/a/51314379
type: AnswerComment
has text: @But why do you think mainWindow.update() is bad solution? I mean it's working fine for me.
score: 0
type: Comment

http://stackoverflow.com/comment/89338877
score: 0
has text: `subprocess.Popen`
comment on: http://stackoverflow.com/q/51178115
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51241012
tagged with: amazon-ec2
has answer: http://stackoverflow.com/a/69533283
tagged with: amazon-web-services
has answer: http://stackoverflow.com/a/51245085
favorite count: 0
has comment: http://stackoverflow.com/comment/89468196
tagged with: python
has title: aws: boto3 get all instances of a load balancers
has comment: http://stackoverflow.com/comment/89467793
type: Question
type: AnsweredQuestion
tagged with: elastic-load-balancer
score: 7
has body: I can able to get the load balancers using below import boto3 elb = boto3.client('elbv2') lbs = elb.describe_load_balancers() How to get the instances of the lbs. Also How Can I fetch the load balancers which state is not active as describe_load_balanacers only give state active load balanceres.
tagged with: boto3
accepted answer: http://stackoverflow.com/a/51245085
upvote count: 8
answer count: 2
possible better answer: http://stackoverflow.com/a/69533283
downvote count: 1
has comment: http://stackoverflow.com/comment/89468298

http://stackoverflow.com/comment/89371076
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51194499
type: Comment
has text: hmmmm, the only think comes to mind is if you use `try` and `except` and do the above for all your possible formats

http://stackoverflow.com/comment/89454479
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51237625
has text: The output is still: `Index: [2 22 22, 3 33 33, 4 44 44, 5 55 55, 6 66 66]` The file isn't in any particular format.So, it's just spaces. I'm not sure if it recognizes the first space as column 1?

http://stackoverflow.com/comment/89382152
has text: Will this actually raise an `ImportError` rather than just setting `rapidjson` to `None`? If so, it’s a nifty solution, probably simpler than mocking the importer.
comment on: http://stackoverflow.com/a/51200157
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/115645022
type: Comment
has text: That was invalid closed bug !
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/65391616

http://stackoverflow.com/comment/89545161
type: Comment
comment on: http://stackoverflow.com/q/51283580
type: QuestionComment
has text: i agree with you
score: 0

http://stackoverflow.com/a/51320776
has comment: http://stackoverflow.com/comment/89619258
accepted answer of: http://stackoverflow.com/q/51320142
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51320142
score: 0
type: Answer
has body: You need insert with GroupBy.transform of size: df.insert(2, 'Count', df.groupby(['Group','Size'])['Size'].transform('size')) print (df) Group Size Count Some_other_column1 Some_other_column2 0 Short Small 2 blabla1 blabla6 1 Moderate Medium 1 babla3 blabla8 2 Short Small 2 blabla2 blabla7 3 Moderate Small 1 blabla4 blabla9 4 Tall Large 1 blabla5 blabla10 5 Short Medium 1 blabla11 blabla12

http://stackoverflow.com/q/51234758
type: Question
tagged with: filtering
tagged with: function
upvote count: 0
tagged with: tags
score: -1
answer count: 1
favorite count: 0
tagged with: beautifulsoup
has comment: http://stackoverflow.com/comment/89448503
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/51235850
has body: I'm scraping an HTML webpage. I'm using the BeautifulSoup lib (4.6.0) and Python (3.7) on a Mac (Sierra). Among other things, I see a bunch of 'div' tags which have class attributes. Some of the 'div' tags come with multiple class attribute values. Now I want to filter based on tag name and class attribute values, e.g. I want to find the 'div' tags that have class='a' but not class='b' (and, yes, some of the div tags come with class='a b'). To get those tags I tried to use a filtering function as mention in the BS4 documentation (https://www.crummy.com/software/BeautifulSoup/bs4/doc/#a-function). I'm under the impression that find_all() passes a bs4 tag element to the function and within the function you can do whatever you would do on a BS4 tag element. That seems not to be true. I get a string and obviously all my BS4 tag element operations raise an exception. Two questions: What exactly does find_all() pass to the function and how can the argument be used? Besides a function how would otherwise be able to achieve the desired functionality?
has title: Filtering function issues in BS4 find_all() statement in Python
downvote count: 1

http://stackoverflow.com/comment/89448998
comment on: http://stackoverflow.com/q/51234995
type: Comment
type: QuestionComment
has text: your sample is a bit confusing, everything is called `Predictions` :) I'm not sure how you can access each information in the object `item` inside your for-loop, could you print a sample of the final`df_list` ?
score: 0

http://stackoverflow.com/q/51258029
downvote count: 0
tagged with: osmnx
possible better answer: http://stackoverflow.com/a/53544161
favorite count: 0
has answer: http://stackoverflow.com/a/53544161
tagged with: python-3.x
has body: I am using OSMNx to plot shortest path routes and I cannot figure out a way to plot multiple routes on the same map. Here's my code so far, route_list = [] for i in range(len(pick_drop_outliers_ratio)): coords = pick_drop_outliers_ratio["Pickup_Points"][i] count = pick_drop_outliers_ratio["Count"][i] print("i: ", i, " count: ", count) if(count&gt;9): coords = literal_eval(coords) pickup_lat = (coords[0][0]) pickup_lon = (coords[0][1]) dropoff_lat = (coords[1][0]) dropoff_lon = (coords[1][1]) orig_node = ox.get_nearest_node(G, (pickup_lat, pickup_lon)) dest_node = ox.get_nearest_node(G, (dropoff_lat, dropoff_lon)) route = nx.shortest_path(G, orig_node, dest_node, weight='length') route_list.append(route) fig, ax = ox.plot_graph_route(G, route_list, node_size=0) I wish to plot every route in route_list on the same map in different colors for each route. Since there is no built in function in OSMNx, is there a way to do this? I found the solution is "plotting the graph then adding routes manually on top with matplotlib." But Could not implement.
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/53708286
has title: Plotting Multiple Routes with OSMNx
score: 7
upvote count: 7
has answer: http://stackoverflow.com/a/51484316
tagged with: osrm
type: Question
tagged with: matplotlib
accepted answer: http://stackoverflow.com/a/53708286
answer count: 3

random-forest
tags question: http://stackoverflow.com/q/51168298
tag name: random-forest
tags question: http://stackoverflow.com/q/51172335
tags question: http://stackoverflow.com/q/51169653
tags question: http://stackoverflow.com/q/51256753
type: Tag
tags question: http://stackoverflow.com/q/51316056
tags question: http://stackoverflow.com/q/51235597

http://stackoverflow.com/comment/89377589
comment on: http://stackoverflow.com/q/51197683
score: 0
type: QuestionComment
has text: it is called "object"
type: Comment

http://stackoverflow.com/comment/89608898
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51315819
has text: @ThomasDickey But surely the version of libncursesw.so.5 used for manylinux wheels is a standard ncurses, not a threaded one with a different API? Or does OpenSUSE just not do manylinux?
score: 0

http://stackoverflow.com/comment/89431047
type: QuestionComment
has text: Readability, for example, if the column names are complicated.
type: Comment
comment on: http://stackoverflow.com/q/51225275
score: 0

http://stackoverflow.com/comment/89443607
type: Comment
has text: @OlivierMelançon: that's handled by `object.__new__`; see [the v3.7.0 implementation](https://github.com/python/cpython/blob/v3.7.0/Objects/typeobject.c#L3671-L3714). The exception is raised for any class with `Py_TPFLAGS_IS_ABSTRACT` set. The flag is set when `__abstractmethods__` is set to a non-empty value, by `ABCMeta.__new__`.
comment on: http://stackoverflow.com/a/51232156
score: 1
type: AnswerComment

http://stackoverflow.com/comment/89516927
type: QuestionComment
comment on: http://stackoverflow.com/q/51268802
has text: Can you post the code you have?
score: 0
type: Comment

http://stackoverflow.com/comment/89558509
score: 0
type: QuestionComment
type: Comment
has text: You mention a websocket solution "would be outstanding" - you could take a look at this repo: https://github.com/jonathonmcmurray/ws.q `wsu.q` & `wschaintick.q` provide the framework for creating a WebSocket chained tickerplant, essentially republishing over websockets. Examples at bottom of README
comment on: http://stackoverflow.com/q/51290256

http://stackoverflow.com/a/51580860
has body: So what does it mean that it is 'built into every python interpreter' ? The sys module is written in C and compiled into the Python interpreter itself. Depending on the version of the interpreter, there may be more modules of this kind — sys.builtin_module_names lists them all. As you have noticed, a built-in module still needs to be imported like any other extension. &gt;&gt;&gt; import sys &gt;&gt;&gt; sys.builtin_module_names ('_ast', '_codecs', '_collections', '_functools', '_imp', '_io', '_locale', '_operator', '_signal', '_sre', '_stat', '_string', '_symtable', '_thread', '_tracemalloc', '_warnings', '_weakref', 'atexit', 'builtins', 'errno', 'faulthandler', 'gc', 'itertools', 'marshal', 'posix', 'pwd', 'sys', 'time', 'xxsubtype', 'zipimport')
score: 2
answers question: http://stackoverflow.com/q/51277119
downvote count: 0
upvote count: 2
type: Answer

http://stackoverflow.com/q/51249153
possible better answer: http://stackoverflow.com/a/51249842
tagged with: jenkins
has title: Jenkins job unable to pass integer parameters into python script during build
tagged with: python
type: AnsweredQuestion
type: Question
has body: I have a python script that I tested on an EC2 instance, which works perfectly fine on the server but when I try to pass the same parameters from Jenkins job as shown below. I get the error message: Security Group Created sg-ca09bcae in vpc vpc-d79691b9. Traceback (most recent call last): File "./create_sg.py", line 32, in 'FromPort': int(FROM_PORT_1.strip("")), marked build as failure Finished: FAILURE> ValueError: invalid literal for int() with base 10: 'within' Build step 'Execute shell' I'm pretty sure the error is because of the string parameter that I'm passing through Jenkins parameters but there isn't an option to send both From and To ports as integers in jenkins parameters. How can I set the parameters to an integer within Jenkins build job? Python code to create SG: #!/usr/bin/env python import sys import boto3 from botocore.exceptions import ClientError region = "us-west-1" VPC_ID=sys.argv[1] SECURITY_GROUP_NAME=sys.argv[2] DESCRIPTION=sys.argv[3] IP_PROTOCOL_1=sys.argv[4] FROM_PORT_1=sys.argv[5] TO_PORT_1=sys.argv[6] CIDR_IP_1=sys.argv[7] ec2 = boto3.client('ec2') response = ec2.describe_vpcs() vpc_id = VPC_ID try: response = ec2.create_security_group(GroupName=SECURITY_GROUP_NAME,Description=DESCRIPTION,VpcId=VPC_ID) security_group_id = response['GroupId'] print('Security Group Created %s in vpc %s.' % (security_group_id, vpc_id)) data = ec2.authorize_security_group_ingress( GroupId=security_group_id, IpPermissions=[ {'IpProtocol': IP_PROTOCOL_1, 'FromPort': int(FROM_PORT_1), 'ToPort': int(TO_PORT_1), 'IpRanges': [{'CidrIp': CIDR_IP_1}]} ] ) print('Ingress Successfully Set %s' % data) except ClientError as e: print(e) @nosklo, Suggested I try the following: VPC_ID=sys.argv[1] SECURITY_GROUP_NAME=sys.argv[2] DESCRIPTION=' '.join(sys.argv[3:-4]) IP_PROTOCOL_1=sys.argv[-4] FROM_PORT_1=sys.argv[-3] TO_PORT_1=sys.argv[-2] CIDR_IP_1=sys.argv[-1] With which the ports are listed as 0 vs the values that I passed in the parameters.
tagged with: boto3
tagged with: amazon-web-services
accepted answer: http://stackoverflow.com/a/51249906
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/51249842
has answer: http://stackoverflow.com/a/51249906
tagged with: python-3.x

http://stackoverflow.com/a/51182201
has comment: http://stackoverflow.com/comment/89347032
upvote count: 19
answers question: http://stackoverflow.com/q/51182182
score: 19
has body: You can using startswith df[~df.Team.str.startswith('Fin')] Or df[~df.Team.str.contains('Fin')]
downvote count: 0
has comment: http://stackoverflow.com/comment/89348276
type: Answer
has comment: http://stackoverflow.com/comment/89348262

http://stackoverflow.com/a/51243988
score: 1
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51243666
type: Answer
answers question: http://stackoverflow.com/q/51243666
downvote count: 0
has body: I will quote from the documentation.Refer the code to understand better. time.strftime(format) Return a string representing the time, controlled by an explicit format string. For a complete list of formatting . &gt;&gt;&gt; t = time(12, 10, 30, tzinfo=GMT1()) &gt;&gt;&gt; t.strftime("%H:%M:%S %Z") '12:10:30 Europe/Prague' datetime.strftime(format) Return a string representing the date and time, controlled by an explicit format string. &gt;&gt;&gt; dt = datetime.strptime("21/11/06 16:30", "%d/%m/%y %H:%M") &gt;&gt;&gt; dt.strftime("%A, %d. %B %Y %I:%M%p") 'Tuesday, 21. November 2006 04:30PM' date.strftime(format) Return a string representing the date, controlled by an explicit format string. Format codes referring to hours, minutes or seconds will see 0 values. &gt;&gt;&gt; d = date.fromordinal(730920) &gt;&gt;&gt; d.strftime("%d/%m/%y") '11/03/02' &gt;&gt;&gt; d.strftime("%A %d. %B %Y") 'Monday 11. March 2002'

http://stackoverflow.com/comment/90033760
type: QuestionComment
has text: Morgen! _ROBOTSTXT_OBEY_ is set to true_. Does is not correct? Thank you for your help.
comment on: http://stackoverflow.com/q/51253538
score: 0
type: Comment

http://stackoverflow.com/q/51211034
tagged with: transform
has title: Pandas minute-data find- first local min between now and first occurrence of (threshold) condition
upvote count: 2
has body: Looking to find the first occurrence from current time for each row until the end of the date where the value passes some threshold thresh = 0.10 creating dataframe columns for the min inside that window Input timestamp date value endofdaytime 2018-03-11 13:03:00 2018-03-11 0.03 2018-03-11 16:29:52 2018-03-11 13:08:00 2018-03-11 0.00 2018-03-11 16:29:52 2018-03-11 15:22:00 2018-03-11 0.11 2018-03-11 16:29:52 2018-03-11 16:03:00 2018-03-11 0.03 2018-03-11 16:29:52 2018-03-11 16:29:52 2018-03-11 0.03 2018-03-11 16:29:52 2018-03-12 13:03:00 2018-03-12 0.03 2018-03-12 16:29:59 2018-03-12 13:08:00 2018-03-12 0.00 2018-03-12 16:29:59 2018-03-12 16:03:00 2018-03-12 0.03 2018-03-12 16:29:59 2018-03-12 16:29:59 2018-03-12 0.12 2018-03-12 16:29:59 output timestamp date value endofdaytime min2thresh thresh 2018-03-11 12:34:00 2018-03-11 0.22 2018-03-11 16:29:52 0.00 0.11 2018-03-11 13:03:00 2018-03-11 0.00 2018-03-11 16:29:52 0.00 0.11 2018-03-11 13:08:00 2018-03-11 0.03 2018-03-11 16:29:52 0.03 0.11 2018-03-11 15:22:00 2018-03-11 0.11 2018-03-11 16:29:52 0.04 0.12 2018-03-11 16:03:00 2018-03-11 0.04 2018-03-11 16:29:52 0.12 0.12 2018-03-11 16:29:52 2018-03-11 0.12 2018-03-11 16:29:52 NaN NaN 2018-03-12 13:03:00 2018-03-12 0.03 2018-03-12 16:29:59 0.00 0.13 2018-03-12 13:08:00 2018-03-12 0.00 2018-03-12 16:29:59 0.00 0.13 2018-03-12 16:03:00 2018-03-12 0.03 2018-03-12 16:29:59 0.03 0.13 2018-03-12 16:29:59 2018-03-12 0.13 2018-03-12 16:29:59 NaN NaN This code will get me the min until the end of the date. df['min2thresh'] = df.groupby('date')['value'].transform(lambda x: x[::-1].cummin()[::-1]) But only want the min until the threshold is passed. So I assume I need to change the -1 in [::-1] to a method to find the first location of that threshold. Perhaps.. [:: df.loc[(df["value"] &gt;= thresh)]] So that would be df['min2thresh'] = df.groupby('date')['value'].transform(lambda x: x[::df.loc[(df["value"] &gt;= thresh)]].cummin()[::df.loc[(df["value"] &gt;= thresh)]]) But that c…
tagged with: pandas
favorite count: 0
type: UnansweredQuestion
tagged with: python
score: 2
answer count: 0
downvote count: 0
type: Question

http://stackoverflow.com/q/51251355
favorite count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: python
score: 1
downvote count: 1
has body: Having trouble with reading a csv file into a pandas dataframe where the line endings are not standard. Here is my code: df_feb = pd.read_csv(data_location, sep = ",",nrows = 500, header = None, skipinitialspace = True,encoding = 'utf-8') Here is the output (personal info scratched out): Output This is what the input data looks like: The above output splits what should be a single line into 4 lines. A new line should start for every phone number (phone number = scratched out bit). I am aiming to have each line look like this: Goal output Thank you in advance for your help!
type: Question
has title: Read_csv in Pandas where file structure is inconsistent
has comment: http://stackoverflow.com/comment/89482272
has answer: http://stackoverflow.com/a/51967978
tagged with: pandas
answer count: 1
tagged with: opencsv
has comment: http://stackoverflow.com/comment/89503760

http://stackoverflow.com/q/51228818
has title: Pandas merge multiple times generates a _x and _y columns
has answer: http://stackoverflow.com/a/51228868
accepted answer: http://stackoverflow.com/a/51228868
linked to: http://stackoverflow.com/q/51226423
tagged with: python
has body: I have 2 dataframes where I found common matches based on a column (tld), if a match is found (between a column in source and destination) I copied the value of column (uuid) from source to the destination dataframe. Now I also need to check if a different column is a match. (company_name) Dataframe 1: source uuid website company_name tld 0 11 www.facebook.com facebook facebook.com 1 22 www.yahoo.com yahoo inc yahoo.com 2 33 www.google.com Google google.com 3 44 www.cisco.com Cisco cisco.com Dataframe 2: destination id website company_name tld match uuid 0 a www.facebook.com facebook facebook.com False NaN 1 b www.y.com Yahoo Inc y.com False NaN 2 c www.g.com Google g.com False NaN 3 d www.g.com Google Inc g.com False NaN 4 e www.facebook.com Facebook Inc facebook.com False NaN Find matches: destination.loc[destination.tld.isin(source.tld),'match'] = True destination = destination.merge(source'tld', 'uuid', on='tld', how='left') The above copy the UUID column from source into the UUID column in the destination dataframe. id website company_name tld match uuid 0 a www.facebook.com facebook facebook.com True 11 1 b www.y.com YahooInc y.com False NaN 2 c www.g.com Google g.com False NaN 3 d www.g.com GoogleInc g.com False NaN 4 e www.facebook.com FacebookInc facebook.com True 11 Now I need to check if company_name is a match as well to have something like this: id website company_name tld match uuid 0 a www.facebook.com facebook facebook.com True 11 1 b www.y.com YahooInc y.com False NaN 2 c www.g.com Google g.com True 33 3 d www.g.com GoogleInc g.com False NaN 4 e www.facebook.com FacebookInc facebook.com True 11 When I try to add: destination.loc[destination.company_name.isin(source.company_name), 'match'] = True destination = destination.merge(source'company_name', 'uuid', on='company_name', how='left') I get a duplicated uuid column: uuid_x and uuid_y id website company_name tld match uuid_x uuid_y 0 a www.facebook.com facebook facebook.com True 11 11 1 b w…
type: AnsweredQuestion
type: Question
tagged with: dataframe
score: 0
tagged with: pandas
answer count: 1

http://stackoverflow.com/comment/89471832
has text: The same method applies here as the answer provided by jezrael in your [previous post](https://stackoverflow.com/questions/43347939/all-possible-combinations-of-columns-in-dataframe-pandas-python) - you just need to tweek the `concat` part to the following: `df = pd.concat([(2*df[c[1]]).sub(df[c[0]]+df[c[2]]) for c in cc], axis=1, keys=cc)`
score: 0
type: Comment
comment on: http://stackoverflow.com/q/51246224
type: QuestionComment

http://stackoverflow.com/q/51318988
has comment: http://stackoverflow.com/comment/90927551
tagged with: python
tagged with: logging
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51412072
has title: Why Flask logger does not log in docker when using UWSGI in front?
possible better answer: http://stackoverflow.com/a/62500365
has comment: http://stackoverflow.com/comment/89678210
has comment: http://stackoverflow.com/comment/89782665
has answer: http://stackoverflow.com/a/62500365
has comment: http://stackoverflow.com/comment/89682653
tagged with: uwsgi
has body: I have a Flask application inside of Docker that was logging into docker logs when it was running without UWSGI in front. Now I have used UWSGI with the config below to run my application inside of Docker: [uwsgi] master = true processes = 5 threads = 2 socket = 127.0.0.1:3031 chmod-socket = 664 stats=0.0.0.0:30310 chdir = /etc/fantas uid = root gid = root wsgi-file=uwsgi_fantas.py callable=app vacuum = true The uwsgi_fantas.py file contains: from fantas.fantas_app import FantasApp app = FantasApp().setup() The setup method returns app: from flask_restful import Api from fantas import app class FantasApp(object): def setup(self): api = Api(app) api.add_resource(Token, '/users') return app Finally the part that initiates the Flask framework is inside of __init__.py in the root directory of project: from flask import Flask import logging app = Flask(__name__) s_handler = logging.StreamHandler() s_handler.setLevel(logging.DEBUG) app.logger.addHandler(s_handler) As UWSGI works directly with the app object I have configured logger inside of __init__.py, but the problem is that it does not log anything into Docker when it is run, it just logs UWSGI requests. What is wrong in the process of app.logger configuration? Problem has been solved, but now logs get duplicated! EDIT-1: I set app.logger.setLevel(logging.DEBUG) and it seems that Flask logs into Docker successfully. The weird part is that it logs 3 times! I removed all logger configs and handlers and just used: app.logger.setLevel(logging.DEBUG) But now it logs 2 times: proj_fantas.1.huagnqqpzo1n@linuxkit-025000000001 | [2018-07-13 07:02:38,008] DEBUG in token: [Token] authenticating user... proj_fantas.1.huagnqqpzo1n@linuxkit-025000000001 | DEBUG:flask.app:[Token] authenticating user... Why it is like that? EDIT-2: The output of app.logger.handlers is [&lt;logging.StreamHandler object at 0x7f0f430ca8d0&gt;]. It just shows the StreamHandler that I initialized earlier, nothing more. EDIT-3: The output of ps -ef command…
type: Question
has comment: http://stackoverflow.com/comment/89760210
upvote count: 22
answer count: 2
has comment: http://stackoverflow.com/comment/89747867
tagged with: flask
score: 22
tagged with: docker
has comment: http://stackoverflow.com/comment/89747774
has comment: http://stackoverflow.com/comment/89673473
has answer: http://stackoverflow.com/a/51412072
downvote count: 0
has comment: http://stackoverflow.com/comment/89682678
has comment: http://stackoverflow.com/comment/89796291
linked to: http://stackoverflow.com/q/21127360
favorite count: 0

http://stackoverflow.com/q/51179649
linked to: http://stackoverflow.com/q/22354094
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/89341914
has title: Function to remove outliers in python
answer count: 2
has answer: http://stackoverflow.com/a/51185798
favorite count: 0
tagged with: statistics
tagged with: python-2.7
tagged with: pandas
tagged with: python-3.x
downvote count: 0
has body: I am trying to write a function to update all the outliers in all the columns in a dataset with the interquartile range. It is working when I pass a column as input but if I add another loop to iterate through all the columns its not working. df2ColumnNames=df2.columns def fixoutliers(x): for i in df2ColumnNames: print("colnames ",i) xy=x[i] print(xy) updated=[] Q1,Q3=np.percentile(xy,[25,75]) IQR=Q3-Q1 #print(IQR) minimum=Q1-1.5*IQR maximum=Q3+1.5*IQR print("maximum",maximum) for i in xy: if(i&gt;maximum): i=maximum updated.append(i) elif(i&lt;minimum): i=minimum updated.append(i) else: print("In else") updated.append(i) return updated
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51183773
tagged with: python
score: 2

http://stackoverflow.com/comment/89614877
comment on: http://stackoverflow.com/a/51291703
type: AnswerComment
type: Comment
score: 11
has text: I need logs from lambda but dont require those default log messages from lambda.

http://stackoverflow.com/q/51322864
has answer: http://stackoverflow.com/a/51323462
score: 0
tagged with: python-import
answer count: 1
has title: Variable in python script is changing, but when I import the varibale it is every time the same
tagged with: variables
has comment: http://stackoverflow.com/comment/89621106
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89621000
has body: I have a two scripts. In one there happens a lot of stuff and there is one variable I am interested in: Called satisfaction In the other programme I am executing the first several times and each time I have to check, if the value of satisfaction has changed. But, it imports always the same value for satisfaction, even it changed. Here is the Code of the second script: for i in range(10): subprocess.call('python main.py', shell=True) from main import satisfaction print('SATISFACTION:',satisfaction) in the first round, it imports the value, but then it do not change it.. First round: Output 1. script: satisfaction: 0.6499999999999999 Output 2. script: SATISFACTION: 0.6499999999999999 Second round: Output 1. script: satisfaction: 0.625 Output 2. script: SATISFACTION: 0.6499999999999999 Third round: Output 1. script: satisfaction: 0.75 Output 2. script: SATISFACTION: 0.6499999999999999 And so on... I would be really thankfull, if somebody could help me, Justus
tagged with: loops
accepted answer: http://stackoverflow.com/a/51323462
type: Question

http://stackoverflow.com/comment/89534362
has text: http://scipy.github.io/old-wiki/pages/EricsBroadcastingDoc
comment on: http://stackoverflow.com/q/51277646
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89612869
score: 1
has text: that tuple unpacking, solid stuff.
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51318316

http://stackoverflow.com/q/51287148
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89552623
has comment: http://stackoverflow.com/comment/89551987
upvote count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/51287228
type: Question
has comment: http://stackoverflow.com/comment/89551864
has title: How do I join these two DataFrames on shared values in a column using pandas?
tagged with: python-2.7
score: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/89551816
accepted answer: http://stackoverflow.com/a/51287228
answer count: 1
has comment: http://stackoverflow.com/comment/89561539
has body: I have a dataframe like the following (df1)- read_year read_month load trading_block 0 2017 3 0.019582 0 1 2017 3 0.019460 0 2 2017 3 0.018888 0 3 2017 3 0.018940 0 4 2017 3 0.019114 0 And another like the following (df2)- read_year read_month lmp trading_block 0 2009 1 37.5694 0 1 2009 1 34.5777 0 2 2009 1 33.7039 0 3 2009 1 33.1503 0 4 2009 1 33.8935 0 What I want is for df2 to merge/join/concat (whichever one works) on only the years that match- read_year. The expected output should look like the following- read_year read_month load trading_block lmp 0 2017 3 0.019582 0 32.1201 1 2017 3 0.019460 0 12.1230 2 2017 3 0.018888 0 40.2941 3 2017 3 0.018940 0 20.3918 4 2017 3 0.019114 0 50.9371 How do I go about doing this easily?
favorite count: 0
tagged with: python

http://stackoverflow.com/a/51190951
answers question: http://stackoverflow.com/q/51190740
score: 2
has body: This is a way you can sort of force the NumPy API to do this, although it probably will not be too different from doing it yourself: import numpy as np # Make one-dimensional array of lists of strings a = np.array([None, None]) a[0] = ['a', 'b', 'c'] a[1] = ['e', 'f', 'g'] # Join print(np.char.join(' ', a)) &gt;&gt;&gt; ['a b c' 'e f g']
has comment: http://stackoverflow.com/comment/89372530
downvote count: 0
upvote count: 2
type: Answer

http://stackoverflow.com/q/51213768
type: Question
tagged with: nltk
downvote count: 0
answer count: 1
score: 1
favorite count: 0
tagged with: hidden-markov-models
has title: Get transition probability, emission(output) probability, and initial probability from hmm nltk
has body: I have successfully implementing hidden markov model for pos tagging with library from NLTK HMM Tagger and now I want to know every probability that was used in the tagging process for every word,tag. From what I read there are transition probability, emission probability, initial start probability, and probability of the tag. How to get those probability? I searched the internet and can't find it. I want validate the tagging result with my own calculation and it is too many if i count one by one every word and tag probability because the size of my corpus is big.
tagged with: python
type: UnansweredQuestion
tagged with: probability
upvote count: 1
has answer: http://stackoverflow.com/a/51312231

http://stackoverflow.com/comment/89498843
score: 1
has text: @Johnbosco: you can patch it on whatever level you want. At the `FooBarMixin`, or at `Foo`, if you only want that behavior for `Foo`s.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51260225

http://stackoverflow.com/a/51218478
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51218205
score: 1
has comment: http://stackoverflow.com/comment/89488196
has comment: http://stackoverflow.com/comment/89488148
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89486751
has body: Give each employee a manager attribute, and set this in Manager.add_emp(). Then Supervisor.add_emp() can get the supervisor's manager, and call add_emp() on that manager. class Employee: num_of_emps = 0 raise_amount = 1 def __init__(self, first, last, id, pay): self.first = first self.last = last self.id = id self.pay = pay self.manager = None def set_manager(self, mgr): self.manager = mgr class Manager(Employee): raise_amount = 1.08 def __init__(self, first, last, id, pay, emp_under_sup = None): super().__init__(first, last, id, pay) if emp_under_sup is None: self.emp_under_sup = [] else: self.emp_under_sup = emp_under_sup def add_emp(self, emp): if emp not in self.emp_under_sup: self.emp_under_sup.append(emp) emp.set_manager(self) class Supervisor(Employee): raise_amount = 1.06 def __init__(self, first, last, id, pay, emp_under_sup = None): super().__init__(first, last, id, pay) if emp_under_sup is None: self.emp_under_sup = [] else: self.emp_under_sup = emp_under_sup def add_emp(self, emp): if emp not in self.emp_under_sup: self.emp_under_sup.append(emp) if self.manager: self.manager.add_emp(emp)
upvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/89488163
answers question: http://stackoverflow.com/q/51218205

http://stackoverflow.com/q/51200630
answer count: 1
tagged with: crop
score: 0
tagged with: python
has title: How do you detect and crop multiple images on a single white background using PIL?
type: UnansweredQuestion
tagged with: whitespace
type: Question
tagged with: python-imaging-library
tagged with: image
has comment: http://stackoverflow.com/comment/89382889
has body: I have just started using PIL and I need help with detecting and cropping out multiple images on a single white background using PIL. They can be different sizes and be in different locations. Right now, I can only crop out one image. Please help, Thank you! def trim(im): bg = Image.new(im.mode, im.size, im.getpixel((0,0))) diff = ImageChops.difference(im, bg) diff = ImageChops.add(diff, diff, 2.0, -100) bbox = diff.getbbox() if bbox: return im.crop(bbox) else: print("No image detected") image1 = Image.open('multiple.jpg') image2 = test(image1)
has answer: http://stackoverflow.com/a/51566727

http://stackoverflow.com/a/51179193
answers question: http://stackoverflow.com/q/51179120
upvote count: 3
type: AcceptedAnswer
type: Answer
score: 3
downvote count: 0
has body: In File -> Settings -> Keymap you can modify the shortcuts the way you want.
accepted answer of: http://stackoverflow.com/q/51179120

http://stackoverflow.com/q/51178081
has comment: http://stackoverflow.com/comment/89347985
upvote count: 1
downvote count: 1
type: Question
has body: In config.py, I have: config = 0 #config = [] def init_config(): global config config = 1 #config.append("1") print("init", config) In main.py, I have: from config import init_config from config import config def main(): init_config() print("main", config) if __name__ == '__main__': main() And both the config.py and the main.py in the same directory. After running python main.py, I got: init 1 main 0 But if I use the comment lines in the config.py instead, I got: init ['1'] main ['1'] So why does the difference happen? (Python 3.5.5)
has answer: http://stackoverflow.com/a/51178174
has comment: http://stackoverflow.com/comment/89338822
score: 0
has title: Global variable sharing across different modules behave differently
answer count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/51178174
tagged with: python
linked to: http://stackoverflow.com/q/13034496
type: AnsweredQuestion

http://stackoverflow.com/q/51321411
has title: multiple-variable (2d) explorations in pandas
accepted answer: http://stackoverflow.com/a/51321528
tagged with: pandas
type: AnsweredQuestion
favorite count: 0
tagged with: data-analysis
type: Question
has body: Dears, I have a project from Udacity "the Data Analyst Nanodegree" , in this project I am supposed to analyse and explore the IMDB data to answer a set of questions decided by me. it seems all the questions and analysis I have submitted are 1 dimensional (1d) or 1 variable data exploration, and one of the project requirements is to submit 1d and 2d data exploration. therefore I need your kind support to understand multiple-variable (2d) explorations.
tagged with: seaborn
tagged with: data-visualization
upvote count: 1
tagged with: python
answer count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/51321528
score: 0

http://stackoverflow.com/q/51241103
tagged with: floating-accuracy
has answer: http://stackoverflow.com/a/52069746
tagged with: python
has comment: http://stackoverflow.com/comment/89522548
favorite count: 0
has comment: http://stackoverflow.com/comment/89461791
upvote count: 2
tagged with: numerical-analysis
type: UnansweredQuestion
tagged with: floating-point
has body: Consider this difference equation: The solution is I am trying to solve it numerically in python, to explicate issues that arise with floating point computations. I wrote a function that computes xn+1 def diff(n): c = 1 b = -1/5.0 a = 0 for i in xrange(n): a = 14/5.0*b+3/5.0*c b, c = a, b return a but I don't know how to solve this numerically and then to explain why python can not provide the xn = (-1/5)n solution. I can see that for larger n, the return value of my function diverges from the true value.
score: 2
has comment: http://stackoverflow.com/comment/89524989
type: Question
linked to: http://stackoverflow.com/q/11256433
answer count: 1
downvote count: 0
has title: How to solve difference equations numerically in python

http://stackoverflow.com/q/51271691
answer count: 1
favorite count: 0
tagged with: beautifulsoup
tagged with: http://stackoverflow.com/tag/html
tagged with: python
tagged with: css
type: UnansweredQuestion
tagged with: web-scraping
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/53937694
has body: I'm trying to scrape 11 fields from a standard SEC filing on EDGAR (SEC.gov) and return them to a simple dictionary. When I run the code below, 7 of the fields work fine, but 4 of the fields (named in the code as "Director", "Officer", "Person", and "Ticker") return an empty list value in spite of showing actual text in these fields on the page and I cannot figure out how to resolve. I obtained the CSS selector info for these fields using DevTools in Chrome and viewing the Elements tab while on the page I'm trying to scrape. One thing to note is that these 4 fields have longer CSS selectors than the ones that work correctly (i.e. the "tree" describing the location on the page is longer than the others) so I feel there must be something I'm doing wrong syntax-wise in pointing to these 4 fields. As a side note I'm new to Python, and early in the process of working on this I learned that with Beautiful Soup the CSS selector references must use "nth-of-type" instead of "nth-child", so I've already made those changes to my code. I'm at a loss as to why these 4 fields won't return the data shown on the form, while the other 7 work fine. Any help or guidance would be much appreciated! Note: I'm using Python 3. import bs4, requests, pprint def getFormData(form4url): res = requests.get(form4url) res.raise_for_status() soup = bs4.BeautifulSoup(res.text, 'html.parser') # scrape the data from each field of the SEC Form 4 document. Each field is identified by its # CSS selector from the web page's html (viewed using DevTools -&gt; Elements tab in Chrome) person = soup.select('body &gt; table:nth-of-type(2) &gt; tbody &gt; tr:nth-of-type(1) &gt; td:nth-of-type(1) &gt; table:nth-of-type(2) &gt; tbody &gt; tr &gt; td &gt; a') ticker = soup.select('body &gt; table:nth-of-type(2) &gt; tbody &gt; tr:nth-of-type(1) &gt; td:nth-of-type(2) &gt; span.FormData') director = soup.select('body &gt; table:nth-of-type(2) &gt; tbody &gt; tr:nth-of-type(1) &gt; td:nth-of-type(3) &gt; table &gt; t…
has title: Beautiful Soup web scraping with CSS selectors
type: Question
upvote count: 1
has comment: http://stackoverflow.com/comment/89594259

http://stackoverflow.com/q/51220918
has title: Python: Plot residuals on a fitted model
score: 5
upvote count: 5
downvote count: 0
has comment: http://stackoverflow.com/comment/89423542
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/51221620
tagged with: python
has body: I want to plot the lines (residuals; cyan lines) between data points and the estimated model. Currently I'm doing so by iterating over all data points in my income pandas.DataFrame and adding vertical lines. x, y are the points' coordinates and predicted are the predictions (here the blue line). plt.scatter(income["Education"], income["Income"], c='red') plt.ylim(0,100) for indx, (x, y, _, _, predicted) in income.iterrows(): plt.axvline(x, y/100, predicted/100) # /100 because it needs floats [0,1] Is there a more efficient way? This doesn't seem like a good approach for more than a few rows.
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51221620
tagged with: matplotlib
type: Question

http://stackoverflow.com/a/51312829
has comment: http://stackoverflow.com/comment/89602910
answers question: http://stackoverflow.com/q/51312645
upvote count: 4
type: AcceptedAnswer
downvote count: 0
score: 4
accepted answer of: http://stackoverflow.com/q/51312645
type: Answer
has body: You ought to use cv2.minMaxLoc(). This will return only one and the best match. min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(results) top_left = max_loc bottom_right = (top_left[0] + w, top_left[1] + h) cv2.rectangle(image.copy(), top_left, bottom_right, 255, 2) **Illustration: ** I have Messi on the football ground as the images and his face as the template. img = cv2.imread('C:/Users/selwyn77/Desktop/messi.jpg', 0) img2 = cv2.imread('C:/Users/selwyn77/Desktop/messi.jpg', 1) template = cv2.imread('C:/Users/selwyn77/Desktop/messi_face.jpg', 0) w, h = template.shape[::-1] #img3 = img2.copy() res = cv2.matchTemplate(img,template,cv2.TM_CCOEFF_NORMED) min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res) top_left = max_loc bottom_right = (top_left[0] + w, top_left[1] + h) cv2.rectangle(img2, top_left, bottom_right, (0, 255, 0), 2) cv2.imshow('img', img2) EDIT: You can set a threshold and check whether max_val is greater than this threshold. If it is greater then proceed to draw the matching region. threshold = 0.85 min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(results) if max_val &gt; threshold: top_left = max_loc bottom_right = (top_left[0] + w, top_left[1] + h) cv2.rectangle(image.copy(), top_left, bottom_right, 255, 2)

http://stackoverflow.com/a/51186964
answers question: http://stackoverflow.com/q/51179133
accepted answer of: http://stackoverflow.com/q/51179133
has comment: http://stackoverflow.com/comment/91041124
upvote count: 12
score: 12
has body: I see you're timing things you shouldn't be timing (definition of dtype, device, ...). What's interesting to time here is the creation of the input, output and weight tensors. startTime = datetime.now() # Create random Tensors to hold input and outputs. x = torch.randn(N, D_in, device=device, dtype=dtype) t = torch.randn(N, D_out, device=device, dtype=dtype) torch.cuda.synchronize() print(datetime.now()-startTime) # Create random Tensors for weights. startTime = datetime.now() w1 = torch.randn(D_in, H, device=device, dtype=dtype, requires_grad=True) w2 = torch.randn(H, D_out, device=device, dtype=dtype, requires_grad=True) w3 = torch.randn(D_out, D_out, device=device, dtype=dtype, requires_grad=True) torch.cuda.synchronize() print(datetime.now()-startTime) and the training loop startTime = datetime.now() for i in range(10000): y_pred = x.mm(w1).clamp(min=0).mm(w2).clamp(min=0).mm(w3) loss = (y_pred - t).pow(2).sum() if i % 1000 == 0: print(i, loss.item()) loss.backward() # Manually update weights using gradient descent with torch.no_grad(): w1 -= learning_rate * w1.grad w2 -= learning_rate * w2.grad # Manually zero the gradients after updating weights w1.grad.zero_() w2.grad.zero_() torch.cuda.synchronize() print(datetime.now() - startTime) Why the GPU is slower I run it on my machine with a GTX1080 and a very good CPU, so the absolute timing is lower, but the explanation should still be valid. If you open a Jupyter notebook and run it on the CPU: 0:00:00.001786 time to create input/output tensors 0:00:00.003359 time to create weight tensors 0:00:04.030797 time to run training loop Now you set device to cuda and we call this "cold start" (nothing has been previously run on the GPU in this notebook) 0:00:03.180510 time to create input/output tensors 0:00:00.000642 time to create weight tensors 0:00:03.534751 time to run training loop You see that the time to run the training loop is reduced by a small amount, but there is an overhead of 3 seconds because you need to …
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/89357038
type: Answer

http://stackoverflow.com/q/51197074
has answer: http://stackoverflow.com/a/51197138
tagged with: python
answer count: 4
has answer: http://stackoverflow.com/a/51197099
has body: A solution would be to use replace() twice: import pandas as pd s = pd.Series([True, False, False]) s = s.replace(False, "A") s = s.replace(True, 'B') Then, Out[1]: 0 B 1 A 2 A Is there a more elegant way to accomplish this?
downvote count: 0
score: 1
linked to: http://stackoverflow.com/q/49259580
type: Question
upvote count: 1
has answer: http://stackoverflow.com/a/51197097
has title: How to replace a Series of booleans with a Series of strings?
has comment: http://stackoverflow.com/comment/89375908
has answer: http://stackoverflow.com/a/51197499
tagged with: pandas
favorite count: 0
has comment: http://stackoverflow.com/comment/89376087
type: UnansweredQuestion

http://stackoverflow.com/a/51263267
has body: You are submitting the form to the wrong URL http://127.0.0.1:8000/GET/?q=lots+of because you have action="GET". &lt;form action="GET" action="{% url 'posts:search' %}"&gt; Change it to method="GET": &lt;form method="GET" action="{% url 'posts:search' %}"&gt; The error message shows that your post_details view cannot handle the case where a post with that slug does not exist: def post_details(request, slug) posts = Posts.objects.get(slug=slug) # can raise DoesNotExist ... You could use get_object_or_404 instead: from django.shortcuts import get_object_or_404 def post_details(request, slug) posts = get_object_or_404(Posts, slug=slug) ... Finally, I would recommend renaming your model from Posts to Post to match the recommended Django style, and use post = get_object_or_404(...) since you are fetching a single post.
upvote count: 3
accepted answer of: http://stackoverflow.com/q/51263220
has comment: http://stackoverflow.com/comment/89505250
has comment: http://stackoverflow.com/comment/89505532
answers question: http://stackoverflow.com/q/51263220
has comment: http://stackoverflow.com/comment/89505115
has comment: http://stackoverflow.com/comment/89504583
has comment: http://stackoverflow.com/comment/89505281
has comment: http://stackoverflow.com/comment/89504922
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 3

http://stackoverflow.com/q/51307031
score: 2
upvote count: 2
tagged with: fonts
has title: Matplotlib change font size within table (just header) - python
type: Question
tagged with: matplotlib
has answer: http://stackoverflow.com/a/56515764
has answer: http://stackoverflow.com/a/51315695
answer count: 2
has body: I'd like for the headers of the columns to have a smaller font than the values in the cells so that they're readable (I'll show what I mean in an attached jpeg). Right now everything has the same font size. Example of the table code: fig = plt.figure(figsize=(11, 8.27)) ax = fig.add_subplot(111) ax.axis('off') index_length = len(well_data_table.index) table_1 = well_data_table.iloc[0:30] table_2= well_data_table.iloc[30:60] table_3 = well_data_table.iloc[60:-1] q='lightsalmon' colors3 = [q,q,q,q,q,q,q,q,q,q,q] the_table1 = ax.table(cellText=table_1.values, colWidths = [.1]*len(table_1.columns), rowLabels=table_1.index, colColours = colors3, colLabels=table_1.columns, cellLoc = 'center', rowLoc = 'center', loc='bottom', bbox=[.1, 0, 1, 1]) the_table1.auto_set_font_size(False) the_table1.set_fontsize(8) the_table1.scale(1, 1) ax.title.set_text("""TEST""") pdf.savefig(facecolor='w')
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: size
tagged with: python
linked to: http://stackoverflow.com/q/34069558

http://stackoverflow.com/q/51205382
has comment: http://stackoverflow.com/comment/89391815
has title: python3 import issue on PyCharm
score: 6
tagged with: python
type: AnsweredQuestion
tagged with: pycharm
downvote count: 0
duplicate of: http://stackoverflow.com/q/14132789
type: Question
upvote count: 6
has body: I'm annoyed about the import logic when I write Python3 code in PyCharm Community Edition, Below is my structure. project ├── orm.py ├── app.py ├── coroweb.py in app.py, I import orm use below codes. from . import orm from .coroweb import xxx It looks good in PyCharm, but when I run app.py, it will failed due to below error ImportError: cannot import name 'orm' Then, I use related import like this. import orm from coroweb import xxx it running good but has import error in PyCharm. It's Unresolved reference. I want to use code tracing in PyCharm, so I want to know how to fix this issue.
answer count: 1
linked to: http://stackoverflow.com/q/14132789
has answer: http://stackoverflow.com/a/51205531
accepted answer: http://stackoverflow.com/a/51205531
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/comment/89502839
comment on: http://stackoverflow.com/q/51262008
has text: Thanks. Actually I'm facing a string in every loop and using `eval` to evaluate it... Some calculations are so subtle that it cannot raise an `OverflowError`. How to build a criteria would be a problem...
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51329853
type: Answer
score: 1
has body: create a dictionary for each team like: team_colors = {'gs':'#E90', 'hou': '#555', 'LAC': '#FF0'} then when you iterate add color to your scatter plot by calling the color attribute in marker. 'data': [ go.Scatter( x=[team_dict[i][p]['Salary']], y=[team_dict[i][p]['PPG']], text=p, mode='markers', opacity=0.7, marker={ 'size': 15, 'line': {'width': .5, 'color': 'black'}, 'color':team_color[i] # looks like you iterate through team names }, name= i, ) for i in team_initials for p in team_dict[i] ], And that should make the plays on the same team have the same color. It mike be better to turn your nested dictionary into a pandas data frame and pass a whole team at a time and just call the columns you want "Salary" and "PPG". You can use this post to show you how to make a dataframe from your nested dictionary.
upvote count: 1
downvote count: 0
answers question: http://stackoverflow.com/q/51314752
has comment: http://stackoverflow.com/comment/89682096

http://stackoverflow.com/comment/89591308
comment on: http://stackoverflow.com/a/51296815
score: 0
type: AnswerComment
has text: You should not apply it to new_df. You should apply it to the string column of the original dataframe.
type: Comment

http://stackoverflow.com/a/51562139
has body: This is the solution I have found. @receiver(post_save, sender= AdminUser) def add_admin_permission(sender, instance, created, **kwargs): if created: grupo = Group.objects.get(id=1) grupo.user_set.add(instance)
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/51200009
answers question: http://stackoverflow.com/q/51200009
upvote count: 1
type: AcceptedAnswer
type: Answer

f-string
tags question: http://stackoverflow.com/q/51295158
tags question: http://stackoverflow.com/q/51320743
tag name: f-string
tags question: http://stackoverflow.com/q/51253372
type: Tag
tags question: http://stackoverflow.com/q/51312952

http://stackoverflow.com/comment/89563369
score: 0
type: AnswerComment
type: Comment
has text: probably to do with my whole dataset. Maybe null values of the response or something. The only suggested answer that works on my whole set is: .transform(lambda x: Counter(x).most_common(1)[0][0])) do you have any idea what can cause the error using your solution.
comment on: http://stackoverflow.com/a/51288707

http://stackoverflow.com/a/51267094
upvote count: 3
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: You may use (?&lt;!\d)[1-9]\d{3,4}(?!\d) See the regex demo. NOTE: In Pandas str.extract, you must wrap the part you want to be returned with a capturing group, a pair of unescaped parentheses. So, you need to use (?&lt;!\d)([1-9]\d{3,4})(?!\d) ^ ^ Example: df2['num_col'] = df2.Warehouse.str.extract(r'(?&lt;!\d)([1-9]\d{3,4})(?!\d)', expand = False).astype(float) Just because you can simple use a capturing group, you may use an equivalent regex: (?:^|\D)([1-9]\d{3,4})(?!\d) Details (?&lt;!\d) - no digit immediately to the left or (?:^|\D) - start of string or non-digit char (a non-capturing group is used so that only 1 capturing group could be accommodated in the pattern and let str.extract only extract what needs extracting) [1-9] - a non-zero digit \d{3,4} - three or four digits (?!\d) - no digit immediately to the right is allowed Python demo: import re s = "US Machine Operations | 0054 '0054','0008',or '0009' to be a match, but i would want '10354' or '10032', or '9005', or '9000'" print(re.findall(r'(?&lt;!\d)[1-9]\d{3,4}(?!\d)', s)) # =&gt; ['10354', '10032', '9005', '9000']
has comment: http://stackoverflow.com/comment/89518205
accepted answer of: http://stackoverflow.com/q/51267040
has comment: http://stackoverflow.com/comment/89514577
answers question: http://stackoverflow.com/q/51267040
score: 3

http://stackoverflow.com/comment/89511608
has text: It depends. Do the machine algorithms you are using accept lists as input parameters?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51266728

http://stackoverflow.com/comment/89388993
comment on: http://stackoverflow.com/q/51203772
type: Comment
type: QuestionComment
score: 0
has text: Hi Sahil, 01-02-1949 is 01Feb1949. the number of months is increasing by increasing the decimal by 0.083.

http://stackoverflow.com/q/51217113
has body: Given a document containing a paragraph d = docx.Document() p = d.add_paragraph() I expected the following technique to work every time: if len(p._element) == 0: # p is empty OR if len(p._p) == 0: # p is empty (Side question, what's the difference there? It seems that p._p is p._element in every case I've seen in the wild.) If I add a style to my paragraph, the check no longer works: &gt;&gt;&gt; p2 = d.add_paragraph(style="Normal") &gt;&gt;&gt; print(len(p2._element)) 1 Explicitly setting text=None doesn't help either, not that I would expect it to. So how to I check if a paragraph is empty of content (specifically text and images, although more generic is better)? Update I messed around a little and found that setting the style apparently adds a single pPr element: &gt;&gt;&gt; p2._element.getchildren() [&lt;CT_PPr '&lt;w:pPr&gt;' at 0x7fc9a2b64548&gt;] The element itself it empty: &gt;&gt;&gt; len(p2._element.getchildren()[0]) 0 But more importantly, it is not a run. So my test now looks like this: def isempty(par): return sum(len(run) for run in par._element.xpath('w:r')) == 0 I don't know enough about the underlying system to have any idea if this is a reasonable solution or not, and what the caveats are. More Update Seems like I need to be able to handle a few different cases here: def isempty(par): p = par._p runs = p.xpath('./w:r[./*[not(self::w:rPr)]]') others = p.xpath('./*[not(self::w:pPr) and not(self::w:r)] and ' 'not(contains(local-name(), "bookmark"))') return len(runs) + len(others) == 0 This skips all w:pPr elements and runs with nothing but w:rPr elements. Any other element, except bookmarks, whether in the paragraph directly or in a run, will make the result non-empty.
type: Question
accepted answer: http://stackoverflow.com/a/51217625
has comment: http://stackoverflow.com/comment/89416021
has comment: http://stackoverflow.com/comment/89416049
answer count: 1
score: 1
has comment: http://stackoverflow.com/comment/89415870
tagged with: python-docx
has comment: http://stackoverflow.com/comment/89416154
tagged with: python
favorite count: 0
upvote count: 2
has answer: http://stackoverflow.com/a/51217625
has comment: http://stackoverflow.com/comment/89415847
downvote count: 1
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89415984
has title: How to detect an empty paragraph in python-docx
has comment: http://stackoverflow.com/comment/89415982

http://stackoverflow.com/a/51250015
answers question: http://stackoverflow.com/q/51249794
accepted answer of: http://stackoverflow.com/q/51249794
type: AcceptedAnswer
downvote count: 0
upvote count: 16
has body: Activating the virtualenv gives you convenience. It is never required. Even for scripts that are configured to run with #!/usr/bin/env python, (which looks up the python executable on your path), you could manually update the PATH environment variable: $ PATH="/path/to/venv/bin" some_script Activating makes the PATH update stick until you deactivate again, and that can be convenient. For example, I regularly have several virtualenvs in use at any one time. Some of them are there only to install some command-line tools I have symlinked into my ~/bin/ directory, another is home to a Jupyter notebook, and 2 more are used to quickly verify code snippets in different Python versions with access to 3rd-party libraries. I don't activate any of those. When you don’t activate a virtualenv, all that happens is that your terminal PATH variable is not updated to put the bin directory of the virtualenv first, so when you enter python or pip or other script without any path into the terminal, the shell will find a different Python binary to run. You can always use any of the commands in the virtualenv bin/ directory by giving the full path to that command.
type: Answer
score: 16

http://stackoverflow.com/comment/89376281
score: 1
comment on: http://stackoverflow.com/q/51197241
has text: You should also mention the input that gives you infinite reursion.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51317377
score: 11
has comment: http://stackoverflow.com/comment/89657242
upvote count: 11
has comment: http://stackoverflow.com/comment/89707294
has comment: http://stackoverflow.com/comment/89706692
downvote count: 0
has comment: http://stackoverflow.com/comment/89709273
has body: Try ffmpeg on the command line: Output each channel in stereo input to individual mono files: ffmpeg -i stereo.wav -map_channel 0.0.0 left.wav -map_channel 0.0.1 right.wav I tried it on your file and it seems to work. If you need it to be in a python program just use os.system(cmd)
answers question: http://stackoverflow.com/q/51275725
type: Answer

http://stackoverflow.com/q/51257614
has comment: http://stackoverflow.com/comment/89495258
has body: A question on aggregation but this time the totals are on multiple fields, one set based on a criteria and the second set on grand totals. My df: display_name security_type1 currency_str state rfq_qty_CAD_Equiv A GOVT USD Done 100,000 B CORP NZD Passed 100,000 B CORP USD Done 100,000 C CORP EUR Done 100,000 C CORP EUR Traded Away 100,000 C CORP GBP Done 100,000 C CORP GBP Done 100,000 C CORP USD Done 100,000 Desired output follows: display_name security_type1 currency_str Done_RFQ Done_RFQ_Volume A GOVT USD 1 100,000 B CORP USD 1 100,000 C CORP EUR 1 100,000 C CORP GBP 2 200,000 C CORP USD 1 100,000 Total_RFQ Total RFQ_Volume Done_Pct 1 100,000 100% 2 200,000 50% 5 500,000 20% 5 500,000 40% 5 500,000 20% That is: Group on display_name,security_type1and currency_str Done_RFQ is the row count where statecontains any string with Done in it. Done_RFQ_Volume is the sum of rfq_qty_CAD_Equiv where statecontains any string with Done i.e. where point 2 is true. Total_RFQ is the count of all unique display_name,security_type1and currency_str combinations regardless if Done appears for state and Total RFQ_Volume is the sum of rfq_qty_CAD_Equiv for all records where point 4 is true. Finally display the percentage of Done to total count i.e. Done_Pct = Done_RFQ / Total_RFQ My attept at achieving this: d = [ ('Done_RFQ', lambda x: x.str.contains('Done').sum()) ('Done_RFQ_Volume', 'sum'), ('Total_RFQ', 'size'), ('Total RFQ_Volume', 'sum') ] df_Done_Client_Hit_Rate_Volume = df.groupby(['cust_cdr_display_name','rbc_security_type1','currency_str']).agg(d).reset_index() df_Done_Client_Hit_Rate_Volume['Hit Rate'] = df_Done_Client_Hit_Rate_Volume['Done_RFQ'] / df_Done_Client_Hit_Rate_Volume['Total_RFQ'] display(df_Done_Client_Hit_Rate_Volume) I'm not sure how to refer to the 'Done' rows and not 'Done' rows when summing rfq_qty_CAD_Equiv. The two volume columns (set out in d=), are based on the results of the criteria. Any help would be appreciated.
has comment: http://stackoverflow.com/comment/89494534
type: Question
has comment: http://stackoverflow.com/comment/89494871
tagged with: dataframe
has comment: http://stackoverflow.com/comment/89496121
has comment: http://stackoverflow.com/comment/89495123
score: 0
has comment: http://stackoverflow.com/comment/89494477
has comment: http://stackoverflow.com/comment/89494603
tagged with: pandas-groupby
tagged with: pandas
answer count: 1
has comment: http://stackoverflow.com/comment/89495059
has answer: http://stackoverflow.com/a/51257907
accepted answer: http://stackoverflow.com/a/51257907
has comment: http://stackoverflow.com/comment/89495863
has comment: http://stackoverflow.com/comment/89495727
has comment: http://stackoverflow.com/comment/89571441
tagged with: python
has title: Pandas Groupby: Aggregations on the same columns but multiple totals based on multiple critera
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89494589
has comment: http://stackoverflow.com/comment/89494469

http://stackoverflow.com/comment/89480966
type: Comment
comment on: http://stackoverflow.com/q/51250461
score: 0
type: QuestionComment
has text: @bad of course, it uses OAuth which is the preferred way

http://stackoverflow.com/q/51234889
upvote count: 2
has comment: http://stackoverflow.com/comment/109277468
tagged with: python
downvote count: 1
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51235026
score: 1
tagged with: selenium
has title: **what versions of python does HTMltestrunner support**
type: Question
has comment: http://stackoverflow.com/comment/89451331
answer count: 1
has comment: http://stackoverflow.com/comment/89448702
has answer: http://stackoverflow.com/a/51235026
favorite count: 0
has body: Problem: I am trying to use HTMltestrunner to generate HTML report for selenium tests. But it is giving me Import Module error. This is the error message I am receiving ImportError: No module named HTMLTestRunner Question: What versions of Python does HTMltestrunner support?

http://stackoverflow.com/a/51312727
has comment: http://stackoverflow.com/comment/89604956
upvote count: 2
accepted answer of: http://stackoverflow.com/q/51312381
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89605157
type: Answer
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/51312381
has body: If you know your app will only run in one process with multiple threads (which is probably not the case in most production WSGI servers), one approach is to pair the resource with a threading.Lock, encapsulating both in a class. Then 'pass' a (single) instance of that class to the app via the config. Within the encapsulating class, guard access to the resource. The Flask side might do @app.route('/something') def something(): app.config['RESOURCE'].action(...) ... which calls a method that locks access to the resource and delegates the call. def action(self, ...): with self.lock: self.resource.action(...) Locking in this way will block other Flask threads that might want simultaneous access to resource. There's a working example you can crib from here. Look at control.py, and ignore the part about running Flask in a separate thread. This works fine in the dev server. All bets are off if you deploy under uwsgi/gunicorn.

http://stackoverflow.com/comment/89416599
has text: @JamesRogers With an `if` statement.
comment on: http://stackoverflow.com/q/51217478
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51306598
has title: Automatic Scanned Document Image Enhancement
tagged with: image-enhancement
has body: I'm developing automatic image enhancement based on Microsoft paper Whiteboard scanning and image enhancement in the "White balancing and image enhancement" section they provide the steps for the enhancement: First: they estimate the background of the scanned document or the detected white Board: 1. "Divide the whiteboard region into rectangular cells. The cell size should be roughly the same as what we expect the size of a single character on the board (15 by 15 pixels in our implementation)." then 2. "Sort the pixels in each cell by their luminance values. Since the ink absorbs the incident light, the luminance of the whiteboard pixels is higher than stroke pixels’. The whiteboard color within the cell is, therefore, the color with the highest luminance. In practice, we average the colors of the pixels in the top 25 percentile in order to reduce the error introduced by sensor noise" then 3. "Filter the colors of the cells by locally fitting a plane in the RGB space. Occasionally there are cells that are entirely covered by pen strokes, the cell color computed in Step 2 is consequently incorrect. Those colors are rejected as outliers by the locally fitted plane and are replaced by the interpolated values from its neighbors." My problem is with the second and the third steps: How they get the luminace value, should I convert the input image to YUV color space and get the luminace value from the Y channel or just work on RGB color space? How to fit a local plane in the RGB space ? Here is my python code that I tried to make cell from input image, get the luminance value from YUV color space and a simple result that seems incorrect compared by the result they get in the paper. Python Code: import cv2 import numpy as np ## Return List of cells from a given Image def SubImage(image): Cells = [] CellRows = [] for i in range(0,rows/CellSize): subIm = image[i*CellSize:(i+1)*CellSize,:] CellRows.append(subIm) for img in CellRows: for i in range(0,cols/CellSize): subIm = img…
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/89590744
has answer: http://stackoverflow.com/a/51823224
upvote count: 1
tagged with: python
favorite count: 0
downvote count: 0
type: UnansweredQuestion
tagged with: computer-vision
tagged with: opencv
linked to: http://stackoverflow.com/q/33997220
has comment: http://stackoverflow.com/comment/89590468
has comment: http://stackoverflow.com/comment/89594720
has answer: http://stackoverflow.com/a/51818328
score: 1

http://stackoverflow.com/q/51288677
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/89582398
type: Question
has comment: http://stackoverflow.com/comment/89577608
has title: How to display image on web page based on selected value from select field without reloading page
tagged with: flask
score: 0
has body: I am trying to figure out how to display an image on the webform page when a certain option is selected from the select field. And then getting the image to change when a different option is selected. The url image link is stored in the Sqlite3 database with the respective select field options. I am having trouble putting this all together and was wondering if someone may be able to help. Here is some code that may make things easier to understand. The select field I am focusing on is the Host field and the extra part of the Host class is where the URL image link is stored. class LoginForm(FlaskForm): host = SelectField('Host Solution Required', choices = [], validators= . [validators.InputRequired('Please select a Board')]) @app.route('/', methods=['GET', 'POST']) def form(): form = LoginForm() form.device.choices = [(device.id, device.name) for device in Device.query.filter_by(cat=None).all()] form.host.choices= [(host.id, host.name) for host in Host.query.all()] #if form.validate_on_submit(): To use this I will have to figure out how to validate the choices for device if request.method =='POST': device = Device.query.filter_by(id=form.device.data).first() host = Host.query.filter_by(id= form.host.data).first() #This code takes care of changing the format of the ordering link that is put into bugzilla. if host.name =='None' and form.cat.data == 'None': return '&lt;h1&gt; You did not order anything, please go back and fill out cat or host&lt;/h2&gt;' elif host.name == 'None': return '&lt;h1&gt; ({} x {}) for {}&lt;/h1&gt;'.format(form.number.data, device.name, form.team.data) elif form.cat.data == 'None': return '&lt;h1&gt; ({} x {}-{}) for {} . &lt;/h1&gt;'.format(form.quantity.data, host.name, form.finish.data, form.team.data) else: return '&lt;h1&gt; ({} x {}-{}) AND ({} x {}) for {} . &lt;/h1&gt;'.format(form.quantity.data, host.name, form.finish.data, form.number.data, device.name, form.team.data) return render_template('form.html', form=form, street = host.ex…
tagged with: http://stackoverflow.com/tag/html
tagged with: flask-sqlalchemy
tagged with: flask-wtforms
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89578386

http://stackoverflow.com/comment/89598414
type: Comment
has text: After using your pivot example, I got a keyerror on my dataset when trying to get all values in the row. Did I do something wrong?
comment on: http://stackoverflow.com/a/51310583
type: AnswerComment
score: 0

http://stackoverflow.com/a/52054402
downvote count: 0
has comment: http://stackoverflow.com/comment/124290068
type: Answer
score: 1
upvote count: 1
has body: i meet the same problem, and i use the same as you ,Python 3.7 64bit, meet stop working also. now i found if use Python 3.6.4 64bit. no error raise. you can try.
answers question: http://stackoverflow.com/q/51178708

numpy-ndarray
tags question: http://stackoverflow.com/q/51253850
tags question: http://stackoverflow.com/q/51253515
tags question: http://stackoverflow.com/q/51291797
tags question: http://stackoverflow.com/q/51287299
tags question: http://stackoverflow.com/q/51212744
tags question: http://stackoverflow.com/q/51201747
tags question: http://stackoverflow.com/q/51232019
tags question: http://stackoverflow.com/q/51310712
tag name: numpy-ndarray
tags question: http://stackoverflow.com/q/51206036
type: Tag
tags question: http://stackoverflow.com/q/51282642

http://stackoverflow.com/q/51307319
score: 1
has answer: http://stackoverflow.com/a/51307857
tagged with: loss-function
has title: How to set a function from an external python library as custom loss function in Keras?
type: Question
has body: I recently started working with python and more specifically with Keras for a machine learning application. I want to train an artificial neural network with the following custom loss function that makes use of the hypervolume, given in the pygmo library: def hypervolume_difference_loss(y_true, y_pred): import numpy as np from pygmo import hypervolume ref_point = [1.0, 1.0] ref_PF = np.array(y_true) out_PF = np.array(y_pred) hv_d = np.empty(shape=y_true.shape[0], dtype=float) for i, (ref_point _i, out_PF _i) in enumerate(zip(ref_point , out_PF )): ref_hv_obj = hypervolume(points=ref_point .reshape(10, -1,order='F')) out_hv_obj = hypervolume(points=ref_point .reshape(10, -1,order='F')) ref_hv = ref_hv_obj.compute(ref_point ) out_hv = out_hv_obj.compute(ref_point ) hv_d[i] = abs(ref_hv - out_hv) return hv_d Based on Keras documentation the custom loss function has to be a tensorflow symbolic function. I have found several examples (e.g. link) showing how to write such a symbolic function with the use of Keras backend functions but I was not able to find a way to write a symbolic function that can use the result of an external library. I recently found a similar issue in this link but no solution is provided. The only workaround I can think of is to re-write the hypervolume function with Keras backend representation. Could you please let me know if there is any more convenient way? I would greatly appreciate any kind of help or recommendation. Thank you in advance.
downvote count: 0
answer count: 1
tagged with: keras
favorite count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: python

http://stackoverflow.com/q/51262056
accepted answer: http://stackoverflow.com/a/51500499
tagged with: pyqtgraph
has comment: http://stackoverflow.com/comment/89930845
type: Question
has title: PyQTGraph ImageExporter bug related to image size
tagged with: export
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/51500499
has body: I am using pyqtgraph to produce plots in a PyQT window. I want to export PNG image of the graphs. I have this error when I try to export my plots: ImageExporter.py", line 70, in export bg = np.empty((self.params['width'], self.params['height'], 4), >dtype=np.ubyte) TypeError: 'float' object cannot be interpreted as an integer I noticed that the self.params['width'] and self.params['height'] are floats. But np.empty can not create an erray using float sizes. Even if i set the width and height manually using : exporter.parameters()['width'] = self.raw_DataPlot.width() exporter.parameters()['height'] = self.raw_DataPlot.height() The results are floats. I noticed that If I change the line 70 of ImageExporter.py to : bg = np.empty((int(self.params['width']), int(self.params['height']), 4),dtype=np.ubyte) The export works fine. Is it possible to address this issue and update the library? Or is there a workaround that doesn't push me to change the pyqtgraph library itself. Thanks
has comment: http://stackoverflow.com/comment/89537255
has comment: http://stackoverflow.com/comment/89537237
has comment: http://stackoverflow.com/comment/89915247
tagged with: python
tagged with: http://stackoverflow.com/tag/png
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89531613

http://stackoverflow.com/comment/89336417
has text: `dict(pressure=5.5)` is a different key in a parent `dict`, write instead `fields=dict(pressure=5.5)`
type: QuestionComment
type: Comment
score: 1
comment on: http://stackoverflow.com/q/51176864

http://stackoverflow.com/comment/89406706
type: AnswerComment
has text: Ok, please test if same problem with zeros like in real data, thanks.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51187292

http://stackoverflow.com/a/51279100
has body: Your mistake is here :silpa when you are replacing you have not cared about indices where character is replacing so how it is going when you give sent input after replacing n we get string like tfot now in next iteration next letter you encounter in your original string is t so it will replace the first letter that is t in the replaced string so . "tfot" becomes "ufot" and last t is not being replaced
downvote count: 0
type: Answer
upvote count: 3
score: 3
answers question: http://stackoverflow.com/q/51278380

http://stackoverflow.com/comment/89568451
score: 0
type: Comment
has text: that's what I was looking for, thanks! where can I read more about this method of blocking?
comment on: http://stackoverflow.com/a/51295415
type: AnswerComment

http://stackoverflow.com/comment/89424187
type: Comment
comment on: http://stackoverflow.com/q/51221824
score: 0
type: QuestionComment
has text: When you say dataframe, do you mean `pandas`? Then it should be tagged accordingly. And what have you tried, why did it fail?

http://stackoverflow.com/a/51265966
has comment: http://stackoverflow.com/comment/89510564
accepted answer of: http://stackoverflow.com/q/51265888
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51265888
has body: Idea is create helper DataFrame by groupby with size or value_counts and then unstack and join to original df: df = (df.join(df.groupby(['user_id', 'label']) .size() .unstack(fill_value=0) .add_prefix('label_'), 'user_id')) df = (df.join(df.groupby('user_id')['label'] .value_counts() .unstack(fill_value=0) .add_prefix('label_'), 'user_id')) Or using crosstab and merge with left join: df = (df.merge(pd.crosstab(df['user_id'], df['label']) .add_prefix('label_'), on='user_id', how='left')) print (df) user_id label label_0 label_1 label_2 0 a 0 1 2 0 1 a 1 1 2 0 2 a 1 1 2 0 3 b 1 1 1 1 4 b 2 1 1 1 5 b 0 1 1 1 6 c 0 1 1 1 7 c 1 1 1 1 8 c 2 1 1 1
score: 6
type: Answer
upvote count: 6

http://stackoverflow.com/q/51243969
score: 0
answer count: 2
tagged with: python-3.x
has body: I am using windows 10 OS with Python 3.5. I am trying to run a program related to torch. So I installed Pytorch with the help of the instructions specified on their website: Pytorch installation See the following image for selection of the downloadable: I installed it using : pip install http://download.pytorch.org/whl/cpu/torch-0.4.0-cp35-cp35m-win_amd64.whl pip install torchvision I have encountered the following error: Error Traceback (most recent call last): File "C:\Python35\lib\site-packages\twisted\trial\runner.py", line 701, in findByName __import__(name) File "C:\Users\aims\Desktop\CNN\source\cnn4matrix.py", line 4, in <module> import torch File "C:\Python35\lib\site-packages\torch\__init__.py", line 78, in <module> from torch._C import * ImportError: DLL load failed: The specified module could not be found. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Python35\lib\site-packages\twisted\trial\runner.py", line 803, in loadByName return self.suiteFactory([self.findByName(name, recurse=recurse)]) File "C:\Python35\lib\site-packages\twisted\trial\runner.py", line 704, in findByName return self.loadFile(_name, recurse=recurse) File "C:\Python35\lib\site-packages\twisted\trial\runner.py", line 674, in loadFile module = SourceFileLoader(name, fileName).load_module() File "<frozen importlib._bootstrap_external>", line 385, in _check_name_wrapper File "<frozen importlib._bootstrap_external>", line 806, in load_module File "<frozen importlib._bootstrap_external>", line 665, in load_module File "<frozen importlib._bootstrap>", line 268, in _load_module_shim File "<frozen importlib._bootstrap>", line 693, in _load File "<frozen importlib._bootstrap>", line 673, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 662, in exec_module File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed File "C:\Users\aims\Desktop\CNN\source\cnn4matrix.py", line 4, in <module> impo…
tagged with: python
tagged with: pytorch
type: UnansweredQuestion
type: Question
has answer: http://stackoverflow.com/a/51244655
has title: Encounter Error after installing Pytorch using pip in python3.5
has answer: http://stackoverflow.com/a/51251337

http://stackoverflow.com/comment/89561360
comment on: http://stackoverflow.com/a/51288707
has text: Thanks! I tried df['mostGivenResponse'] = df.groupby('item').response.transform(pd.Series.mode) but then it says: ValueError: Length of passed values is 1, index implies 162 (sorry I started learning Python today)
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/89568743
comment on: http://stackoverflow.com/q/51292047
score: 0
type: Comment
type: QuestionComment
has text: Possible duplicate of [Parsing values from a JSON file?](https://stackoverflow.com/questions/2835559/parsing-values-from-a-json-file)

http://stackoverflow.com/q/51248169
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/240178
tagged with: python
has body: When I manually declare and initialise all the elements in a list of lists and change one of the values, the change can be seen as one would expect. a=[[0,0,0],[0,0,0]] a[0][0]=9 print(a) The output is [[9,0,0],[0,0,0]] as one would expect. However, when I use shorthand notation, changing the first element of the first list changes the first element of all the lists. Here's the code: a=[[0]*3]]*2 a[0][0]=9 print(a) This time, the output is [[9,0,0],[9,0,0]]! What's going on?
has title: Changing values of elements in a list of lists
tagged with: list
answer count: 0
score: 1
type: Question
duplicate of: http://stackoverflow.com/q/240178
has comment: http://stackoverflow.com/comment/89475273
tagged with: matrix
upvote count: 1
downvote count: 0
tagged with: initialization
favorite count: 0

http://stackoverflow.com/a/53708286
answers question: http://stackoverflow.com/q/51258029
score: 16
upvote count: 16
accepted answer of: http://stackoverflow.com/q/51258029
has body: EDIT: note that as of OSMnx 0.15.0, you can now easily plot multiple routes with their own colors easily and natively: routes = [route1, route2, route3] rc = ['r', 'y', 'c'] fig, ax = ox.plot_graph_routes(G, routes, route_colors=rc, route_linewidth=6, node_size=0) For more info, see the docs or this usage example notebook. =============================== Original answer from 2018: It's worth noting that this functionality now exists in OSMnx as of v0.8.2. Example here of plotting multiple routes each with their own color. import networkx as nx import osmnx as ox ox.config(log_console=True, use_cache=True) G = ox.graph_from_place('Piedmont, CA, USA', network_type='drive') # pick 4 random nodes as origins/destinations for the 2 routes orig1 = list(G.nodes())[0] dest1 = list(G.nodes())[-1] orig2 = list(G.nodes())[50] dest2 = list(G.nodes())[-50] # calculate shortest paths for the 2 routes route1 = nx.shortest_path(G, orig1, dest1, weight='length') route2 = nx.shortest_path(G, orig2, dest2, weight='length') # create route colors rc1 = ['r'] * (len(route1) - 1) rc2 = ['b'] * len(route2) rc = rc1 + rc2 nc = ['r', 'r', 'b', 'b'] # plot the routes fig, ax = ox.plot_graph_routes(G, [route1, route2], route_color=rc, orig_dest_node_color=nc, node_size=0)
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/comment/89438097
type: QuestionComment
comment on: http://stackoverflow.com/q/51229188
score: 0
type: Comment
has text: @abarnert As I said in the title, but neglected to mention again in the body, is that port forwarding isn't really an option here. I'm looking for a general solution where you could ideally download the program onto any generic computer and have it work without special settings.

http://stackoverflow.com/q/51172775
tagged with: machine-learning
upvote count: 1
tagged with: python
tagged with: computer-vision
answer count: 1
has answer: http://stackoverflow.com/a/51173400
score: 0
downvote count: 1
tagged with: tensorflow
accepted answer: http://stackoverflow.com/a/51173400
has title: Problems with dimensions when fitting image in resnet model
type: AnsweredQuestion
has body: Maybe there some way to get rid of the avg_pool layer?I cant find solution :( SAMPLE_SHAPE = (32,32,3) def generate_model(sample_shape): inp = Input(shape=sample_shape) resnet = resnet50.ResNet50(weights="imagenet",include_top=False) x = resnet(inp) predictions = Dense(2, activation='softmax')(x) m = Model(inputs=inp, outputs=predictions) #model.add(Dense(2, activation='softmax')) # This creates a model #predictions = Dense(2, activation='softmax')(x) return m model = generate_model(SAMPLE_SHAPE) Error: InvalidArgumentError Traceback (most recent call last) ~\Anaconda3\lib\site-packages\tensorflow\python\framework\ops.py in _create_c_op(graph, node_def, inputs, control_inputs) 1566 try: -> 1567 c_op = c_api.TF_FinishOperation(op_desc) 1568 except errors.InvalidArgumentError as e: InvalidArgumentError: Negative dimension size caused by subtracting 7 from 1 for 'resnet50_14/avg_pool/AvgPool' (op: 'AvgPool') with input shapes: [?,1,1,2048]. During handling of the above exception, another exception occurred: ValueError Traceback (most recent call last) in () 15 #predictions = Dense(2, activation='softmax')(x) 16 return m ---> 17 model = generate_model(SAMPLE_SHAPE) in generate_model(sample_shape) 7 inp = Input(shape=sample_shape) 8 resnet = resnet50.ResNet50(weights="imagenet",include_top=False) ----> 9 x = resnet(inp) 10 predictions = Dense(2, activation='softmax')(x) 11 ~\Anaconda3\lib\site-packages\keras\engine\topology.py in call(self, inputs, **kwargs) 552 553 # Actually call the layer, collecting output(s), mask(s), and shape(s). --> 554 output = self.call(inputs, **kwargs) 555 output_mask = self.compute_mask(inputs, previous_mask) 556 ~\Anaconda3\lib\site-packages\keras\engine\topology.py in call(self, inputs, mask) 1988 return self._output_tensor_cache[cache_key] 1989 else: -> 1990 output_tensors, _, _ = self.run_internal_graph(inputs, masks) 1991 return output_tensors 1992 ~\Anaconda3\lib\site-packages\keras\engine\topology.py in run_internal_graph(self, inputs…
tagged with: keras
favorite count: 0
type: Question

http://stackoverflow.com/q/51234354
possible better answer: http://stackoverflow.com/a/51234514
has answer: http://stackoverflow.com/a/51234514
has comment: http://stackoverflow.com/comment/89447812
has comment: http://stackoverflow.com/comment/89447747
type: AnsweredQuestion
has body: I wrote an Airbnb scraper that goes through every subpage of home listings for a specified location and for every subpage it returns zip object like this: subpage = zip(names, prices) After scraping single subpage, I add the subpage zip object to a list: all_subpages.append(subpage) So in the end all_subpages is a list of zip objects, each one containg data from one subpage. My problem is I want to display data from all_subpages in HTML table form and I want this data sorted by price. So my question is: how do I print the contents of all_subpages ordered by price? Expected output: Name Price Apartment 3 10 GBP Apartment 1 15 GBP Apartment 2 20 GBP etc.
has comment: http://stackoverflow.com/comment/89448325
type: Question
answer count: 2
has title: How to sort a list of zip objects by specified criteria?
score: 0
has comment: http://stackoverflow.com/comment/89447771
has answer: http://stackoverflow.com/a/51234434
tagged with: python
accepted answer: http://stackoverflow.com/a/51234434
has comment: http://stackoverflow.com/comment/89447729

http://stackoverflow.com/comment/89486477
comment on: http://stackoverflow.com/a/51250626
has text: I do not know how to link to more than another question, is there a way to link to a specific answer, since the one I posted was not the accepted answer? I could probably cleanup my answer a bit, but I was honestly expecting this to be closed as a duplicate since it is and I had already flagged it, and figured I would help the guy out getting his feather gone, so didn't see much point in spending my entire lunch break developing a well critiqued answer to a duplicate question.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/51211538
accepted answer: http://stackoverflow.com/a/51211843
type: Question
tagged with: seaborn
score: 5
tagged with: python
has title: countplot from several columns
answer count: 2
has answer: http://stackoverflow.com/a/51211843
upvote count: 5
has answer: http://stackoverflow.com/a/51213206
tagged with: pandas
type: AnsweredQuestion
has body: I have a dataframe with several categorical columns. I know how to do countplot which routinly plots ONE column. Q: how to plot maximum count from ALL columns in one plot? here is an exemplary dataframe to clarify the question: import pandas as pd import numpy as np import seaborn as sns testdf=pd.DataFrame(({ 'Ahome' : pd.Categorical(["home"]*10), 'Bsearch' : pd.Categorical(["search"]*8 + ["NO"]*2), 'Cbuy' : pd.Categorical(["buy"]*5 + ["NO"]*5), 'Dcheck' : pd.Categorical(["check"]*3 + ["NO"]*7), } )) testdf.head(10) sns.countplot(data=testdf,x='Bsearch'); The last line is just using normal countplot for one column. I'd like to have the columns category (home,search,buy and check) in x-axis and their frequency in y-axis.
downvote count: 0
possible better answer: http://stackoverflow.com/a/51213206
favorite count: 0

http://stackoverflow.com/q/51290777
accepted answer: http://stackoverflow.com/a/51291106
tagged with: linear-algebra
type: Question
tagged with: numpy
score: 0
has body: I am using a matrix to count combinations of relationships between nodes in a graph (the details are irrelevant). I have an N*N adjacency matrix, rows and columns correspond to nodes. So, position [5,7] is how many times node 5 is with node 7. As is [7,5]. Position [3,3] is how many times node 3 appears at all, so how many times it appears in total. At each loop I have to reduce my matrix. I take a vector of size n, and I subtract the matrix diagonal by that vector. So, I am reducing the total count of each node: so like, [1,1] and [2,2] and [3,3] in my matrix, etc. Hopefully I am making sense so far. Here is this question. At this point, I have modified the diagonal of my matrix. Now, I want to modify every position [i,j] where i != j and matrix[i,j] != 0 I want to modify it such that: matrix[i,j] = min(matrix[i,i],matrix[j][j]) Now of course I could just iterate through every index pair (i,j) and do what I wrote just above. But that is slow. I am hoping there is some clever math or numpy trick to make this much faster. Thank you!
has title: 2d numpy, efficiently assign nonzero indices [row,col] the minimum of [row,row] and [col,col]
tagged with: matrix
answer count: 1
has answer: http://stackoverflow.com/a/51291106
tagged with: python
type: AnsweredQuestion

crop
tags question: http://stackoverflow.com/q/51200630
tag name: crop
type: Tag

http://stackoverflow.com/q/51321564
downvote count: 0
favorite count: 0
tagged with: exception
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89618545
tagged with: python
score: 2
answer count: 0
upvote count: 2
has title: exception handling - AttributeErrror: 'datetime.datetime' object has no attribute 'sleep'
type: Question
has comment: http://stackoverflow.com/comment/89621363
has comment: http://stackoverflow.com/comment/89618576
has body: I'm running a script to collect all the lifetime tweets of a list of users. As a result, I've had to add an exception handling bit for when my credentials time out. The error I'm currently receiving is: During handling of the above exception, another exception occurred: Traceback (most recent call last): File "PROJECT_july.py", line 108, in time.sleep(60 * 5) AttributeError: 'datetime.datetime' object has no attribute 'sleep' The script I've used to handle the error is: except tweepy.TweepError: time.sleep(60 * 5) auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET) auth.set_access_token(ACCESS_TOKEN, ACCESS_SECRET) api = tweepy.API(auth, wait_on_rate_limit=True) print("tweep error avoided: tweepy.TweepError XXX2") Please note - I'm just using 'import time' (deleted 'import datetime' the first time I received this error!). Any advice is massively appreciated! Thank you,
has comment: http://stackoverflow.com/comment/89618559

http://stackoverflow.com/comment/89452906
comment on: http://stackoverflow.com/q/51236885
score: 0
type: Comment
type: QuestionComment
has text: As a side note, why are you reading the Python 2.0 docs? Even if you're wondering with Python 2 rather than 3, surely it's 2.7, or at least 2.6?

http://stackoverflow.com/comment/89514810
has text: but i am not trying to convert it to an int
comment on: http://stackoverflow.com/q/51268192
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51170644
score: 0
answer count: 1
tagged with: python
type: AnsweredQuestion
tagged with: oop
accepted answer: http://stackoverflow.com/a/51170889
has title: How to correctly restore a OOP tensorflow model?
tagged with: tensorflow
type: Question
has body: For the sake of a current project, I decided to define a tensorflow model within a class instance. This all worked well until I wanted to restore it to continue training from the latest checkpoint. It is a simple linear regression model which is built upon initialization of the instance. It tries to approximate the function f(x) = 3x + 1. The logic is: if there's no checkpoint yet, create a new model, train it for 20 epochs, save it. If there is already a checkpoint, load it, and continue training from it for 20 epochs. Now, initially training the network works. But when trying to train it after loading it, it throws the following error: File "", line 1, in runfile('/home/abc/tf_tests/restore_test/restoretest.py', wdir='/home/sku/tf_tests/restore_test') File "/home/abc/anaconda3/envs/tensorflow/lib/python3.5/site-packages/spyder/utils/site/sitecustomize.py", line 710, in runfile execfile(filename, namespace) File "/home/abc/anaconda3/envs/tensorflow/lib/python3.5/site-packages/spyder/utils/site/sitecustomize.py", line 101, in execfile exec(compile(f.read(), filename, 'exec'), namespace) File "/home/sku/tf_tests/restore_test/restoretest.py", line 71, in model.run_training_step(sess, x, y) NameError: name 'model' is not defined The question is: how do restore it and proceed the training properly? I have found an interesting article about OOP here, but it does not deal with saving and restoring models. My code is below. Thank you for helping me out! import tensorflow as tf import numpy as np import matplotlib.pyplot as plt class LinearModel(object): def __init__(self): self.build_model() def build_model(self): # x is input, y is output self.x = tf.placeholder(dtype=tf.float32, name='x') self.y = tf.placeholder(dtype=tf.float32, name='y') self.w = tf.Variable(0.0, name='w') self.b = tf.Variable(0.0, name='b') self.global_step = tf.Variable(0, trainable=False, name='global_step', dtype=tf.int32) self.y_pred = self.w * self.x + self.b # quadratic error as loss self.loss =…
has answer: http://stackoverflow.com/a/51170889

http://stackoverflow.com/a/57080255
score: 1
upvote count: 1
type: Answer
has body: On callback function I put self.recognizer.recognize_google(audio) regardless the recognizer parameter. For sure, the class need to have a recognizer = sr.Recognizer()
downvote count: 0
answers question: http://stackoverflow.com/q/51306399

http://stackoverflow.com/comment/89473594
comment on: http://stackoverflow.com/q/51212204
has text: @RoryDaulton Actually, this question can be reduced to the other one. If you are looking for a sequence x_1, x_2, ..., x_l that adds up to n with -k<= x_i <= k, then you could instead look for a sequence y_1, y_2, ..., y_l that adds up to n + l*k, with 0<= y_i <= k. Then, you set x_i = y_i - k.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89431086
type: QuestionComment
comment on: http://stackoverflow.com/q/51225275
score: 0
has text: In your numpy example, you're using it to provide convenient names - in a DataFrame - you already have them... If as you mention column names are complicated, then just use `df.rename(columns={'some stupidly long name that's a pain in the rear to keep typing out': 'short_name'}, inplace=True)` if you find you keep having to assign a reasonable name to it, or just unpack the tricky ones such as: `a, b = df['laskdjflaskdjflasdkfjladfsjladsjflaskdjflasdfj'], df['asdfjlasdoijasdofjnasdfkjlaskdf']`and access the rest on the df itself.
type: Comment

http://stackoverflow.com/q/51253850
has body: What I mean by this is imagine you have an ndarray a with shape (2,3,4). I want to define another ndarray b with shape (3,2,4) such that b[i][j][k] = a[j][i][k] Matrix operations only apply to the last 2 index places. If there is a way to make matrix operations act on any 2 chosen index places then everything can be solved. Thank you
downvote count: 0
has answer: http://stackoverflow.com/a/51254370
favorite count: 0
tagged with: multidimensional-array
answer count: 3
has answer: http://stackoverflow.com/a/51253915
tagged with: python
has answer: http://stackoverflow.com/a/51253958
score: 2
possible better answer: http://stackoverflow.com/a/51253915
upvote count: 2
accepted answer: http://stackoverflow.com/a/51254370
has title: How do I in a sense "juggle" elements in ndarrays?
tagged with: transpose
type: AnsweredQuestion
type: Question
tagged with: numpy
tagged with: numpy-ndarray

http://stackoverflow.com/q/51290073
has comment: http://stackoverflow.com/comment/89558202
has title: Python Match List with appropriate list
score: 0
tagged with: pandas
tagged with: python
favorite count: 0
accepted answer: http://stackoverflow.com/a/51290178
downvote count: 2
has answer: http://stackoverflow.com/a/51290234
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51290178
has body: Need to match the lists with appropriate value, i was able to match with two lists, but here involved three lists. # **Main List** main_list = ['munnar', 'ooty', 'coonoor', 'nilgri', 'wayanad', 'coorg', 'chera', 'hima'] # **List1** List1 = ['ooty', 'coonoor', 'chera'] # **List2** List2 = ['hill', 'hill', 'hill'] # **List3** List3 = ['nilgri', 'hima'] # **List4** List4 = ['mount', 'mount'] List1 belong to List2 same List3 belong to List4, I can match List1 with List2 and List3 with List4 using list comprehension pd.DataFrame( list(zip(List1, List2)), columns=('Area', 'Content') ) Area Content ooty hill coonoor hill chera hill And pd.DataFrame( list(zip(List3, List4)), columns=('Area', 'Content') ) Area Content nilgri mount hima mount List1 and List3 is available in Main List, now have to match List2 and List4 in Main List. if its not matching then it need to have NA Expecting below output using pandas. Area Content munnar NA ooty hill coonoor hill nilgri mount wayanad NA coorg NA chera hill hima mount Please help !!!
type: Question
upvote count: 2
answer count: 2
possible better answer: http://stackoverflow.com/a/51290234

recursion
type: Tag
tags question: http://stackoverflow.com/q/51216218
tags question: http://stackoverflow.com/q/51206289
tags question: http://stackoverflow.com/q/51199082
tag name: recursion
tags question: http://stackoverflow.com/q/51202596
tags question: http://stackoverflow.com/q/51197241
tags question: http://stackoverflow.com/q/51256968
tags question: http://stackoverflow.com/q/51289619
tags question: http://stackoverflow.com/q/51310139
tags question: http://stackoverflow.com/q/51225136
tags question: http://stackoverflow.com/q/51265307
tags question: http://stackoverflow.com/q/51199548
tags question: http://stackoverflow.com/q/51227600
tags question: http://stackoverflow.com/q/51180949
tags question: http://stackoverflow.com/q/51270368
tags question: http://stackoverflow.com/q/51181967
tags question: http://stackoverflow.com/q/51303609
tags question: http://stackoverflow.com/q/51229870
tags question: http://stackoverflow.com/q/51322081

http://stackoverflow.com/comment/89367170
comment on: http://stackoverflow.com/a/51192659
type: AnswerComment
has text: Sorry, to clarify: What **','** am I removing? The one inside df2=pd.read_csv('filename.csv', sep=',')? Or is it somewhere else that I do that?
score: 0
type: Comment

ubuntu
tags question: http://stackoverflow.com/q/51282879
tags question: http://stackoverflow.com/q/51224927
tags question: http://stackoverflow.com/q/51218108
tags question: http://stackoverflow.com/q/51243515
tags question: http://stackoverflow.com/q/51217876
tags question: http://stackoverflow.com/q/51292527
tags question: http://stackoverflow.com/q/51239512
tags question: http://stackoverflow.com/q/51173220
tags question: http://stackoverflow.com/q/51257776
tags question: http://stackoverflow.com/q/51224674
tags question: http://stackoverflow.com/q/51205924
tags question: http://stackoverflow.com/q/51303321
tags question: http://stackoverflow.com/q/51279791
tags question: http://stackoverflow.com/q/51277060
tags question: http://stackoverflow.com/q/51239146
tags question: http://stackoverflow.com/q/51216194
tags question: http://stackoverflow.com/q/51194310
tag name: ubuntu
tags question: http://stackoverflow.com/q/51210305
tags question: http://stackoverflow.com/q/51285853
tags question: http://stackoverflow.com/q/51323244
tags question: http://stackoverflow.com/q/51305595
tags question: http://stackoverflow.com/q/51197793
tags question: http://stackoverflow.com/q/51276933
tags question: http://stackoverflow.com/q/51264043
tags question: http://stackoverflow.com/q/51317778
type: Tag
tags question: http://stackoverflow.com/q/51213730

http://stackoverflow.com/comment/89522615
comment on: http://stackoverflow.com/q/51271726
score: 0
type: Comment
type: QuestionComment
has text: Ah yes, I have. The SDK they link to is already part of the 'Desktop API package' which I've downloaded. I'm not sure if there is another way to change my 'path'..

http://stackoverflow.com/a/51286652
has comment: http://stackoverflow.com/comment/89550991
accepted answer of: http://stackoverflow.com/q/51286454
downvote count: 0
score: 1
type: AcceptedAnswer
has body: You can use zip with list slicing. Ex: s = ['TW', 6.5, 'TS', 5.0, 'core_h', 2.0, 'core_tand', 2.0, 'core_er', 2.0, 'trace_height', 5.0, 'trace_er', 5.0, 'trace_tand', 5.0, 'D', 5.0, 'prepreg_h', 14.0, 'prepreg_er', 14.0, 'prepreg_tand', 14.0, 'roughness_level', 22.0] res = "" for i,v in zip(s[::2], s[1::2]): res += "{0}_{1}-".format(i, v) print(res) Output: TW_6.5TS_5.0core_h_2.0core_tand_2.0core_er_2.0trace_height_5.0trace_er_5.0trace_tand_5.0D_5.0prepreg_h_14.0prepreg_er_14.0prepreg_tand_14.0roughness_level_22.0
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/51286454

http://stackoverflow.com/comment/89407003
has text: What are you using to do the request? It is possible that whatever tool/browser you are using is sending two requests for some reason.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51212950

http://stackoverflow.com/comment/89496036
type: QuestionComment
type: Comment
has text: I did so but still the same problem persists...
comment on: http://stackoverflow.com/q/51241670
score: 0

http://stackoverflow.com/q/51227057
has comment: http://stackoverflow.com/comment/89440079
type: Question
has comment: http://stackoverflow.com/comment/89455064
has body: I'm plotting scattergeo plots on a US map (51 traces for 51 states including DC and 4 traces for 4 different years). I have updatemenus with 2 buttons that switch between one scattergeo with legend (51 traces) and another scattergeo with a slider at the bottom (4 traces). I initially set the 4 traces (years) visible = False because I wanted only the 51 traces to appear initially but when I click the button to switch to scattergeo with slider and set first 51 traces visible = False and final 4 traces visible = [True, False, False, False] none of my traces are visible on the map. No sure why this is happening. When I set cities_year visible = True when first creating the scattergeo (i.e. they are visible initially) the traces appear but I don't want that because then I have the all my scatterpoints being plotted twice on top of each other. Here is some code to create dataset: data = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/2014_us_cities.csv') data = data.iloc[:400] # Keep only first 400 samples data.loc[:100, 'year'] = '1990' data.loc[100:200, 'year'] = '1991' data.loc[200:300, 'year'] = '1992' data.loc[300:, 'year'] = '1993' I am using plotly version 2.7.0 and the offline plotting Here is my plotly code: cities = [] for state in data['name'].value_counts().index: data_sub = data.loc[data['name'] == state] city = dict( type = 'scattergeo', visible = True, locationmode = 'USA-states', lon = data_sub['lon'], lat = data_sub['lat'], mode = 'markers', marker = dict( size = 8, color = "rgb(255, 102, 102)", opacity = 0.4, line = dict( width=0.5, color='rgb(255, 102, 102)' ) ), name = state ) cities.append(city) cities_year = [] for year in sorted(data.year.value_counts().index): data_sub = data.loc[data['year'] == year] city = dict( type = 'scattergeo', visible = False, locationmode = 'USA-states', lon = data_sub['lon'], lat = data_sub['lat'], mode = 'markers', marker = dict( size = 8, color = "rgb(255, 102, 102)", opacity = 0.4, line = dict( wi…
has title: Plotly traces not visible after updating menu
answer count: 1
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: python
score: 1
tagged with: plotly
upvote count: 1
has answer: http://stackoverflow.com/a/51293907

http://stackoverflow.com/q/51199548
upvote count: 1
tagged with: python
duplicate of: http://stackoverflow.com/q/23294658
tagged with: recursion
type: AnsweredQuestion
downvote count: 1
linked to: http://stackoverflow.com/q/11356168
type: Question
has body: The code below, when referenced in a separate file is returning incorrect data. When given data that does not match the if/else statements, it will loop through the function again, but the variable in the other file (client_type) will still be the incorrect choice. function: def create_client(): client_type = input() if client_type == 'Mickey': return 'Mickey' elif client_type == 'Jenny': return 'Jenny' elif client_type == 'McElroy': return 'McElroy' else: create_client() call to the function: client_type = functions.create_client() if client_type == 'Mickey': client = functions.client(3, 5, 2) elif client_type == 'Jenny': client = functions.client(5, 2, 3) elif client_type == 'McElroy': client = functions.client(4, 1, 5) else: print('Error on choosing client in function create_client.')
has title: Python function is returning incorrect data
has answer: http://stackoverflow.com/a/51199560
has comment: http://stackoverflow.com/comment/89380778
linked to: http://stackoverflow.com/q/17778372
accepted answer: http://stackoverflow.com/a/51199560
score: 0
duplicate of: http://stackoverflow.com/q/17778372
answer count: 1
favorite count: 0

http://stackoverflow.com/a/51267080
has comment: http://stackoverflow.com/comment/89516341
type: Answer
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/89524143
has body: None of those solutions is more nor less pythonic than the other, and both have pros and cons, depending on your typical use case. And both have a couple issues... the first solution is highly inefficient if you add thousands of data in a row the second keeps on sorting a list that is, most of the time, already sorted. Given Python's builtin sort algorithm behaviour this should not be a huge issue but that's still a few function calls and they don't come for free. and in both cases, elements being exposed as a public attribute breaks encapsulation and make the whole question moot since anyone can either add to .elements without sorting it after or read from .elements without sorting it before... So the very first thing to do is actually to make elements private. Then you want to keep track of wether _elements needs sorting: class Foo: def __init__(self): self._elements = [] self._sorted = True def add_element(self, element): self._elements.append(element) self._sorted = False def read_elements(self): if not self._sorted: self._elements.sort() self._sorted = True for element in self._elements: do_something(element) Now you have a properly encapsulated implementation that only sorts when necessary...
answers question: http://stackoverflow.com/q/51266055

http://stackoverflow.com/comment/89370695
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51193692
has text: @sacul and your comment about timing is also not true, see below for timing results, `numpy` and `zip()` approaches work almost the same time, while `for` loop is almost twice as fast...

http://stackoverflow.com/a/51219822
downvote count: 0
has comment: http://stackoverflow.com/comment/89421174
answers question: http://stackoverflow.com/q/51219752
has comment: http://stackoverflow.com/comment/89421156
has comment: http://stackoverflow.com/comment/89421223
has comment: http://stackoverflow.com/comment/89421133
has comment: http://stackoverflow.com/comment/89421334
type: Answer
score: 1
has comment: http://stackoverflow.com/comment/89421107
has comment: http://stackoverflow.com/comment/89421283
upvote count: 1
has comment: http://stackoverflow.com/comment/89421202
has body: If you can be sure that there are always two double-quotes in the strings you're trying to parse, you can simply use str.split('"')[0] to extract what's between them. &gt;&gt;&gt; s = '''As a manager, he told FIFA TV he communicates his messages in a measured way. "I’m not one of the lads," Southgate explained.''' &gt;&gt;&gt; s.split('"')[1] 'I’m not one of the lads,' Edit: I now see that your input string actually uses the slanted double-quotes, “ and ”, not the standard double-quote, ", in which case I suggest that you use the following instead: s = '''As a manager, he told FIFA TV he communicates his messages in a measured way. “I’m not one of the lads,” Southgate explained.''' print(s[s.find('“') + 1:s.find('”')]) This outputs: I’m not one of the lads,
accepted answer of: http://stackoverflow.com/q/51219752
type: AcceptedAnswer

http://stackoverflow.com/comment/89610121
score: 0
type: Comment
type: QuestionComment
has text: Might be module specific issue. Try using `psycopg2 ` module to execute your query.
comment on: http://stackoverflow.com/q/51317007

http://stackoverflow.com/q/51268856
linked to: http://stackoverflow.com/q/14946371
answer count: 2
tagged with: pandas
downvote count: 0
possible better answer: http://stackoverflow.com/a/51268970
has answer: http://stackoverflow.com/a/51268970
favorite count: 0
has answer: http://stackoverflow.com/a/51268980
tagged with: http://stackoverflow.com/tag/csv
tagged with: datetime
tagged with: python
type: AnsweredQuestion
has body: I am trying to plot my data in the csv file. Currently my dates are not shown properly in the plot also if i am converting it. How can I change it to show the proper dat format as defined Y-m-d? The second question is that I am currently plotting all the dat in one plot but want to have for every Valuegroup one subplot. My code looks like the following: import pandas as pd import matplotlib.pyplot as plt csv_loader = pd.read_csv('C:/Test.csv', encoding='cp1252', sep=';', index_col=0).dropna() csv_loader['Date'] = pd.to_datetime(csv_loader['Date'], format="%Y-%m-%d") print(csv_loader) fig, ax = plt.subplots() csv_loader.groupby('Valuegroup').plot(x='Date', y='Value', ax=ax, legend=False, kind='line') plt.grid(True) The csv file looks like the following: Calcgroup;Valuegroup;id;Date;Value Group1;A;1;20080103;0.1 Group1;A;1;20080104;0.3 Group1;A;1;20080107;0.5 Group1;A;1;20080108;0.9 Group1;B;1;20080103;0.5 Group1;B;1;20080104;1.3 Group1;B;1;20080107;2.0 Group1;B;1;20080108;0.15 Group1;C;1;20080103;1.9 Group1;C;1;20080104;2.1 Group1;C;1;20080107;2.9 Group1;C;1;20080108;0.45
upvote count: 1
accepted answer: http://stackoverflow.com/a/51268980
type: Question
score: 1
tagged with: dataframe
has title: Wrong Dates in Dataframe and Subplots

http://stackoverflow.com/comment/89428546
has text: I'm getting an error about slug when I try to recreate this.
score: 0
comment on: http://stackoverflow.com/q/51187108
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51250214
has comment: http://stackoverflow.com/comment/89479326
accepted answer of: http://stackoverflow.com/q/51250173
downvote count: 0
answers question: http://stackoverflow.com/q/51250173
has body: The order of arguments in the regex object’s sub method is replacement, string: dollar1 = re_leadgarbage.sub("", dollar1) dollar1 = re_trailgarbage.sub("", dollar1) Consider also using \Z (end of string) instead of $ (optional newline, end of string) and note that you can make only one replacement with ^\D+|\D+\z. Also, \d matches all Unicode digits, so consider [^0-9] instead of \D if you don’t want to get ٣.
has comment: http://stackoverflow.com/comment/89480852
has comment: http://stackoverflow.com/comment/89479456
has comment: http://stackoverflow.com/comment/89479410
score: 1
has comment: http://stackoverflow.com/comment/89479345
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89480519
has comment: http://stackoverflow.com/comment/89491888
type: Answer
has comment: http://stackoverflow.com/comment/89491877

http://stackoverflow.com/q/51236252
possible better answer: http://stackoverflow.com/a/51238583
type: Question
has answer: http://stackoverflow.com/a/51238583
has answer: http://stackoverflow.com/a/51238963
answer count: 3
downvote count: 0
tagged with: drop-down-menu
accepted answer: http://stackoverflow.com/a/51238531
linked to: http://stackoverflow.com/q/4915920
favorite count: 0
upvote count: 2
has body: I'm trying to get all data from a website called Correios. On this website, I need to handle some dropdowns which I'm having some issues with, like: It's returning a list with a bunch of empty strings. chrome_path = r"C:\\Users\\Gustavo\\Desktop\\geckodriver\\chromedriver.exe" driver = webdriver.Chrome(chrome_path) lista_x = [] driver.get("http://www2.correios.com.br/sistemas/agencias/") driver.maximize_window() dropdownEstados = driver.find_elements_by_xpath("""//*[@id="estadoAgencia"]""") optEstados = driver.find_elements_by_tag_name("option") for valores in optEstados: print(valores.text.encode()) And what I get from that is: b'' b'ACRE' b'ALAGOAS' b'AMAP\xc3\x81' b'AMAZONAS' b'BAHIA' b'CEAR\xc3\x81' b'DISTRITO FEDERAL' b'ESP\xc3\x8dRITO SANTO' b'GOI\xc3\x81S' b'MARANH\xc3\x83O' b'MINAS GERAIS' b'MATO GROSSO DO SUL' b'MATO GROSSO' b'PAR\xc3\x81' b'PARA\xc3\x8dBA' b'PERNAMBUCO' b'PIAU\xc3\x8d' b'PARAN\xc3\x81' b'RIO DE JANEIRO' b'RIO GRANDE DO NORTE' b'ROND\xc3\x94NIA' b'RORAIMA' b'RIO GRANDE DO SUL' b'SANTA CATARINA' b'SERGIPE' b'S\xc3\x83O PAULO' b'TOCANTINS' b'' b'' b'' b'' b'' b'' b'' b'' b'' b'' b'' b'' b'' b'' b'' b'' b'' b'' b'' b'' b'' b'' b'' b'' b'' b'' b'' How can I remove the empty b" "?
tagged with: python
tagged with: selenium-webdriver
score: 2
type: AnsweredQuestion
tagged with: selenium
has comment: http://stackoverflow.com/comment/89455308
has title: Selenium search by tag name option
tagged with: webdriver
has answer: http://stackoverflow.com/a/51238531

regex
tags question: http://stackoverflow.com/q/51200247
tags question: http://stackoverflow.com/q/51319318
tags question: http://stackoverflow.com/q/51235303
tags question: http://stackoverflow.com/q/51178183
tags question: http://stackoverflow.com/q/51204314
tags question: http://stackoverflow.com/q/51228500
tags question: http://stackoverflow.com/q/51189193
tags question: http://stackoverflow.com/q/51267040
tags question: http://stackoverflow.com/q/51170279
tags question: http://stackoverflow.com/q/51312205
tag name: regex
tags question: http://stackoverflow.com/q/51199256
tags question: http://stackoverflow.com/q/51193073
tags question: http://stackoverflow.com/q/51251909
tags question: http://stackoverflow.com/q/51230093
tags question: http://stackoverflow.com/q/51209153
tags question: http://stackoverflow.com/q/51217598
tags question: http://stackoverflow.com/q/51318777
tags question: http://stackoverflow.com/q/51233383
tags question: http://stackoverflow.com/q/51243464
tags question: http://stackoverflow.com/q/51172657
tags question: http://stackoverflow.com/q/51293154
tags question: http://stackoverflow.com/q/51188878
tags question: http://stackoverflow.com/q/51232799
tags question: http://stackoverflow.com/q/51212853
tags question: http://stackoverflow.com/q/51170530
tags question: http://stackoverflow.com/q/51247349
tags question: http://stackoverflow.com/q/51201020
tags question: http://stackoverflow.com/q/51307191
tags question: http://stackoverflow.com/q/51284448
tags question: http://stackoverflow.com/q/51290694
tags question: http://stackoverflow.com/q/51275995
tags question: http://stackoverflow.com/q/51286833
tags question: http://stackoverflow.com/q/51298027
tags question: http://stackoverflow.com/q/51319019
tags question: http://stackoverflow.com/q/51197175
tags question: http://stackoverflow.com/q/51302523
tags question: http://stackoverflow.com/q/51178459
tags question: http://stackoverflow.com/q/51184305
tags question: http://stackoverflow.com/q/51188700
tags question: http://stackoverflow.com/q/51183238
tags question: http://stackoverflow.com/q/51203260
tags question: http://stackoverflow.com/q/51248360
tags question: http://stackoverflow.com/q/51213111
tags question: http://stackoverflow.com/q/51298698
tags question: http://stackoverflow.com/q/51209233
tags question: http://stackoverflow.com/q/51230548
tags question: http://stackoverflow.com/q/51205044
tags question: http://stackoverflow.com/q/51232412
tags question: http://stackoverflow.com/q/51214979
tags question: http://stackoverflow.com/q/51270894
tags question: http://stackoverflow.com/q/51177121
tags question: http://stackoverflow.com/q/51230486
tags question: http://stackoverflow.com/q/51207723
tags question: http://stackoverflow.com/q/51243399
tags question: http://stackoverflow.com/q/51294386
tags question: http://stackoverflow.com/q/51269242
tags question: http://stackoverflow.com/q/51323703
tags question: http://stackoverflow.com/q/51218064
tags question: http://stackoverflow.com/q/51234900
tags question: http://stackoverflow.com/q/51286999
tags question: http://stackoverflow.com/q/51227601
tags question: http://stackoverflow.com/q/51313585
tags question: http://stackoverflow.com/q/51294237
tags question: http://stackoverflow.com/q/51245613
tags question: http://stackoverflow.com/q/51244034
tags question: http://stackoverflow.com/q/51225317
tags question: http://stackoverflow.com/q/51256658
tags question: http://stackoverflow.com/q/51281729
tags question: http://stackoverflow.com/q/51255230
tags question: http://stackoverflow.com/q/51170763
tags question: http://stackoverflow.com/q/51232748
tags question: http://stackoverflow.com/q/51216402
tags question: http://stackoverflow.com/q/51183066
tags question: http://stackoverflow.com/q/51279846
tags question: http://stackoverflow.com/q/51193354
tags question: http://stackoverflow.com/q/51210853
tags question: http://stackoverflow.com/q/51314570
tags question: http://stackoverflow.com/q/51236164
tags question: http://stackoverflow.com/q/51172416

http://stackoverflow.com/comment/89386092
comment on: http://stackoverflow.com/a/51173958
has text: I will surely give it a try over this weekends
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/51241717
score: 2
has comment: http://stackoverflow.com/comment/89832426
downvote count: 0
favorite count: 0
type: Question
has body: I have created a Cloud ML model that serves online predictions. The model is a simple classification model based on retraining inception v3. I require my model to process many instances (cropped images in my case) in each request. The request body is formatted as follows: instances = [] count = 0 for item in itemMap: w = itemMap[item]['width'] h = itemMap[item]['height'] x1 = itemMap[item]['x'] y1 = itemMap[item]['y'] x2 = x1 + w y2 = y1 + h crop_x1 = int(x1-w/2) crop_x2 = int(x2+w/2) crop_y1 = int(y1-h/5) crop_y2 = int(y2+h/5) #cropped and resized image cropped_image = frame.crop((crop_x1,crop_y1,crop_x2,crop_y2)) resized_crop = cropped_image.resize((299,299)) buffer = BytesIO() resized_crop.save(buffer, format="JPEG") img_str = base64.b64encode(buffer.getvalue()) instances.append({"key":str(count), "image_bytes": {"b64": img_str.decode('utf-8')}}) count += 1 Here are the key parts on my request code: def predict_json(project, model, instances, version=None): """Send json data to a deployed model for prediction. Args: project (str): project where the Cloud ML Engine Model is deployed. model (str): model name. instances ([Mapping[str: Any]]): Keys should be the names of Tensors your deployed model expects as inputs. Values should be datatypes convertible to Tensors, or (potentially nested) lists of datatypes convertible to tensors. version: str, version of the model to target. Returns: Mapping[str: any]: dictionary of prediction results defined by the model. """ # Create the ML Engine service object. # To authenticate set the environment variable # GOOGLE_APPLICATION_CREDENTIALS=&lt;path_to_service_account_file&gt; service = googleapiclient.discovery.build('ml', 'v1') name = 'projects/{}/models/{}'.format(project, model) if version is not None: name += '/versions/{}'.format(version) response = service.projects().predict( name=name, body={'instances': instances} ).execute() if 'error' in response: raise RuntimeError(response['error']) return response['predictions'] a…
tagged with: google-cloud-ml
tagged with: python
upvote count: 2
answer count: 2
has answer: http://stackoverflow.com/a/51363237
has answer: http://stackoverflow.com/a/51255514
tagged with: machine-learning
tagged with: tensorflow
type: UnansweredQuestion
has title: Cloud ML Engine online prediction not scaling
tagged with: google-cloud-platform

http://stackoverflow.com/comment/89451149
has text: If i use like you told me too, the paramaters arrive correctly in the run method but the thread isn't invoked !
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51236032
type: AnswerComment

http://stackoverflow.com/comment/89493665
score: 1
type: AnswerComment
has text: @doctorer: Yes, I'd recommend that. You might try 1, 4, 8, 16, 31, 32, 60-64. Depending on the architecture of your CPU, you'll likely find one of these provides an optimal speed. The 60-64 values "oversubscribe" your CPU, which sometimes gives better results if the CPU can hide memory latency. Using 31 and 60-63 free different amounts of resources for the Python and OpenBLAS threads managing the computation.
comment on: http://stackoverflow.com/a/51257384
type: Comment

http://stackoverflow.com/comment/89467689
comment on: http://stackoverflow.com/q/51242352
type: Comment
score: 0
has text: When you do the average you are converting the dataframe to a single series. Can think of a series as like a single column. There is no need to reference the column name as there is only one. Simply remove the `.wind_speed` part from the `y0` and `xpos` lines above.
type: QuestionComment

http://stackoverflow.com/comment/89470998
has text: @MedAli tried that one out as it is: `In [10]: from sklearn import train_test_split ...: X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 1/3, random_state = 0) Traceback (most recent call last): File "<ipython-input-10-c8c8670e7485>", line 1, in <module> from sklearn import train_test_split ImportError: No module named sklearn`
score: 0
comment on: http://stackoverflow.com/q/51245311
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51313420
score: -1
has comment: http://stackoverflow.com/comment/89604817
type: Answer
answers question: http://stackoverflow.com/q/51313324
downvote count: 2
upvote count: 1
has body: Are you using this library? https://pythonhosted.org/Flask-Session/ The docs suggest importing it this way: from flask.ext.session import Session
has comment: http://stackoverflow.com/comment/100269047

http://stackoverflow.com/comment/89556501
type: QuestionComment
has text: So given something like `Coord = [1,2,3,4,5]`, you want `RHO[1][2][3][4][5]`?
comment on: http://stackoverflow.com/q/51289268
score: 0
type: Comment

http://stackoverflow.com/comment/90228906
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51610175
has text: heatmap generated is different from a density pointer per location
score: 0

http://stackoverflow.com/comment/89424987
type: Comment
type: QuestionComment
has text: @Shashank Singh code worked
comment on: http://stackoverflow.com/q/51221190
score: 0

http://stackoverflow.com/q/51301985
score: 0
tagged with: floating-point
downvote count: 1
type: UnansweredQuestion
tagged with: tuples
has comment: http://stackoverflow.com/comment/89580965
has body: I have a LIST in python, mentioned below. I am trying to convert it from list format to SEQUENCE OF TUPLES. I am able to convert it into a tuple but unable to get the desired output. Can someone please go through the code I have mentioned below ? There should not be any strings in the output like I have in the list. SO i convert it into tuples without string in the output. Expected output = ((4.1,), (4.2,), (4.3,), (4.4,), (4.5,), (4.6,), (4.7,)) sample code to convert List_to_be_converted = sf sf = ['4.1', '4.2', '4.3', '4.4', '4.5', '4.6', '4.7'] convert = tuple((float(x[0]), ) for x in sf) output after running the code convert = ((4.0,), (4.0,), (4.0,), (4.0,), (4.0,), (4.0,), (4.0,)) I am unable to see the decimal values of the output. What can be the possible error? please Thank you a lot for your time
favorite count: 0
has comment: http://stackoverflow.com/comment/89580849
has comment: http://stackoverflow.com/comment/89580856
type: Question
has answer: http://stackoverflow.com/a/51302329
has title: I change the format of a list with floating values to sequence of tuples in PYTHON. But the output i get is not exactly the same
upvote count: 1
tagged with: python
answer count: 1
tagged with: list

http://stackoverflow.com/comment/89370728
has text: You're probably right, but it gets the job done. Thanks!
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51193749

http://stackoverflow.com/comment/89531793
type: QuestionComment
has text: Cannot reproduce. Installing cuckoo in a fresh Python 2.7.10 virtualenv installs python-dateutil 2.4.2 but not pandas. Did you perhaps enable site-packages for the virtualenv?
comment on: http://stackoverflow.com/q/51277060
score: 0
type: Comment

http://stackoverflow.com/comment/89610077
type: QuestionComment
comment on: http://stackoverflow.com/q/51253538
has text: is your scrapy and the middleware on the same python? make a virtualenv: `python3 -m venv ~/virtualenvs/scrapy && source ~/virtualenvs/scrapy/activate && pip install scrapy scrapy_cloudflare_middleware`
score: 0
type: Comment

http://stackoverflow.com/comment/89598136
score: 0
type: Comment
has text: no the files are sorting like this: 1,10,11,12,13,14,15,16,17,18,19,20,21.....52,53,54,9
type: AnswerComment
comment on: http://stackoverflow.com/a/51310734

http://stackoverflow.com/comment/89416211
has text: What operating system are you using?
score: 0
comment on: http://stackoverflow.com/q/51217478
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/90269483
type: Comment
has text: @Martin Can you add an example of this expected result with 5 colours please.
comment on: http://stackoverflow.com/a/51231150
type: AnswerComment
score: 0

http://stackoverflow.com/q/51206648
has answer: http://stackoverflow.com/a/51215393
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89401393
tagged with: python
has body: I am learning mypy, and the first error I got is cannot find module. My file is: from tzwhere import tzwhere tzw = tzwhere.tzwhere() print(tzw) It is runnable by python because tzwhere package is installed. But when I run it through mypy I get this: mypy mp.py mp.py:1: error: Cannot find module named 'tzwhere' mp.py:1: note: (Perhaps setting MYPYPATH or using the "--ignore-missing-imports" flag would help) How do I make it say No library stub file for module 'tzwhere' and deal with stub files instead of Cannot find module?
has title: mypypath: Cannot find module named 'tzwhere'
type: Question
upvote count: 4
has comment: http://stackoverflow.com/comment/89397479
tagged with: mypy
score: 4
has comment: http://stackoverflow.com/comment/89401640
downvote count: 0
answer count: 1

http://stackoverflow.com/q/51212922
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/43559164
downvote count: 0
score: 1
favorite count: 0
has title: update multiple django id's at once
type: Question
has answer: http://stackoverflow.com/a/51213084
tagged with: django
tagged with: python
answer count: 1
has body: I have a django html page where I have multiple records total 3 colomns(id,P_350,P_450) and I want to update at once when I click submit button. It is working fine when I was updating one by one but I wanted to update multiple records so that I added a loop "for id in ids:" in front to access multiple id's; but somehow I did not able to make it work. My questions is: Should I use also getlist method for the other P_350 and P_450 Am I doing correct by looping ids.If not how can I do that ? Here is my view.py file: ids = request.POST.getlist("id") P_350 = request.POST["P_350"] P_450 = request.POST["P_450"] for id in ids: fp_item = fp.objects.get(id=id) items=[P_350,P_450] for index, w in enumerate(items): if index == 0: if len(w) > 1: fp_item.P_350 = w fp_item.save() elif index == 1: if len(w) > 1: fp_item.P_450 = w fp_item.save() Here is my html file input section: {{ field.FP_Item }} {% if field.P_350|length == 0 %} {% else %} {% endif %} {% if field.P_450|length == 0 %} {% else %} {% endif %}
upvote count: 1

http://stackoverflow.com/a/51290462
score: 2
upvote count: 2
accepted answer of: http://stackoverflow.com/q/51289348
answers question: http://stackoverflow.com/q/51289348
has comment: http://stackoverflow.com/comment/89562020
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: To answer the question, the colors for the "bwr" colormap can be obtained via import matplotlib.cm print(matplotlib.cm.datad["bwr"]) which prints ((0.0, 0.0, 1.0), (1.0, 1.0, 1.0), (1.0, 0.0, 0.0)) and that is simply ["blue", "white", "red"]. This may not be too useful for the actual application though. To create a colormap with a wider range of white in the middle, best create the colormap from a list of colors, and possibly their respective values. To this end, the LinearSegmentedColormap.from_list method can be used. from matplotlib.colors import LinearSegmentedColormap colors = [(0, "blue"), (0.4, "white"), (0.6, "white"), (1, "red")] cmap = LinearSegmentedColormap.from_list("bwwr", colors) The numbers are between 0 and 1, need to be ascending and denote the "position" of that respecitive color. The above would create a colormap with a gradient from blue to white between 0 and 0.4, then all white between 0.4 and 0.6, then a gradient from white to red between 0.6 and 1. import numpy as np import matplotlib.pyplot as plt from matplotlib.colors import LinearSegmentedColormap colors = [(0, "blue"), (0.4, "white"), (0.6, "white"), (1, "red")] cmap = LinearSegmentedColormap.from_list("bwwr", colors) a = np.arange(0,100).reshape(10,10) fig, (ax,ax2) = plt.subplots(ncols=2, figsize=(7,3)) im = ax.imshow(a, cmap="bwr") fig.colorbar(im, ax=ax) im2 = ax2.imshow(a, cmap=cmap) fig.colorbar(im2, ax=ax2) ax.set_title("bwr") ax2.set_title("bwwr") plt.show()

http://stackoverflow.com/comment/89523608
type: Comment
type: QuestionComment
score: 2
has text: You are *not comparing equivalent objects*. You are comparing a Python 2 bytestring with a Python 3 Unicode string. At the very least you'd want to compare `sys.getsizeof(u'Hello World')` (Python 2.7: 72, Python 3.6: 60) to use Unicode strings in both places, or `sys.getsizeof(b'Hello World')` (Python 2.7: 48, Python 3.6: 44) to use byte strings in both.
comment on: http://stackoverflow.com/q/51272754

http://stackoverflow.com/comment/89542900
type: AnswerComment
has text: Hello. The confusion matrix shows a lot of thing at the same time. First of all, the performance is higher when the black blocks are on the diagonal. Here, you are very good at predicting the one class but very very bad at predicting the other class. Additionally, from the confusion matrix, you can calculate the sensitivity, specificity, false positive rate, false negative rate etc... I will add some references about the CM in my answer
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51282672

http://stackoverflow.com/q/51274675
score: 0
has comment: http://stackoverflow.com/comment/89527655
upvote count: 1
tagged with: sqlite
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/89527574
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89527564
has comment: http://stackoverflow.com/comment/89527560
has body: I have a text field in a SQLite database table that stores JSON. I want my Python script to query all rows and stuff each JSON string into a single JSON object (or string, since I'm going to send it through a ReST API). What is the best approach for doing so? Note there will be thousands of rows. Thanks!
answer count: 0
tagged with: http://stackoverflow.com/tag/json
type: Question
has title: Python: create JSON obj from JSONified string in DB
has comment: http://stackoverflow.com/comment/89527593

http://stackoverflow.com/q/51289930
tagged with: http://stackoverflow.com/tag/html
has answer: http://stackoverflow.com/a/51289969
has body: So, I have two pages in my app that currently use the same html, and I pass arguments to render_template to specify a couple of things that should differ between the two pages (mostly just headings and table data). Would it be better to have separate html files that both extend a common file?
type: UnansweredQuestion
tagged with: python
type: Question
answer count: 1
tagged with: flask
score: 0
has title: Is it bad practice to have two pages in a flask app use the same html?

http://stackoverflow.com/q/51253312
favorite count: 0
has title: url formatting with beginning & ending date & time using Python
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/51254708
tagged with: python
has body: I'm using Pandas to generate a list of dates and times within a specified range to get query an API. My aim is to query weeks or months on per-hour basis. time_range = pd.date_range('20180601T07:00:0000', '20180701T07:00:0000', freq='H') time_range = time_range.strftime("%Y%m%d"+'T%H:00-0000') yields a list of times in the desired list format. Where I'm encountering difficulty is that the URL is formatted... startdatetime=20180601T07:00-0000&amp;enddatetime=20180601T08:00-0000 I understand I need to start with values 0 &amp; 1 from the Pandas list but I don't how to cycle through. Should I be thinking of a dictionary like... {date1:[hour1, hour2, etc...], date2:[hour1, hour2, etc...], ...} and use a .format where startdatetime={1}&amp;enddatetime={2} ? or should it be more like a for loop... for date in date_range: url = 'http://somename?startdatetime={date}&amp;enddatetime{date2}' urldate = url.format(date=date) urldate2 = url.format(date2=date + 1) Any help is appreciated!
type: AnsweredQuestion
score: 1
tagged with: date-formatting
upvote count: 1
type: Question
downvote count: 0
tagged with: url
has answer: http://stackoverflow.com/a/51254708
tagged with: datetime
answer count: 1

http://stackoverflow.com/comment/89535968
type: AnswerComment
score: 0
type: Comment
has text: Please use this url and help yourself buddy. https://github.com/countercept/python-exe-unpacker/blob/master/pyinstxtractor.py
comment on: http://stackoverflow.com/a/51279150

http://stackoverflow.com/a/51214344
answers question: http://stackoverflow.com/q/51214231
has body: Option 1 any with enumerate Keep your ranges in a list, then use any and enumerate to check if an index is contained in any of the ranges: &gt;&gt;&gt; s = "AAbbbCddEE" &gt;&gt;&gt; ranges = [range(2,5), range(6,8), range(4,9)] &gt;&gt;&gt; ''.join([letter for idx, letter in enumerate(s) if not any(idx in rng for rng in ranges)]) 'AAE' Option 2 Use set difference to identify indices to keep... r = set(range(len(s))) for rng in ranges: r -= set(rng) # {0, 1, 9} ...Then join with a list comprehension &gt;&gt;&gt; ''.join([letter for idx, letter in enumerate(s) if idx in r]) 'AAE' I would highly recommend the second approach. The overhead from calculating the initial set is still much more desirable than having to possibly check every range for each element: # Initial List s = "AAbbbCddEE" ranges = [range(2,5), range(6,8), range(4,9)] %timeit ''.join([letter for idx, letter in enumerate(s) if not any(idx in rng for rng in ranges)]) 8.38 µs ± 220 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each) %%timeit r = set(range(len(s))) for rng in ranges: r -= set(rng) ''.join([letter for idx, letter in enumerate(s) if idx in r]) 3.35 µs ± 59.3 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each) # Much larger list len(s) 100000 len(ranges) 300 %timeit ''.join([letter for idx, letter in enumerate(s) if not any(idx in rng for rng in ranges)]) 3.25 s ± 13.7 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) %%timeit r = set(range(len(s))) for rng in ranges: r -= set(rng) ''.join([letter for idx, letter in enumerate(s) if idx in r]) 18.8 ms ± 90.9 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
has comment: http://stackoverflow.com/comment/89410496
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89410432
score: 4
type: Answer
upvote count: 4
accepted answer of: http://stackoverflow.com/q/51214231
downvote count: 0

http://stackoverflow.com/a/51313971
has body: Do I get it right that your main script runs the other projects ("repositories", but let's call them "subprojects") as child processes, not as an in-process Python calls? If so, you have to: attach PyCharm's debugger to those processes by hand, if they run for a noticeable time or can be paused; or make your main script only print the subproject invocation arguments, but not run it. Then create a new PyCharm run configuration for the subproject in question by hand, and set its command line arguments the way main script does.
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/51278235
upvote count: 1
type: Answer

http://stackoverflow.com/comment/89358350
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51187402
has text: Thanks !! @BurhanKhalid, Agree with your point. I updated question too.

http://stackoverflow.com/comment/90732629
has text: Wrap-Up: In the only reply within a month to this problem. But it requires change of distro for a rather complicated system (elastic search, tikka, vpn, scripts, etc.). That, of course, creates other problems and itself isn't helping with a solution. For now, am I wrong to consider spidev and using 08/15 displays on rock64 non-functional? I'm sorry that we can't provide a secure display for our journalists to verify against, but it seems it is beyond reach.
type: Comment
score: 1
comment on: http://stackoverflow.com/a/51356818
type: AnswerComment

http://stackoverflow.com/comment/89566881
has text: Have you tried some code so far?
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51294657

http://stackoverflow.com/comment/89333713
has text: I think the question is very basic, and not showing the user the basic way to solve the problem first before going to the next higher level may be encouraging bad practice. The user needs to know what is the inefficient way before implementing the efficient way
type: AnswerComment
comment on: http://stackoverflow.com/a/51175403
score: 0
type: Comment

http://stackoverflow.com/comment/89582841
type: Comment
type: QuestionComment
has text: @ThatBird Craig, Harold
comment on: http://stackoverflow.com/q/51303063
score: 1

http://stackoverflow.com/q/51222992
tagged with: python
has body: After installing Odoo it shows only empty page apps not able to install please be a guide this is the screen for after installation
type: Question
has comment: http://stackoverflow.com/comment/89426937
tagged with: odoo
has comment: http://stackoverflow.com/comment/89426319
has title: Odoo app installation not showing
score: 0
has answer: http://stackoverflow.com/a/51239868
has comment: http://stackoverflow.com/comment/89455016
answer count: 1
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89434242

http://stackoverflow.com/comment/89495447
has text: how do you want to handle multiple logs/dicts? give us an example with at least 2 logs
comment on: http://stackoverflow.com/q/51258434
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51287299
favorite count: 0
possible better answer: http://stackoverflow.com/a/51287620
has answer: http://stackoverflow.com/a/51287620
tagged with: python
upvote count: 4
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/89558592
tagged with: complex-numbers
has body: I have a numpy ndarray x of of shape (M,N) where each element in N is a 2 element tuple containing real and imaginary parts of a complex number. I would like to unpack the tuple into another dimension such that my x would now have the shape (M,N,2) My first idea is to seperate the real and imaginary parts into two numpy arrays of shape (M,N) and concatenate them over the second axis so that I can get the desired output. To do so, I tried to access only the real and imaginary parts as follows x[:,:][0] x[:,:][1] However, it returns me the whole array instead of only the real/imaginary parts. Any pointers on how I can proceed? An example array is as follows array([[( 4.82641562, -1.84333128), (-1.29724314, 2.06545141), ( 0.02074953, -1.32518303)], [(-0.81477981, -3.34148138), ( 0.231383 , 1.35495823), ( 1.66341462, -1.33603417)], [( 2.2809137 , -1.17720382), (-1.05115026, -2.09556016), ( 1.57932884, -0.7438237 )], [(-2.2170903 , 0.81147059), ( 0.17489367, 0.15123805), (-1.95151614, -0.5669619 )], [(-2.16413158, 0.44555251), ( 1.2545366 , -0.06933326), ( 1.08469658, 1.71108236)], [(-0.99776606, -0.0607623 ), (-0.11785624, -1.90687216), ( 1.28964911, -1.03083365)], [( 1.65550362, -1.26383881), ( 0.13404437, 1.4402823 ), ( 0.04223597, -1.00992713)], [(-0.4696885 , 2.66014003), (-1.12157114, -1.03019938), ( 2.6312301 , 0.22770433)], [( 1.74457246, -0.91478885), (-0.18861201, 0.75360561), ( 0.27141119, 0.71356903)], [(-0.15940566, 1.26613812), ( 1.28238354, 1.31858431), ( 0.31217745, 0.13244299)]], dtype=[('real', '&lt;f8'), ('imag', '&lt;f8')])
type: Question
tagged with: numpy
tagged with: numpy-ndarray
score: 4
has comment: http://stackoverflow.com/comment/89558756
answer count: 2
has title: Unpacking a numpy ndarray of tuples and add it in a new dimension
has answer: http://stackoverflow.com/a/51287541
accepted answer: http://stackoverflow.com/a/51287541

http://stackoverflow.com/comment/89342315
has text: Thanks. But when I do this, df['New'] contains only zeroes: 0 0.0 1 0.0 2 0.0 3 0.0 4 0.0 5 0.0 6 0.0 7 0.0
comment on: http://stackoverflow.com/a/51179884
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/89429849
has text: @Venom update the question with the full traceback error.
comment on: http://stackoverflow.com/a/51224199
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/51220615
answer count: 2
has title: plotly: TypeError: cannot convert dictionary update sequence element #0 to a sequence
has answer: http://stackoverflow.com/a/51220695
tagged with: python
favorite count: 0
upvote count: 14
score: 13
has body: I have a problem with the project I'm currently working on, so I'm leaving a question. The current contents are drawn in table format by sensor. But a few days ago, when I was working on something, I didn't know how to fix it, so I asked for help. import plotly.plotly as py import plotly.figure_factory as ff from bluepy import sensortag import sys import time import datetime import numpy as np py.sign_in("smrlswja9963","94b4enXKYqyOu4iuPDGG") time.sleep(1.0) tag = sensortag.SensorTag('24:71:89:CC:53:00') tag.IRtemperature.enable() tag.humidity.enable() stream1=py.Stream('liz9v2c0or') stream1.open() i=0 while True: now = datetime.datetime.now() dateTime = now.strftime("%Y-%m-%d %H:%M:%S") A = tag.IRtemperature.read() B = tag.humidity.read() tempt=A[0] humty=B[0] stream1.write({dateTime,tempt,humty}) i+=1 tag.waitForNotifications(3.0) table = go.Table( header=dict(values=["dateTime","tempt","humty"]), cells=dict(values=[[dateTime],[tempt],[humty]]), stream = dict(token='liz9v2c0or',)) data=[table] py.iplot(table, filename="latex table") After executing the following code, the following error occurred. Traceback (most recent call last): File "/home/pi/do it.py", line 27, in &lt;module&gt; stream1.write({dateTime,tempt,humty}) File "/usr/local/lib/python2.7/dist-packages/plotly/plotly/plotly.py", line 632, in write stream_object.update(trace) TypeError: cannot convert dictionary update sequence element #0 to a sequence In this case, the code that I draw the graph using plolty does not have a problem when receiving data from stream, but when I draw table plot. How can I graph here? I'm really curious. Please let me know.
downvote count: 1
accepted answer: http://stackoverflow.com/a/51220695
type: Question
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/70734989
has answer: http://stackoverflow.com/a/70734989
tagged with: plotly

http://stackoverflow.com/comment/89450072
type: Comment
has text: One question @WarrenWeckesser. Is xrandom = sqrtm(H).dot(np.sqrt(y)*u) not supposed to be defined with the inverse of H: xrandom = sqrtm(Hinv).dot(np.sqrt(y)*u) ?
type: AnswerComment
comment on: http://stackoverflow.com/a/51227013
score: 0

http://stackoverflow.com/q/51289323
type: AnsweredQuestion
has title: Trying to access column by index number in a pandas df. The dataframe is created by value.counts() function. It does not work
type: Question
tagged with: dataframe
has comment: http://stackoverflow.com/comment/89556608
has body: I am trying to access a column by its index number in a Pandas data-frame using iloc: new = df_new.iloc[:,0] throws out the error : IndexingError: Too many indexers Other posts on iloc show them working fine. Don't understand why is this happening with me . Please help !! The data-frame is : Games 3862 Entertainment 535 Education 453 Photo &amp; Video 349 Utilities 248 Health &amp; Fitness 180 Productivity 178 Social Networking 167 Lifestyle 144 Music 138 Shopping 122 Sports 114 Book 112 Finance 104 Travel 81 News 75 Weather 72 Reference 64 Food &amp; Drink 63 Business 57 Navigation 46 Medical 23 Catalogs 10 and was created by the code : df_new=obj_df["prime_genre"].value_counts() by count of the number of categories of another data-frame
has answer: http://stackoverflow.com/a/51289494
score: 0
tagged with: pandas
linked to: http://stackoverflow.com/q/11285613
answer count: 1
has comment: http://stackoverflow.com/comment/89557100
has comment: http://stackoverflow.com/comment/89556517
tagged with: python
accepted answer: http://stackoverflow.com/a/51289494
has comment: http://stackoverflow.com/comment/89556706
has comment: http://stackoverflow.com/comment/89556895
has comment: http://stackoverflow.com/comment/89557116

http://stackoverflow.com/a/59948814
answers question: http://stackoverflow.com/q/51215904
has body: The Product that best suits your use-case in GCP is Cloud Task. We are using it for a similar use-case where we are retrieving files from another HTTP server and after some processing storing them in Google Cloud Storage. This GCP documentation describes in full detail the steps to create tasks and using them. You schedule your task programmatically in Cloud Tasks and you have to create task handlers(worker services) in the App Engine. Some limitation For worker services running in App Engine the standard environment: Automatic scaling: task processing must finish in 10 minutes. Manual and basic scaling: requests can run up to 24 hours. the flex environment: all types have a 60 minutes timeout.
downvote count: 0
type: Answer
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/106018207

http://stackoverflow.com/comment/89342674
type: QuestionComment
comment on: http://stackoverflow.com/q/51180071
has text: Is `pip` in your PATH?
score: 0
type: Comment

http://stackoverflow.com/a/51324391
has body: You should use it like: with open("%d.jpg" % (i),'wb') as f: while 1: data = conn.recv(buf) #print(data[:10]) #print "PACKAGE RECEIVED..." f.write(data) if not data: break this way f gets closed automatically when you leave the with block when you exit the while. I guess you need to extend the protocol so that the receiver knows what it gets and that you can let it act on that. Something like a 'begin-of-transfer' ... sending the filename, sending the data, sending 'end-of-transfer' that makes the receiver close the file
has comment: http://stackoverflow.com/comment/89628614
has comment: http://stackoverflow.com/comment/89625583
has comment: http://stackoverflow.com/comment/89625309
score: 0
has comment: http://stackoverflow.com/comment/89624451
type: Answer
answers question: http://stackoverflow.com/q/51323887
has comment: http://stackoverflow.com/comment/89630842

http://stackoverflow.com/q/51258627
tagged with: python-3.x
has title: Loop through url-list in python
score: -3
tagged with: python
downvote count: 4
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51258878
tagged with: urllib
type: Question
has comment: http://stackoverflow.com/comment/89495809
has comment: http://stackoverflow.com/comment/89496140
has body: I am new to python and I have list of url in array and I am iterate list but i am getting error urllib.error.HTTPError: HTTP Error 404: Not Found while fetching url. Online code Editor here what I am doing wrong.Thanks import numpy as np import urllib.request lists = ["https://prod-video-eu-central-1.pscp.tv/Kxf6yJwqKtM611tEBKt0kPlPMKdDsrPZDhjluIPeiCz0XsSq-utkVn2kQk2JdaH3rdLCQc3lqjfnmHZtxa-Xzw/live_thumbnail/eu-central-1/eyJkIjowfQ/latest.jpg?token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCIsInZlcnNpb24iOiIyIn0.eyJBbGxvd2VkUHJvdG9jb2xzIjpbInRodW1iIl0sIkJyb2FkY2FzdElkIjoiMW1ueGVvRHJlVm9HWCIsIkdyYW50VHlwZSI6InJlYWQiLCJHcmFudGVkQXQiOjE1MzExNDM3MzksIkdyYW50ZWRUbyI6IndlYi1yYXRlLWxpbWl0ZWQtNWM5MmJjNmNhZGJiNjdmZjcxZGViMmQzNGQ2NWNjMmYiLCJTdHJlYW1OYW1lIjoiS3hmNnlKd3FLdE02MTF0RUJLdDBrUGxQTUtkRHNyUFpEaGpsdUlQZWlDejBYc1NxLXV0a1ZuMmtRazJKZGFIM3JkTENRYzNscWpmbm1IWnR4YS1YenciLCJleHAiOjE1MzEzMTY1Mzl9.4zU4iPPcrG1pXAl3zNu4Yn1GatUl2kJtja33Zbkpkjk&amp;service=proxsee&amp;digest=7I3s5DHm3nr5QEyw2OM5wvmoP3bUdmrE9ffn5WHZ_a0&amp;ts=765571869", "https://prod-video-eu-central-1.pscp.tv/Kxf6yJwqKtM611tEBKt0kPlPMKdDsrPZDhjluIPeiCz0XsSq-utkVn2kQk2JdaH3rdLCQc3lqjfnmHZtxa-Xzw/live_thumbnail/eu-central-1/eyJkIjowfQ/latest.jpg?token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCIsInZlcnNpb24iOiIyIn0.eyJBbGxvd2VkUHJvdG9jb2xzIjpbInRodW1iIl0sIkJyb2FkY2FzdElkIjoiMW1ueGVvRHJlVm9HWCIsIkdyYW50VHlwZSI6InJlYWQiLCJHcmFudGVkQXQiOjE1MzExNDM3MzksIkdyYW50ZWRUbyI6IndlYi1yYXRlLWxpbWl0ZWQtNWM5MmJjNmNhZGJiNjdmZjcxZGViMmQzNGQ2NWNjMmYiLCJTdHJlYW1OYW1lIjoiS3hmNnlKd3FLdE02MTF0RUJLdDBrUGxQTUtkRHNyUFpEaGpsdUlQZWlDejBYc1NxLXV0a1ZuMmtRazJKZGFIM3JkTENRYzNscWpmbm1IWnR4YS1YenciLCJleHAiOjE1MzEzMTY1Mzl9.4zU4iPPcrG1pXAl3zNu4Yn1GatUl2kJtja33Zbkpkjk&amp;service=proxsee&amp;digest=7I3s5DHm3nr5QEyw2OM5wvmoP3bUdmrE9ffn5WHZ_a0&amp;ts=765571869"] for index,value in enumerate(lists): urllib.request.urlopen(value)
has answer: http://stackoverflow.com/a/51258878
has comment: http://stackoverflow.com/comment/89496333
has comment: http://stackoverflow.com/comment/89496006
has comment: http://stackoverflow.com/comment/89495810
upvote count: 1
has comment: http://stackoverflow.com/comment/89496247
answer count: 1
has comment: http://stackoverflow.com/comment/89495957
favorite count: 0

http://stackoverflow.com/q/51212178
tagged with: python
has title: Python Custom Exception
has comment: http://stackoverflow.com/comment/89405296
answer count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: error-handling
score: 2
has comment: http://stackoverflow.com/comment/89405517
has body: i have never done anything serious with python, but i found it very handy for what i wanted to do. I'd like to ask a simple question, how do i raise a custom exception if the third party class already raises it? I am using This class to make asyncronous sql query on my database, and it raises "UNIQUE constraint failed" which is fine for me but i don't want it to log it. This is my simple code try: querypost = "INSERT INTO post(link,Commenti,data) VALUES('"+link+"','"+str(n_commenti)+"','"+str(data)+"')" sql_worker.execute(querypost); except (IntegrityError) as error: print("test") The problem with this is that it never reaches my print and it prints his own excpetion. How do i make it shut up? EDIT: This piece of code made the logger suppress the unwanted message: logging.getLogger("sqlite3worker").setLevel(logging.CRITICAL) Thanks to @AChampion
type: Question
downvote count: 0
linked to: http://stackoverflow.com/q/1319615
has comment: http://stackoverflow.com/comment/89405199
has comment: http://stackoverflow.com/comment/89405354
favorite count: 0
has comment: http://stackoverflow.com/comment/89405501
tagged with: exception
has comment: http://stackoverflow.com/comment/89405424

http://stackoverflow.com/comment/89609579
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51316090
has text: Thanks! This was very helpful. I also found that there was an extra space at the beginning of the file which resulted in a keyerror, so I used this: `df = pd.read_csv('filename.dat', delim_whitespace=True, encoding="utf-8-sig") df.sort_values("PHASE")`

http://stackoverflow.com/comment/89436741
type: Comment
comment on: http://stackoverflow.com/a/51228411
score: 0
type: AnswerComment
has text: Nope, you actually were impacting the running time of the game step because your call to `model` was creating `tf.Tensor`s, which takes time.

http://stackoverflow.com/comment/89606655
comment on: http://stackoverflow.com/q/51314956
has text: Your function returns when it finds the first match, and doesn't process the rest of the funds. Is that really what you want to do?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89402197
score: 0
has text: it calls the 'report' function from test.cmd... and if i run it via the cmd prompt, i don't get all that DEBUG info above... and if I turn on DEBUG on test.cmd (there's a setting), it gives me a different DEBUG than above leading me to believe it has to come from Python
comment on: http://stackoverflow.com/q/51210433
type: QuestionComment
type: Comment

http://stackoverflow.com/a/51264953
has comment: http://stackoverflow.com/comment/89509949
answers question: http://stackoverflow.com/q/51264748
has body: You can join the two dataframes using the item_id column. For this you first need to set the indices correctly, reset it afterwards and remove the superflous column: df_bill = df_bill.set_index("item_id") df_item = df_item.set_index("item_id") df = df_bill.join(df_item).reset_index() df.drop(columns=["item_id"], inplace=True) Or, as one chain of actions: df = (df_bill.set_index("item_id") .join(df_item.set_index("item_id")) .reset_index() .drop(columns=["item_id"])) Or, probably the easiest, using pandas.DataFrame.merge: df = df_bill.merge(df_item).drop(columns=["item_id"]) All of them mess up the order of bill_no, though: bill_no item_name 0 201 Vegetables 1 204 Vegetables 2 202 Noodles 3 203 Dairy Products 4 205 Ice Cream However, you can always call df.sort_values("bill_no") to sort it again: bill_no item_name 1 201 Vegetables 0 202 Noodles 3 203 Dairy Products 2 204 Vegetables 4 205 Ice Crea
downvote count: 0
type: Answer
score: 2
upvote count: 2

http://stackoverflow.com/comment/89469231
type: QuestionComment
has text: I have added the entire loop alogrithm so that you can understand what cfile is
score: 0
comment on: http://stackoverflow.com/q/51244581
type: Comment

http://stackoverflow.com/comment/123755777
type: Comment
comment on: http://stackoverflow.com/a/51313562
type: AnswerComment
has text: Which of those ref-doc links, did you use to formulate the `fields`, anyway? I'm not finding it anywhere.
score: 0

http://stackoverflow.com/q/51250296
has title: Dlib face detection terrible performance on C++, good in python, why?
has comment: http://stackoverflow.com/comment/89497082
tagged with: c++
tagged with: dlib
has body: I am trying to write a simple face detection algorithm using OpenCV for camera capture and Dlib for face detection (using Histogram of Oriented Gradients algorithm). Using Python, I get a decent performance with around 20 fps. However, the same-ish code in C++ has very poor performance, with each dlib's detection process taking around 4 seconds. Does anyone know what's happening ? I did some optimization, but nothing really improve performances : image is reduced to 640x480 I compiled dlib with AVX instructions enabled I also tried to compile with -0fast flag... Here are the codes: In C++: #include "opencv2/objdetect.hpp" #include "opencv2/highgui.hpp" #include "opencv2/imgproc.hpp" #include <dlib/opencv.h> #include <dlib/image_processing/frontal_face_detector.h> #include <dlib/image_processing.h> using namespace dlib; using namespace std; int main(){ cv::VideoCapture cap(0); vector<cv::Rect> facesCV; vector<rectangle> faces; frontal_face_detector detector = get_frontal_face_detector(); cv::namedWindow("test"); cv::Mat frame, small; if (!cap.isOpened()) { cerr << "Unable to connect to camera" << endl; return 1; } while (true) { // Grab a frame if (!cap.read(frame)) { break; } cv::resize(frame, small, {640, 480}); cv_image<rgb_pixel> cimg(small); // Detect faces faces = detector(cimg); for (auto &f : faces) { facesCV.emplace_back(cv::Point((int) f.left(), (int) f.top()), cv::Point((int) f.right(), (int) f.bottom())); } for (auto &r : facesCV) { cv::rectangle(small, r, {0, 255, 0}, 2); } cv::imshow("test", small); cv::waitKey(1); faces.clear(); facesCV.clear(); } } In Python : import argparse import cv2 import dlib #initialize face detector detector = dlib.get_frontal_face_detector() #initialize video source cam = cv2.VideoCapture(0) window = cv2.namedWindow("camera") while True: ret, image = cam.read() if ret is True: gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) gray =cv2.resize(gray, (640, 480)) for r in detector(gray, 0): cv2.rectangle(image, (r.left(), r.top()),…
type: AnsweredQuestion
score: 4
has answer: http://stackoverflow.com/a/51628855
type: Question
upvote count: 4
answer count: 2
has comment: http://stackoverflow.com/comment/89479502
downvote count: 0
has comment: http://stackoverflow.com/comment/90221437
favorite count: 0
has comment: http://stackoverflow.com/comment/89479578
has comment: http://stackoverflow.com/comment/89497476
possible better answer: http://stackoverflow.com/a/52364883
has answer: http://stackoverflow.com/a/52364883
tagged with: python
accepted answer: http://stackoverflow.com/a/51628855

http://stackoverflow.com/comment/89501199
type: Comment
has text: I have updated my post ;) Please accept the answer if it is fine with you
comment on: http://stackoverflow.com/a/51261571
score: 0
type: AnswerComment

http://stackoverflow.com/comment/89439184
has text: After I crop "Image", I use "image_to_string" to extract the text ( from pytesseract import image_to_string) .So maybe this way is not effective . I tried your suggestion now .But I am beginner with this issue so could you please send me the link that you think can be useful . I really appreciate and sorry because I take much of your time.
type: Comment
score: 0
comment on: http://stackoverflow.com/a/51229384
type: AnswerComment

http://stackoverflow.com/a/51299624
has body: Python 3.x maketrans and translate have all the basic functionality of their Python 2 predecessors, and more—but they have a different API. So, you have to understand what they're doing to use them. translate in 2.x took a very simple table, make by string.maketrans, plus a separate deletechars list. In 3.x, the table is more complicated (in large part because it's now translating Unicode characters, not bytes, but it also has other new features). The table is made by a static method str.maketrans instead of a function string.maketrans. And the table includes the deletions list, so you don't need a separate argument to translate. From the docs: static str.maketrans(x[, y[, z]]) This static method returns a translation table usable for str.translate(). If there is only one argument, it must be a dictionary mapping Unicode ordinals (integers) or characters (strings of length 1) to Unicode ordinals, strings (of arbitrary lengths) or None. Character keys will then be converted to ordinals. If there are two arguments, they must be strings of equal length, and in the resulting dictionary, each character in x will be mapped to the character at the same position in y. If there is a third argument, it must be a string, whose characters will be mapped to None in the result. So, to make a table that deletes all punctuation and does nothing else in 3.x, you do this: table = str.maketrans('', '', string.punctuation) And to apply it: translated = s.translate(table) Meanwhile, since you're dealing with Unicode, are you sure string.punctuation is what you want? As the docs say, this is: String of ASCII characters which are considered punctuation characters in the C locale. So, for example, curly quotes, punctuation used in languages other than English, etc. will not be removed. If that's an issue, you'd have to do something like this: translated = ''.join(ch for ch in s if unicodedata.category(ch)[0] != 'P')
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51299228
type: Answer
accepted answer of: http://stackoverflow.com/q/51299228
score: 2
upvote count: 2

http://stackoverflow.com/q/51259361
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89497565
has comment: http://stackoverflow.com/comment/89500455
has comment: http://stackoverflow.com/comment/89587937
tagged with: scikit-image
tagged with: image-processing
type: Question
upvote count: 4
tagged with: numpy
has answer: http://stackoverflow.com/a/51264985
has title: Smooth a bumpy circle
downvote count: 0
has comment: http://stackoverflow.com/comment/89498537
score: 4
has comment: http://stackoverflow.com/comment/89498294
has answer: http://stackoverflow.com/a/51261231
accepted answer: http://stackoverflow.com/a/51264985
answer count: 3
has comment: http://stackoverflow.com/comment/89498426
linked to: http://stackoverflow.com/q/22146383
possible better answer: http://stackoverflow.com/a/51267877
tagged with: python
has answer: http://stackoverflow.com/a/51267877
favorite count: 0
tagged with: geometry
has body: I am detecting edges of round objects and am obtaining "bumpy" irregular edges. Is there away to smooth the edges so that I have a more uniform shape? For example, in the code below I generate a "bumpy" circle (left). Is there a smoothing or moving average kind of function I could use to obtain or approximate the "smooth" circle (right). Preferably with some sort of parameter I can control as my actual images arn't perfectly circular. import numpy as np import matplotlib.pyplot as plt fig, (bumpy, smooth) = plt.subplots(ncols=2, figsize=(14, 7)) an = np.linspace(0, 2 * np.pi, 100) bumpy.plot(3 * np.cos(an) + np.random.normal(0,.03,100), 3 * np.sin(an) + np.random.normal(0,.03,100)) smooth.plot(3 * np.cos(an), 3 * np.sin(an))
linked to: http://stackoverflow.com/q/36042396

http://stackoverflow.com/comment/89620014
score: 0
type: Comment
type: QuestionComment
has text: Also, `addressof(pointer(self))` is wrong... how do you think you can *read this* value after modification if you don't store it anywhere!
comment on: http://stackoverflow.com/q/51321962

http://stackoverflow.com/comment/89473565
comment on: http://stackoverflow.com/a/51245365
score: 0
type: AnswerComment
has text: Great.. Let me try this as well.. BTW, can we have more than 1 Try & Except block in a code, you see I already have a try & except block in my code. Sorry for asking such as basic question, I am quite new to Python.
type: Comment

http://stackoverflow.com/q/51228959
has comment: http://stackoverflow.com/comment/89439496
answer count: 0
type: UnansweredQuestion
tagged with: python
has body: I am using a Xarray Dataset to contain data I'm feeding into a TensorFlow DNN, and when I call the train() function I eventually get this error: TypeError: Cannot convert value dtype('&lt;M8[ns]') to a TensorFlow DType. My assumption is that this is because of the dtype of the dataset's time dimension/coordinate variable is datetime64[ns] which maps to the &lt;M8[ns] dtype: In [1]: np.dtype('datetime64[ns]') == np.dtype('&lt;M8[ns]') Out[1]: True I'd like to modify the Dataset so that the time dimension/coordinate variable instead has an integer type that will perhaps be more palatable to TensorFlow. In the past, I've always used integer types for time variables along with units such as 'days since 2000-01-01 00:00:00'. In this case, if using an integer dtype the units would need to be in minutes or seconds since the time steps are in 30-minute increments. Some info around my current time variable: In [2]: ds['time'].coords['time'] Out[2]: &lt;xarray.DataArray 'time' (time: 720)&gt; array(['2000-12-27T00:00:00.000000000', '2000-12-27T00:30:00.000000000', '2000-12-27T00:59:59.000000000', ..., '2001-01-10T22:30:00.000000000', '2001-01-10T23:00:00.000000000', '2001-01-10T23:29:59.000000000'], dtype='datetime64[ns]') Coordinates: * time (time) datetime64[ns] 2000-12-27 2000-12-27T00:30:00 ... Attributes: long_name: time bounds: time_bnds In [3]: ds['time'].encoding Out[3]: {'calendar': 'noleap', 'dtype': dtype('float64'), 'original_shape': (720,), 'source': '/content/fv091x180L26_dry_HS.cam.h0.2000-12-27-00000.nc', 'units': 'days since 2000-12-27 00:00:00'} Is there a function typically used for this sort of conversion, or do I just roll my own using timedeltas, etc.? Could I somehow request for xarray to convert the time variable into something more vanilla when reading from NetCDF? xarray.open_dataset() with decode_times=False?
upvote count: 5
tagged with: tensorflow
type: Question
score: 5
downvote count: 0
favorite count: 0
has title: Python/Xarray: How to convert time dtype from datetime64[ns] to integer (with appropriate units)?
tagged with: python-xarray
tagged with: pandas
has comment: http://stackoverflow.com/comment/89608258

http://stackoverflow.com/comment/89599546
comment on: http://stackoverflow.com/a/51294965
type: Comment
has text: I see, thanks. I am trying to expand the array with random 0,1 values just to get an initial idea of resize function. I though that using resize was a good alternative to create a file and expand it later in order not to load all into memory.
score: 0
type: AnswerComment

http://stackoverflow.com/a/51325816
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/89782147
has body: The following code should achieve your desired results. from pymongo import MongoClient client = MongoClient() db = client.stackoverflow collection = db.stackoverflow a = {"Customers":{ "Payment":{ "CustomerDetails":{ "Source":"Visa Card", "Name" :"John"}}}} collection.insert(a) # Prints object before update. cur = collection.find_one({"Customers.Payment.CustomerDetails.Name":"John"}) print(cur) final = {"CustomerPayable":{"Month":"Feb-1FN-2018","Details": {"Code":"ghg23","AmtPayable": "123.00"}}} collection.update({"Customers.Payment.CustomerDetails.Name":"John"}, {'$push':{'Customers.Payment.Output':final}}) # Prints object after update. cur = collection.find_one({"Customers.Payment.CustomerDetails.Name":"John"}) print(cur) A couple things wrong with your code are: In you final declaration you tried to use dictionary syntax inside of a list. In your update query you don't have a field called UserID for I changed it to query on Name Anyways, I hope this helps.
answers question: http://stackoverflow.com/q/51316992

http://stackoverflow.com/comment/89334188
type: QuestionComment
comment on: http://stackoverflow.com/q/51175606
score: 2
type: Comment
has text: Readline() is probably not what you are after, as it doesnt appear that your data is terminated with a linefeed, "\n", so try read() Instead, Equally you may just be too impatient, the serial port will say there is data there when it has only received the first character, so your buffer.decode may behave weirdly when only fed 1 or 2 characters

http://stackoverflow.com/q/51264303
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/52657280
has body: In python, is it possible to set application context to the second gui which is invoked by the GUI under test. Ex: We start an application called test1.exe using startApplication. Clicking a button in text1.exe GUI invokes another GUI application called test2.exe. Now is it possible to set application context to test2.exe GUI?
type: Question
score: 0
answer count: 2
accepted answer: http://stackoverflow.com/a/51267535
has answer: http://stackoverflow.com/a/52657280
has title: Squish set application context to aut started by aut under test
tagged with: squish
tagged with: python
has answer: http://stackoverflow.com/a/51267535
tagged with: qt

http://stackoverflow.com/q/51245613
has comment: http://stackoverflow.com/comment/89469903
possible better answer: http://stackoverflow.com/a/51246271
type: Question
score: 0
answer count: 2
upvote count: 1
downvote count: 1
has body: Requirement: Replace the text line occurrence of "url: http://some.web.com/GVH-JBoss.ear" based on a text in previous line i.e "GVH:" with a new text [say: url: ftp://new.web.com/new.ear]. Example: Consider text lines as below: GVH: url: http://some.web.com/GVH-JBoss.ear sha1: 7b7b797735822d411c288d14510e9e023001d3ae VID: url: http://some.web.com/VID.ear sha1: 2fcac8bdcfadcfc12f0a7dfef0bad01db5f8f8a8 Expected: GVH: url: ftp://new.web.com/new.ear sha1: 7b7b797735822d411c288d14510e9e023001d3ae VID: url: http://some.web.com/VID.ear sha1: 2fcac8bdcfadcfc12f0a7dfef0bad01db5f8f8a8 I tried using python regex [re.sub() method] to achieve this: re.sub(r'\s+GVH:[\s]*\s+url:\s\w+.*ear', 'url: ftp://new.web.com/new.ear', line.rstrip(), re.MULTILINE) Other Regexes tried to match this specified pattern: 1. \s+GVH:[\s]*\s+url:\s\w+.*ear 2. (\s+GVH:\n)?\s*url:\s+\w+.*ear$ 3. (\s+GVH:\n)?\s*url:\s+\w+.*ear$ 4. [(?<=GVH:\s).*url:\s\w+.*ear$] 5. (?<=\sGVH:[\s\S])url: \w+.*ear 6. [\s]GVH:[\s\S](?=(\s+url: [\w]\.ear) 7. (^.*GVH:[\s]?$)|(^.*url:\s\w+.*ear$)` With all these regexes, Was able to find the text of either of the lines only but not both. All of them failed to capture and replace those lines of text. Need help in this regard.
favorite count: 0
has answer: http://stackoverflow.com/a/51246271
has title: Replace a text line based on a pattern in previous text line using regular expression in Python
has answer: http://stackoverflow.com/a/51245765
accepted answer: http://stackoverflow.com/a/51245765
has comment: http://stackoverflow.com/comment/89470355
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/89469721
type: AnsweredQuestion

http://stackoverflow.com/q/51225833
answer count: 1
downvote count: 1
tagged with: unicode
favorite count: 0
has answer: http://stackoverflow.com/a/51225889
tagged with: python
upvote count: 0
type: UnansweredQuestion
tagged with: emoji
has title: python convert English emoji to string
tagged with: python-unicode
score: -1
type: Question
has body: I have the following text: / As I understand this is an English emoji, so I want to make it to: wife / mama So I can use my lang_detector which not recognize this text. Thanks.

http://stackoverflow.com/comment/89502424
comment on: http://stackoverflow.com/q/51261926
type: QuestionComment
has text: Welcome to Stackoverflow. Take a big breath and edit your post please. Due to all the CAPS and help screams you put there it is difficult to understand what you did. Please describe your problem. Tell us what you have tried until now. For guidance please check the [how to ask](https://stackoverflow.com/help/how-to-ask) page. Thank you
type: Comment
score: 1

http://stackoverflow.com/comment/89502562
score: 0
type: Comment
type: QuestionComment
has text: Ok I have added the queries. But I got the data from excel sheet and then sent the data to an API and storing the response from API and storing the result in mySQL. Now I am accessing the response from python with same data from same excel sheet.
comment on: http://stackoverflow.com/q/51261964

http://stackoverflow.com/a/51168227
has body: Indeed PUT/POST but also: @app.route('/v1/myapi/editperson/&lt;int:id_person&gt;)', methods=['PUT']) vs. @app.route('/v1/myapi/editperson/&lt;int:id_person&gt;', methods=['PUT'])
accepted answer of: http://stackoverflow.com/q/51167985
score: 4
upvote count: 4
type: AcceptedAnswer
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/51167985

http://stackoverflow.com/q/51213428
tagged with: range
tagged with: python
has comment: http://stackoverflow.com/comment/89408100
answer count: 0
has body: I am trying to process only k (10) portions of a list of lists at a time. The problem is that there are remainders (quotient) from dividing by 10 so I want to also process the remaining. Is there an elegant solution to this? so far here is my code: for x10 in np.arange(0, len(candidates), 10): indexed = enumerate([list(enumerate(entry)) for entry in candidatesx10-10:x10]) Not a duplicate: I dont want to split the list into evenly sized chunks but into multiples of 10 Update: turns out x10:x10+10 did it... thought that would give me out of index error, strange
upvote count: 1
has comment: http://stackoverflow.com/comment/89408767
type: Question
has comment: http://stackoverflow.com/comment/89408832
tagged with: slice
has comment: http://stackoverflow.com/comment/89407747
linked to: http://stackoverflow.com/q/312443
downvote count: 0
score: 1
has title: Iteratively slice list until end
tagged with: iteration
favorite count: 0
duplicate of: http://stackoverflow.com/q/312443
type: UnansweredQuestion

http://stackoverflow.com/comment/90146409
type: AnswerComment
has text: Also, in your current version of the answer, there are non-trivial steps for a final solution. For example, you write `When you're done, call ...`, but what does it mean to be done? An empty queue? All other tasks end? So please complete your answer (include all code) and I will accept it.
type: Comment
comment on: http://stackoverflow.com/a/51253257
score: 0

http://stackoverflow.com/comment/89415380
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51217015
has text: @BowlingHawk95 it works fine in linux, and on windows the file associations system mean that you can run them without python prefix even if there isn't a shebang. But actually the shebang causes issues in python 3 (with `py` wrapper trying to interpret it)

http://stackoverflow.com/q/51239301
has answer: http://stackoverflow.com/a/51247318
tagged with: python
has comment: http://stackoverflow.com/comment/89467770
tagged with: heatmap
linked to: http://stackoverflow.com/q/48459801
type: AnsweredQuestion
has title: matplotlib/seaborn heatmap using pandas dataframe with datetime index
tagged with: matplotlib
type: Question
has answer: http://stackoverflow.com/a/51375105
has comment: http://stackoverflow.com/comment/89470008
has body: my dataframe looks like this: timestamp a b c 2018-07-04 08:11:54.170 5.732026 7.930378 8.606152 2018-07-04 08:15:01.910 5.483141 8.040632 8.414517 2018-07-04 08:23:09.700 5.454963 7.634940 8.940616 2018-07-04 08:25:17.490 6.031954 7.256924 8.380531 2018-07-04 08:42:25.290 5.860383 7.488524 8.358526 2018-07-04 09:16:33.300 5.654590 7.697418 8.476449 2018-07-04 09:27:40.830 5.277766 7.817510 8.887601 2018-07-04 09:33:48.620 5.568183 7.752958 9.019584 2018-07-04 09:45:56.410 5.886682 7.326519 8.714343 2018-07-04 09:50:04.200 6.141217 7.462479 8.745352 2018-07-04 10:13:11.950 5.894507 7.515888 8.752824 2018-07-04 10:19:19.740 5.720255 7.387331 8.755654 It has an index containing datetime timestamps. The other 3 columns have float values. I'd like to create a heatmap with matplotlib/seaborn which looks like this (please note the x-axis): This picture was manually edited. Here's my code snippet: import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import matplotlib.dates as mdates from matplotlib.dates import DayLocator, HourLocator, DateFormatter, drange import datetime as dt df = pd.DataFrame() df['timestamp']=['2018-07-04 08:11:54.170000', '2018-07-04 08:15:01.910000', '2018-07-04 08:23:09.700000', '2018-07-04 08:25:17.490000', '2018-07-04 08:42:25.290000', '2018-07-04 09:16:33.300000', '2018-07-04 09:27:40.830000', '2018-07-04 09:33:48.620000', '2018-07-04 09:45:56.410000', '2018-07-04 09:50:04.200000', '2018-07-04 10:13:11.950000', '2018-07-04 10:19:19.740000'] df['a']=[5.732026, 5.483141, 5.454963, 6.031954, 5.860383, 5.654590, 5.277766, 5.568183, 5.886682, 6.141217, 5.894507, 5.720255] df['b']=[7.930378, 8.040632, 7.634940, 7.256924, 7.488524, 7.697418, 7.817510, 7.752958, 7.326519, 7.462479, 7.515888, 7.387331] df['c']=[8.606152, 8.414517, 8.940616, 8.380531, 8.358526, 8.476449, 8.887601, 9.019584, 8.714343, 8.745352, 8.752824, 8.755654] df=df.set_index(['timestamp']) df.index = pd.to_datetime(df.index) fig, axHM = plt.subplots(1,1, figsize=(…
score: 4
upvote count: 4
answer count: 2
tagged with: pandas
downvote count: 0
accepted answer: http://stackoverflow.com/a/51375105
favorite count: 0
possible better answer: http://stackoverflow.com/a/51247318

http://stackoverflow.com/comment/89622249
type: AnswerComment
comment on: http://stackoverflow.com/a/51323424
has text: @hntrandrew You should probably spend some time working through the official Python tutorial that blue_note linked. It will make it easier for you to understand the BeautifulSoup tutorial. Also see [What tutorial should I read?](https://sopython.com/wiki/What_tutorial_should_I_read%3F)
score: 0
type: Comment

http://stackoverflow.com/a/51207765
score: 3
accepted answer of: http://stackoverflow.com/q/51204835
answers question: http://stackoverflow.com/q/51204835
upvote count: 3
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89397308
type: Answer
downvote count: 0
has body: Unless I misunderstand the question, you just want the product of the sub-lists, although you have to wrap any single elements into lists first. &gt;&gt;&gt; from itertools import product &gt;&gt;&gt; arr = ['a', ['e', 'r', 't'], ['c', 'd']] &gt;&gt;&gt; listified = [x if isinstance(x, list) else [x] for x in arr] &gt;&gt;&gt; listified [['a'], ['e', 'r', 't'], ['c', 'd']] &gt;&gt;&gt; list(product(*listified)) [('a', 'e', 'c'), ('a', 'e', 'd'), ('a', 'r', 'c'), ('a', 'r', 'd'), ('a', 't', 'c'), ('a', 't', 'd')]

http://stackoverflow.com/q/51210220
accepted answer: http://stackoverflow.com/a/51221498
tagged with: elementtree
tagged with: http://stackoverflow.com/tag/xml
has body: Hello I am making a requests call to return order data from a online store. My issue is that once I have passed my data to a root variable the method iter is not returning the correct results. e.g. Display multiple tags of the same name rather than one and not showing the data within the tag. I thought this was due to the XML not being correctly formatted so I formatted it by saving it to a file using pretty_print but that hasn't fixed the error. How do I fix this? - Thanks in advance Code: import requests, xml.etree.ElementTree as ET, lxml.etree as etree url="http://publicapi.ekmpowershop24.com/v1.1/publicapi.asmx" headers = {'content-type': 'application/soap+xml'} body = """<?xml version="1.0" encoding="utf-8"?> <soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope"> <soap12:Body> my_api_key 01/07/2018 04/07/2018 </soap12:Body> </soap12:Envelope>""" #send request to ekm r = requests.post(url,data=body,headers=headers) #save output to file file = open("C:/Users/Mark/Desktop/test.xml", "w") file.write(r.text) file.close() #take the file and format the xml x = etree.parse("C:/Users/Mark/Desktop/test.xml") newString = etree.tostring(x, pretty_print=True) file = open("C:/Users/Mark/Desktop/test.xml", "w") file.write(newString.decode('utf-8')) file.close() #parse the file to get the roots tree = ET.parse("C:/Users/Mark/Desktop/test.xml") root = tree.getroot() #access elements names in the data for child in root.iter('*'): print(child.tag) #show orders elements attributes tree = ET.parse("C:/Users/Mark/Desktop/test.xml") root = tree.getroot() for order in root.iter('{http://publicapi.ekmpowershop.com/}Order'): out = {} for child in order: if child.tag in ('OrderID'): out[child.tag] = child.text print(out) Elements output: {http://publicapi.ekmpowershop.com/}Orders {http://publicapi.ekmpowershop.com/}Order {http://publicapi.ekmpowershop.com/}OrderID {http://…
tagged with: python
tagged with: python-requests
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89400992
type: Question
has comment: http://stackoverflow.com/comment/89403580
has title: XML not returning correct child tags/data in Python
answer count: 1
score: 0
has answer: http://stackoverflow.com/a/51221498

http://stackoverflow.com/comment/89604431
type: AnswerComment
has text: @sariaGoudarzi `os.makedirs()` will take care of that.
score: 0
comment on: http://stackoverflow.com/a/51312945
type: Comment

pandas
tags question: http://stackoverflow.com/q/51265196
tags question: http://stackoverflow.com/q/51254735
tags question: http://stackoverflow.com/q/51289736
tags question: http://stackoverflow.com/q/51277269
tags question: http://stackoverflow.com/q/51248307
tags question: http://stackoverflow.com/q/51220591
tags question: http://stackoverflow.com/q/51226947
tags question: http://stackoverflow.com/q/51193342
tags question: http://stackoverflow.com/q/51242352
tags question: http://stackoverflow.com/q/51300956
tags question: http://stackoverflow.com/q/51310072
tags question: http://stackoverflow.com/q/51255237
tags question: http://stackoverflow.com/q/51300483
tags question: http://stackoverflow.com/q/51219830
tags question: http://stackoverflow.com/q/51205373
tags question: http://stackoverflow.com/q/51278473
tags question: http://stackoverflow.com/q/51240096
tags question: http://stackoverflow.com/q/51193834
tags question: http://stackoverflow.com/q/51171560
tags question: http://stackoverflow.com/q/51174691
tags question: http://stackoverflow.com/q/51191589
tags question: http://stackoverflow.com/q/51209403
tags question: http://stackoverflow.com/q/51323311
tags question: http://stackoverflow.com/q/51249014
tags question: http://stackoverflow.com/q/51305486
tags question: http://stackoverflow.com/q/51219790
tags question: http://stackoverflow.com/q/51189962
tags question: http://stackoverflow.com/q/51199256
tags question: http://stackoverflow.com/q/51228764
tags question: http://stackoverflow.com/q/51307061
tags question: http://stackoverflow.com/q/51289898
tags question: http://stackoverflow.com/q/51249813
tags question: http://stackoverflow.com/q/51243213
tags question: http://stackoverflow.com/q/51313461
tags question: http://stackoverflow.com/q/51262355
tags question: http://stackoverflow.com/q/51269615
tags question: http://stackoverflow.com/q/51196382
tags question: http://stackoverflow.com/q/51272642
tags question: http://stackoverflow.com/q/51230915
tags question: http://stackoverflow.com/q/51315912
tags question: http://stackoverflow.com/q/51287671
tags question: http://stackoverflow.com/q/51304669
tags question: http://stackoverflow.com/q/51296758
tags question: http://stackoverflow.com/q/51318950
tags question: http://stackoverflow.com/q/51225358
tags question: http://stackoverflow.com/q/51262367
tags question: http://stackoverflow.com/q/51180858
tags question: http://stackoverflow.com/q/51265150
tags question: http://stackoverflow.com/q/51189676
tags question: http://stackoverflow.com/q/51285559
tags question: http://stackoverflow.com/q/51287333
tags question: http://stackoverflow.com/q/51192250
tags question: http://stackoverflow.com/q/51281477
tags question: http://stackoverflow.com/q/51287972
tags question: http://stackoverflow.com/q/51246549
tags question: http://stackoverflow.com/q/51267876
tags question: http://stackoverflow.com/q/51283361
tags question: http://stackoverflow.com/q/51280121
tags question: http://stackoverflow.com/q/51246434
tags question: http://stackoverflow.com/q/51188610
tags question: http://stackoverflow.com/q/51199056
tags question: http://stackoverflow.com/q/51200718
tags question: http://stackoverflow.com/q/51281265
tags question: http://stackoverflow.com/q/51282946
tags question: http://stackoverflow.com/q/51207479
tags question: http://stackoverflow.com/q/51169241
tags question: http://stackoverflow.com/q/51235597
tags question: http://stackoverflow.com/q/51180771
tags question: http://stackoverflow.com/q/51301688
tags question: http://stackoverflow.com/q/51224381
tags question: http://stackoverflow.com/q/51244253
tags question: http://stackoverflow.com/q/51211232
tags question: http://stackoverflow.com/q/51298772
tags question: http://stackoverflow.com/q/51261827
tags question: http://stackoverflow.com/q/51292900
tags question: http://stackoverflow.com/q/51316697
tags question: http://stackoverflow.com/q/51221851
tags question: http://stackoverflow.com/q/51189266
tags question: http://stackoverflow.com/q/51316973
tags question: http://stackoverflow.com/q/51176800

http://stackoverflow.com/q/51191964
type: Question
has answer: http://stackoverflow.com/a/51207279
score: 0
has body: My task is: I have a program, written in Python which takes a set of variables (A,B,C) as input, and outputs two numbers (X, Y). I want to run this program over a large range of inputs (A,B,C) I'll refer to running the program with a given set of variables as 'running an experiment' I am using a cluster to do this (I submit my jobs in SLURM) I then want to save the results of the experiments into a single file, e.g. a data frame with columns [A|B|C|X|Y], where each row is the output of a different experiment. My current situation is: I have written my program in the following form: import io from optparse import OptionParser parser = OptionParser() parser.add_option("-f", "--file",action="store", type="string", dest="filename") parser.add_option("-a", "--input_a",type="int", dest="a") parser.add_option("-b", "--input_b",type="int", dest="b") parser.add_option("-c", "--input_c",type="int", dest="c") (options, args) = parser.parse_args() def F(a,b,c): return((a+b, b+c)) Alice = options.input_a Bob = options.input_b Carol = options.input_c with io.open("results_a_{0}_b_{1}_c_{2}.txt".format(Alice, Bob, Carol), "a") as f: (x,y) = F(Alice, Bob, Carol) f.write(u"first output = {0}, second output = {1}".format(x,y)) This allows me to run the program once, and save the results in a single file. In principle, I could then submit this job for a range of (A,B,C), obtain a large number of text files with the results, and then try to aggregate them into a single file. However, I assume this isn't the best way of going about things. What I'd like to know is: Is there a more natural way for me to run these experiments and save the results all in one file, and if so, what is it? How should I submit my collection of jobs on SLURM to do so? I currently am submitting (effectively) the script below, which is not really working: ... for a in 1 2 3; do for b in 10 20 30; do for c in 100 200 300; do python toy_experiment.py -a $a -b $b -c $c &amp; done done done wait [I'm wary that there …
answer count: 1
tagged with: slurm
type: UnansweredQuestion
tagged with: experimental-design
tagged with: python
has comment: http://stackoverflow.com/comment/89367056
has title: Running an experiment with different parameters, saving outputs efficiently
tagged with: cluster-computing

http://stackoverflow.com/a/51181830
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/51181824
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/51181824
has body: The variable i is an integer, yet you try to access an element from it as if it were list, via if i == i[::-1]: I think in this case, you want if str(i) == str(i)[::-1]: And to also cast i to a string inside of if len(str(i)) == n: However, it might be easier to instead do: for i in map(str,range(max)):
type: AcceptedAnswer

http://stackoverflow.com/a/51199781
has body: Your browser binary (in this case, for chromium) is not the same thing as your chromedriver. Just having the binary means you can launch chromium yourself, for example, but webdrivers will not be able to launch their own instances of chrom(e/ium), thus preventing you from using selenium with them. The solution to this is to download a chromedriver executable of your choice (note that version may be significant) in a folder on your path, or directly supply the path when creating your webdriver.
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/51199515
downvote count: 0
score: 1

http://stackoverflow.com/comment/89480354
type: Comment
comment on: http://stackoverflow.com/a/51250645
has text: I'm testing `x, y = 0, x + 1` and `y, x = x+1, 0`, seems like they both throw a declaration error?
score: 0
type: AnswerComment

http://stackoverflow.com/comment/110184153
comment on: http://stackoverflow.com/q/51258883
score: 1
type: Comment
has text: Fixed my issue with systemd, **moved** my `X.service` file from `/etc/systemd/system/X.service` to `~/.config/systemd/user/X.service`, enabled the user service `systemctl --user enable X.service`, reloaded systemd files `sudo systemctl daemon-reload`, then started the user specific service `systemctl --user start X.service` - Hope this helps the next person
type: QuestionComment

http://stackoverflow.com/q/51277876
tagged with: python
has comment: http://stackoverflow.com/comment/89533357
type: AnsweredQuestion
type: Question
has comment: http://stackoverflow.com/comment/89533333
possible better answer: http://stackoverflow.com/a/51277965
tagged with: python-2.7
score: 0
answer count: 2
has body: I have the text file with column Date and it also have some wrong data in date column like space and characters ABC. I just want to maintain those records which have characters into the different file named as Error_file.txt. Tried: import dateutil.parser as dparser from dateutil.parser import parse datelist = ["11/Jan/2018 01:01:00", "" ,"01/01/17", "2016-01-02","KK"] def is_date(string): try: parse(string) return True except ValueError: return False with open('output.txt', 'w') as output: with open('error_file.txt', 'w') as error: for i in datelist: if is_date(str(datelist)) == True: #WRITE TO Output File print dparser.parse(i, fuzzy=True).date() else: #WRITE TO Error File print('Error line') In the above given, record with KK should be maintained in Error_file.txt. But getting following output: Error line Error line Error line Error line Error line
has title: Find invalid value in date field
has comment: http://stackoverflow.com/comment/89533308
has answer: http://stackoverflow.com/a/51277905
accepted answer: http://stackoverflow.com/a/51277905
has answer: http://stackoverflow.com/a/51277965

http://stackoverflow.com/comment/89329535
comment on: http://stackoverflow.com/a/51172494
type: AnswerComment
has text: @Sunitha..Yes its working for me too. Thanks for your kind help.
score: 0
type: Comment

http://stackoverflow.com/a/51228014
has comment: http://stackoverflow.com/comment/89436115
has comment: http://stackoverflow.com/comment/89436007
score: 0
has body: backers = [sub for sub in browser.find_element_by_xpath('//span[@gogo-test="backers"]').text.split() if sub.isdigit()] backers = backers[0] if len(backers) &gt; 0 else None It is already very short, few improvements possible:) Or backers = list(filter(lambda sub: sub.isdigit(), browser.find_element_by_xpath('//span[@gogo-test="backers"]').text.split() )) backers = backers[0] if len(backers) &gt; 0 else None Or with regular expressions: import re backers = browser.find_elements_by_xpath('//span[@gogo-test="backers"]') backers = backers[0].text if len(backers) &gt; 0 else '' backers = re.findall('(\d+)', backers)
answers question: http://stackoverflow.com/q/51227799
has comment: http://stackoverflow.com/comment/89436245
type: Answer

http://stackoverflow.com/a/51285306
has comment: http://stackoverflow.com/comment/89548510
has body: You can also use list comprehension x = ['Gaga', 'Gaga', 'Lam', 'Reem', 'Pal', 'Gaga', 'Lam'] y = [name for name in x if x.count(name) != 1] output ['Gaga', 'Gaga', 'Lam', 'Gaga', 'Lam']
answers question: http://stackoverflow.com/q/51221526
score: 0
type: Answer

global
type: Tag
tag name: global
tags question: http://stackoverflow.com/q/51288447
tags question: http://stackoverflow.com/q/51265816
tags question: http://stackoverflow.com/q/51295852
tags question: http://stackoverflow.com/q/51229505

http://stackoverflow.com/comment/89515561
comment on: http://stackoverflow.com/q/51268504
type: QuestionComment
has text: github link to the same question here https://github.com/keras-team/keras/issues/10643
score: 0
type: Comment

http://stackoverflow.com/q/51232468
tagged with: python
type: AnsweredQuestion
tagged with: django-views
tagged with: django-urls
type: Question
has answer: http://stackoverflow.com/a/51232576
accepted answer: http://stackoverflow.com/a/51232576
score: 0
answer count: 1
has body: urls.py : urlpatterns = [ path('', views.posts, name='home'), path('&lt;string:slug&gt;', views.post_details, name='detail'), ] views.py (function) : def post_details(request, slug): posts = Posts.objects.get(pk=slug) return render(request, 'posts/post_details.html', {'posts': posts}) NOTE : I am currently learning django.
has title: post_details() got an unexpected keyword argument 'string' in Django?
tagged with: django

http://stackoverflow.com/a/51203512
has comment: http://stackoverflow.com/comment/89388220
has body: As an option you can skip using regex and use built-in Python isdigit() (no additional imports needed): digit = [sub for sub in browser.find_element_by_xpath('//span[@gogo-test="backers"]').text.split() if sub.isdigit()][0]
upvote count: 2
has comment: http://stackoverflow.com/comment/89439226
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89388471
has comment: http://stackoverflow.com/comment/89388640
has comment: http://stackoverflow.com/comment/89438149
answers question: http://stackoverflow.com/q/51203260
has comment: http://stackoverflow.com/comment/89388514
type: Answer
accepted answer of: http://stackoverflow.com/q/51203260
has comment: http://stackoverflow.com/comment/89431210
score: 2
has comment: http://stackoverflow.com/comment/89434309
downvote count: 0
has comment: http://stackoverflow.com/comment/89388452
has comment: http://stackoverflow.com/comment/89414597

http://stackoverflow.com/a/71662934
type: Answer
has body: here i built a function to use it instead of repeating, but the problem is how to call a built-in python method. this why i use getattr() function to read my function arguments as i want def test(str_1, fun): for i in range(len(str_1)): if getattr(str_1[i], fun)(): return True return False if __name__ == '__main__': s = raw_input() methods = ["isalnum", "isalpha", "isdigit", "islower", "isupper"] for method in methods: print(test(s, method))
score: 0
answers question: http://stackoverflow.com/q/51320667

http://stackoverflow.com/a/51253207
type: AcceptedAnswer
has body: This model was created using the Functional API Model Basically it works like this (perhaps if you go to the "side question 2" below before reading this it may get clearer): You have an input tensor (you can see it as "input data" too) You create (or reuse) a layer You pass the input tensor to a layer (you "call" a layer with an input) You get an output tensor You keep working with these tensors until you have created the entire graph. But this hasn't created a "model" yet. (One you can train and use other things). All you have is a graph telling which tensors go where. To create a model, you define it's start end end points. In the example. They take an existing model: model = keras.applications.InceptionV3(...) They want to expand this model, so they get its output tensor: model.output They pass this tensor as the input of a GlobalAveragePooling2D layer They get this layer's output tensor as new_output They pass this as input to yet another layer: Dense(N_CLASSES, ....) And get its output as new_output (this var was replaced as they are not interested in keeping its old value...) But, as it works with the functional API, we don't have a model yet, only a graph. In order to create a model, we use Model defining the input tensor and the output tensor: new_model = Model(old_model.inputs, new_output) Now you have your model. If you use it in another var, as I did (new_model), the old model will still exist in model. And these models are sharing the same layers, in a way that whenever you train one of them, the other gets updated as well. Question: how does it know what other layers we want in between? When you do: outputTensor = SomeLayer(...)(inputTensor) you have a connection between the input and output. (Keras will use the inner tensorflow mechanism and add these tensors and nodes to the graph). The output tensor cannot exist without the input. The entire InceptionV3 model is connected from start to end. Its input tensor goes through all the layers to yield an oup…
downvote count: 0
has comment: http://stackoverflow.com/comment/89486343
type: Answer
has comment: http://stackoverflow.com/comment/89486668
score: 5
upvote count: 5
answers question: http://stackoverflow.com/q/51200361
has comment: http://stackoverflow.com/comment/89486760
accepted answer of: http://stackoverflow.com/q/51200361
has comment: http://stackoverflow.com/comment/89487564

http://stackoverflow.com/q/51266961
type: Question
downvote count: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/51267020
favorite count: 0
has body: I have a data set of football players. I need to find the maximum of Penalties or Volleys for each player and add a column at the that prints the maximum value and also whether it was Penalties or Volleys. I tried the following code: import pandas as pd import numpy as np df=pd.read_excel(r'C:\Users\shrey\Desktop\FullData.xlsx') for j,i in df.iterrows(): data=i'Penalties','Volleys' i['max']=np.max(data) i['max_attr']=i.idxmax() But this gives me an error - reduction operation 'argmax' not allowed for this dtype How should I go about with it?
tagged with: pandas
tagged with: python
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/51267020
type: AnsweredQuestion
has title: Finding the maximum of a row in a dataframe and returning its column name in pandas
tagged with: dataframe

http://stackoverflow.com/q/51210929
has title: how to save output of tokenized string into list and compare that list with dictionary keys?
tagged with: nltk
has body: a string of text is tokenized and i want to save the outoput x into the list . so i can comopare that list with dictionary keys . but i am unable to save the output into list . I tried many things, i can compare pre defined list to dictionary but i want to save the output of token string into list . my code is : from nltk.tokenize import sent_tokenize,word_tokenize string=input("enter your text: ? ") # I am megan , hello word x= (word_tokenize(string)) print(x) # now this can be used to compare with dictioonary x=[] champ_ids=x champ_dict = {"hello" : 0, "Carly" : 36, "Freddy" : 85, "Megan" : 14, "Dilbert" : 69} for k, v in champ_dict.items(): if v in champ_ids: print(k) # output hello, megan
has comment: http://stackoverflow.com/comment/89403588
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/89402882
accepted answer: http://stackoverflow.com/a/51211536
has comment: http://stackoverflow.com/comment/89403676
has answer: http://stackoverflow.com/a/51211540
has comment: http://stackoverflow.com/comment/89403167
possible better answer: http://stackoverflow.com/a/51211540
has comment: http://stackoverflow.com/comment/89403513
tagged with: python
tagged with: dictionary
type: AnsweredQuestion
tagged with: list
has comment: http://stackoverflow.com/comment/89403313
has comment: http://stackoverflow.com/comment/89403466
tagged with: output
has answer: http://stackoverflow.com/a/51211536
type: Question
has comment: http://stackoverflow.com/comment/89403248
has comment: http://stackoverflow.com/comment/89402982

http://stackoverflow.com/a/51221615
score: 1
answers question: http://stackoverflow.com/q/51221526
has comment: http://stackoverflow.com/comment/89424069
downvote count: 0
has body: You can use Counter class for exactly this purpose: from collections import Counter x = ['Gaga', 'Gaga', 'Lam', 'Reem', 'Pal', 'Gaga','Lam'] c = Counter(x) new_values = [item for item in x if c[item] &gt; 1] indexes = [1 if c[item] == 1 else 0 for item in x] print(new_values) print(indexes) Output is: ['Gaga', 'Gaga', 'Lam', 'Gaga', 'Lam'] [0, 0, 0, 1, 1, 0, 0]
upvote count: 1
type: Answer

http://stackoverflow.com/q/51301035
tagged with: elementtree
has title: Parsing subchilds in XML with ElementTree
favorite count: 0
tagged with: parsing
tagged with: python
tagged with: http://stackoverflow.com/tag/xml
type: AnsweredQuestion
upvote count: 1
downvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/51302586
has body: Im trying to extract information from a XML-document with ElementTree in Python 3.2. The XML looks like this: 4 B 101 900 900 I manage to get the elementdata from "Group" with: for Page in root.iter('Page'): Group = Page.find('Group').text And "Letter"-data with: for Type in root.iter('Type'): Dim = Type.find('Letter').text However I can't figure out how to get the data from the subchilds of "Deep" (A and B). All help is greatly appreciated!
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/51302586

http://stackoverflow.com/q/51270051
favorite count: 0
has comment: http://stackoverflow.com/comment/89518365
tagged with: string-formatting
tagged with: python
linked to: http://stackoverflow.com/q/15479928
possible better answer: http://stackoverflow.com/a/51270679
tagged with: dictionary
has answer: http://stackoverflow.com/a/51270679
type: AnsweredQuestion
has body: 7.10 and for some reason the following code snippet is producing an error... device_info = {'username': 'test', 'password': 'test', 'appliance': 'name', 'hostname': 'hostname', 'prodcut': 'juice'} print "{} {} {} {} {}".format(**device_info) This raises an exception: Traceback (most recent call last): File "python", line 4, in &lt;module&gt; print "{} {} {} {} {}".format(**device_info) IndexError: tuple index out of range I believe this code should be syntactically sound, however, I don't seem to be able to unpack my dict to pass to any functions, not sure why that doesn't work.
downvote count: 2
accepted answer: http://stackoverflow.com/a/51270125
type: Question
has title: python variable unpacking fails
upvote count: 0
score: -2
tagged with: python-2.7
answer count: 2
tagged with: argument-unpacking
has answer: http://stackoverflow.com/a/51270125

mininet
tags question: http://stackoverflow.com/q/51265502
tag name: mininet
tags question: http://stackoverflow.com/q/51274595
tags question: http://stackoverflow.com/q/51323887
type: Tag

http://stackoverflow.com/a/51254868
upvote count: 1
score: 1
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51254381
has body: Forgive me if there's some flask-specific directory magic going on, but I'm thinking that it's a matter of where the python interpreter is being run from. I'm guessing that you ran python server.py from the web directory when testing it locally. If you were to try running python foo/web/server.py from the directory containing Dockerfile, then you would get the same error you posted above. So in the Dockerfile, try setting the WORKDIR to the web directory. Of course, the RUN, CMD and ls lines will also change. FROM python:3.4-alpine ADD . /code WORKDIR /code/foo/web RUN ls ../config RUN apk update &amp;&amp; \ apk add --virtual build-deps gcc python-dev musl-dev &amp;&amp; \ apk add postgresql-dev RUN pip install psycopg2 RUN python3 ../../setup.py install RUN pip install -r ../../requirements.txt CMD ["python3", "server.py"] EDIT: Alternatively, just use a second WORKDIR command directly before the CMD line, so everything would remain the same as the Dockerfile you posted, except the last two lines are WORKDIR /code/foo/web CMD ["python3", "server.py"] Good luck! Oliver
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51254381
type: Answer

http://stackoverflow.com/a/51255041
has body: You can use a dictionary comprehension: import csv with open('filename.csv') as f: header, *data = csv.reader(f) final_dict = {a:dict(zip(header, [a, *b])) for a, *b in data} Output: {'4': {'column1': '4', ' column2': '12', ' column3': '5', ' column4': '11'}, '29': {'column1': '29', ' column2': '47', ' column3': '23', ' column4': '41'}, '66': {'column1': '66', ' column2': '1', ' column3': '98', ' column4': '78'}}
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/51255024
downvote count: 0
type: Answer

http://stackoverflow.com/comment/89553605
has text: Thanks for your answer! It works fine now! I don't know why Python is only returning two decimal places with normal float...
type: AnswerComment
type: Comment
score: 0
comment on: http://stackoverflow.com/a/51283440

http://stackoverflow.com/q/51255851
upvote count: 6
has answer: http://stackoverflow.com/a/51255943
possible better answer: http://stackoverflow.com/a/66696842
answer count: 2
tagged with: django
tagged with: python
has title: Django's assertQuerysetEqual() method failing despite the two query sets printing out the same in the shell?
has answer: http://stackoverflow.com/a/66696842
has body: I have a Family and a Session with a one-to-many relationship, such that an instance family has a session_set. Further, the Session has a session_number field, which is an integer. I have two instances of Family, family1 and family2, such that if I print out their session_set.order_by('session_number') in the ipdb debugger I get that they look exactly the same: ipdb&gt; family1.session_set.order_by('session_number') &lt;QuerySet [&lt;Session: Welcome&gt;, &lt;Session: First-Time Parents: The Basics of Birth&gt;, &lt;Session: Initial Postpartum Lactation&gt;, &lt;Session: Sleep Techniques for New Babies&gt;, &lt;Session: Breastfeeding Preparation&gt;, &lt;Session: Newborn Care Basics&gt;, &lt;Session: Easing the Transition Back to Work&gt;, &lt;Session: Preparing for Parenting&gt;, &lt;Session: Decoding Baby Cues&gt;, &lt;Session: Postpartum Doula Support&gt;, &lt;Session: First-Time Parents: Birth Prep Q&amp;A&gt;, &lt;Session: Postpartum Lactation Follow-Up&gt;, &lt;Session: Sleep Training for 4 Months &amp; Beyond&gt;, &lt;Session: Mental Wellness in Pregnancy&gt;, &lt;Session: Infant CPR&gt;, &lt;Session: Prenatal Pelvic Physical Therapy&gt;, &lt;Session: Prenatal Massage&gt;]&gt; ipdb&gt; family2.session_set.order_by('session_number') &lt;QuerySet [&lt;Session: Welcome&gt;, &lt;Session: First-Time Parents: The Basics of Birth&gt;, &lt;Session: Initial Postpartum Lactation&gt;, &lt;Session: Sleep Techniques for New Babies&gt;, &lt;Session: Breastfeeding Preparation&gt;, &lt;Session: Newborn Care Basics&gt;, &lt;Session: Easing the Transition Back to Work&gt;, &lt;Session: Preparing for Parenting&gt;, &lt;Session: Decoding Baby Cues&gt;, &lt;Session: Postpartum Doula Support&gt;, &lt;Session: First-Time Parents: Birth Prep Q&amp;A&gt;, &lt;Session: Postpartum Lactation Follow-Up&gt;, &lt;Session: Sleep Training for 4 Months &amp; Beyond&gt;, &lt;Session: Mental Wellness in Pregnancy&gt;, &lt;Session: Infant CPR&gt;, &lt;Session: Prenatal Pelvic Physical Therapy&gt…
accepted answer: http://stackoverflow.com/a/51255943
type: AnsweredQuestion
downvote count: 0
tagged with: django-testing
score: 6
favorite count: 0
type: Question

http://stackoverflow.com/comment/89492526
score: 0
type: Comment
type: QuestionComment
has text: @doctorer: There are many variants of Linux. What comes up when you type `lsb_release -a` and `uname -a`? (Also, did you try the `OPENBLAS_NUM_THREADS` suggestion above.)
comment on: http://stackoverflow.com/q/51256738

http://stackoverflow.com/comment/89445218
type: Comment
comment on: http://stackoverflow.com/a/51232841
type: AnswerComment
has text: I thought so. `NameError: name 'files' is not defined` (but OP should really have provided a [mcve] that runs correctly).
score: 0

http://stackoverflow.com/comment/89566162
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51294121
has text: i did, i did! i got it, but still, it doesn't close...dunno what to do.

vtk
tags question: http://stackoverflow.com/q/51276704
type: Tag
tags question: http://stackoverflow.com/q/51285797
tags question: http://stackoverflow.com/q/51170259
tags question: http://stackoverflow.com/q/51215206
tags question: http://stackoverflow.com/q/51174821
tags question: http://stackoverflow.com/q/51301596
tag name: vtk
tags question: http://stackoverflow.com/q/51201888
tags question: http://stackoverflow.com/q/51288632

http://stackoverflow.com/comment/89569079
type: QuestionComment
has text: So... Where is your code? Show your attempt at solving the problem. We don't write code for you.
score: 3
comment on: http://stackoverflow.com/q/51295774
type: Comment

http://stackoverflow.com/q/51304566
tagged with: django-views
has answer: http://stackoverflow.com/a/51305149
score: 1
has title: How to display my python code in a table on Django webpage?
linked to: http://stackoverflow.com/q/39003732
has comment: http://stackoverflow.com/comment/89585872
answer count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/89595953
favorite count: 0
accepted answer: http://stackoverflow.com/a/51305149
tagged with: pandas
tagged with: python
has comment: http://stackoverflow.com/comment/89599020
tagged with: django-templates
has body: I have written some code in Python that reads in two strings, removes the punctuation and then compares the words in them within a matrix table which it prints to the console. How do I convert the code to be utilised within the Django framework. I want to display a similar matrix on the web. I've already imported it into views. Please may someone point me in the right direction? I've been using django project and lynda to learn as I go along, Edit: Merci for the help guys. Managed to get it to display on a webpage. But it is printing it all out as a single string. How do I style it a bit better?
has answer: http://stackoverflow.com/a/51309711
tagged with: django
upvote count: 1
type: Question
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/51309711

http://stackoverflow.com/q/51297102
upvote count: 18
tagged with: parallels
possible better answer: http://stackoverflow.com/a/58764690
accepted answer: http://stackoverflow.com/a/51297436
has answer: http://stackoverflow.com/a/58764690
favorite count: 0
has body: I have looked at this question but I am not sure I got it correctly or not. I have opened pycharm and one python script and its running (it's topic modeling). Also I have another python script in which I opened in another pycharm in the same server. I also run it. Now these two program are running in the same server, I should mention that I have not changed any configuration neither server nor pycharm. Do you think its ok in this way? or one script technically won't run(in terms of progressing I mean it just show its running but practically wont run) until the other script finished?
has title: running two python script in parallel in pycharm
has answer: http://stackoverflow.com/a/64176728
tagged with: python
answer count: 4
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/44517055
tagged with: pycharm
has answer: http://stackoverflow.com/a/58463159
type: Question
has answer: http://stackoverflow.com/a/51297436
score: 18
downvote count: 0

http://stackoverflow.com/a/65424834
upvote count: 3
downvote count: 1
score: 2
has body: While other solutions found on the web didn't work for me (such as the one above and using $ pip install pyqt5), I solved this by uninstalling and reinstalling Spyder via terminal, using pip. $ pip uninstall spyder ... $ pip install spyder ... Not sure why, but it worked on the first try.
answers question: http://stackoverflow.com/q/51317382
type: Answer

http://stackoverflow.com/comment/89454453
score: 3
comment on: http://stackoverflow.com/q/51237792
has text: You are not instantiating your class. You seem to be doing this -> `CorrectChair.load(1)`, when in fact you want to do something like `CorrectChair(1).load(1)`. Note the parenthesis after `CorrectChair`
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89343349
type: Comment
score: 1
comment on: http://stackoverflow.com/a/51177398
type: AnswerComment
has text: So in other words. As is, Yes, without more detail regarding the setup and a bit creativity. I am afraid you won't be able to just `.read()` and get exactly one JSON representing string.

http://stackoverflow.com/a/51324781
type: Answer
has comment: http://stackoverflow.com/comment/89629372
score: 1
has body: I have no problem running the following with your code. I explicitly set the 4.0 to a float which may help you, though for me it was not an issue. temp_df = pd.DataFrame(dict_temp) print(temp_df) temp_df = temp_df[temp_df &gt; float(4.0)] print(temp_df) Output [5 rows x 6 columns] Book Title Author ... User 3 User 4 0 Great Expectations Charles Dickens ... NaN NaN 1 Of Mice and Men John Steinbeck ... NaN NaN 2 Romeo and Juliet William Shakespeare ... NaN NaN 3 The Time Machine H. G. Wells ... NaN 5.0 4 Alice in Wonderland Lewis Carroll ... NaN 4.2
answers question: http://stackoverflow.com/q/51324402
upvote count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/89629461

http://stackoverflow.com/q/51217780
answer count: 3
tagged with: pandas
favorite count: 0
has answer: http://stackoverflow.com/a/51217827
type: UnansweredQuestion
tagged with: python
score: 2
has answer: http://stackoverflow.com/a/51217888
downvote count: 0
has comment: http://stackoverflow.com/comment/89416840
has body: In a Pandas df, I am trying to drop duplicates across multiple columns. Lots of data per row is NaN. This is only an example, the data is a mixed bag, so many different combinations exist. df.drop_duplicates() IDnum name formNumber 1 NaN AP GROUP 028-11964 2 1364615.0 AP GROUP NaN 3 NaN AP GROUP NaN Hopeful Output: IDnum name formNumber 1 1364615.0 AP GROUP 028-11964 EDIT: If the df.drop_duplicates() looks like this, would it change the solution? : df.drop_duplicates() IDnum name formNumber 0 NaN AP GROUP 028-11964 1 1364615.0 AP GROUP 028-11964 2 1364615.0 AP GROUP NaN 3 NaN AP GROUP NaN
has title: Pandas drop duplicates ignoring NaN
type: Question
has answer: http://stackoverflow.com/a/68943692
tagged with: duplicates
tagged with: dataframe
upvote count: 2

http://stackoverflow.com/comment/89420235
comment on: http://stackoverflow.com/q/51219565
score: 0
type: QuestionComment
has text: For an implementation of the Python subprocess end, take a look at the code being asked about at https://stackoverflow.com/questions/41431882/live-stream-stdout-and-stdin-with-websocket -- indeed, if you weren't asking the question narrowed to flask, I'd just call that an answer (and this a duplicate).
type: Comment

http://stackoverflow.com/comment/89379288
type: QuestionComment
has text: `cwd=r' '` it's a raw string see (https://docs.python.org/3/reference/lexical_analysis.html)
score: 0
type: Comment
comment on: http://stackoverflow.com/q/51198754

http://stackoverflow.com/q/51180949
downvote count: 0
score: 1
has title: Return 2nd smallest item in list using only recursion
has comment: http://stackoverflow.com/comment/89346631
has comment: http://stackoverflow.com/comment/89344796
linked to: http://stackoverflow.com/q/28144569
type: Question
has body: Im having trouble with this more advanced scenario. I understand this: def max(alist): if len(alist) == 1: return alist[0] else: m = max(alist[1:]) return m if m &gt; alist[0] else alist[0] Which finds the max number in a list using just recursion. This repeats the function slowly shrinking the list every time which I get. My problem is I need to create a function that returns the 2nd smallest number. I dont understand how to do this since you need to compare each item with the rest of the items in the list. How would I do this with only recursion and no built in functions or for loops?
has comment: http://stackoverflow.com/comment/89344432
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/89344402
favorite count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51181233
tagged with: python
linked to: http://stackoverflow.com/q/33625995
tagged with: recursion
tagged with: list

http://stackoverflow.com/comment/89571544
comment on: http://stackoverflow.com/q/51297121
score: 0
has text: you're line 5 is using the input values, not the integer values from mph and distance.
type: QuestionComment
type: Comment

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

http://stackoverflow.com/comment/89551501
has text: What would be the result for `empty_list = [" ", "foo", " "]`? `["a", "foo", "b"]` or `["a", "foo", " "]`?
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51286922

http://stackoverflow.com/comment/89460049
score: 0
type: AnswerComment
has text: @user3623123 I'm not sure its correct. Can you add an example of input and output?
type: Comment
comment on: http://stackoverflow.com/a/51240579

http://stackoverflow.com/a/51313239
score: -1
has comment: http://stackoverflow.com/comment/89603544
upvote count: 0
has body: files can be opened the same for both python 2 and 3. Now while file contents may differ if you store string representations and/or pickle data, that can be avoided by not using those constructs - use some common data format instead, like json or a sql database or even a simple csv text file. Then your file will read the same on python 2 and 3.
has comment: http://stackoverflow.com/comment/89603611
answers question: http://stackoverflow.com/q/51313199
has comment: http://stackoverflow.com/comment/89606234
type: Answer
has comment: http://stackoverflow.com/comment/89606212
has comment: http://stackoverflow.com/comment/89605783
downvote count: 1

http://stackoverflow.com/a/51254263
answers question: http://stackoverflow.com/q/51254065
has comment: http://stackoverflow.com/comment/89487711
downvote count: 0
has comment: http://stackoverflow.com/comment/89487642
type: Answer
has comment: http://stackoverflow.com/comment/89517156
has body: Without converting to a string: def shuffle(x): if x &lt; 100: return x t = x l = 0 while t &gt; 0: t //= 10 l += 1 a = x // 10 ** (l-1) * 10 ** (l-1) b = (x % 10) * 10 ** (l-2) return a + b + shuffle((x - a) // 10) and the tests work: &gt;&gt;&gt; shuffle(123456) 162534 &gt;&gt;&gt; shuffle(310) 301
upvote count: 3
score: 3

http://stackoverflow.com/comment/89551210
comment on: http://stackoverflow.com/q/51286833
has text: Please show what code you used.
type: Comment
type: QuestionComment
score: 2

http://stackoverflow.com/q/51276385
has body: I've been attempting to get __get__ __set__ and __delete__ magic method working with decorators put onto the class's method (not the instance). I am entirely unable to get anything other than __get__ to work / be called. I have tried about every combination / arrangement of code but the most recent looks like this: def my_decorator5(func: Callable[..., R]) -&gt; R: """ Decorate func while preserving the signature. """ print(f"{'*'*40} my_decorator main") class Wrap(object): def __init__(self, clsmethod) -&gt; None: print(f"{'*'*40} is __init__") self.value = None self.func = func self.clsmethod = clsmethod self.func_name = func.__name__ def __get__(self, obj, cls) -&gt; R: print(f"{'*'*40} {cls} is getting") owner = cls self.value = func(cls) return cast(R, self.value) def __set__(self, cls, newval) -&gt; None: print(f"{'*'*40} {cls} is setting") self.value = newval def __set_name__(self, cls, newval) -&gt; None: print(f"{'*'*40} {self} is __set_name__") print(f"{'*'*40} {cls} is __set_name__") print(f"{'*'*40} {newval} is __set_name__") def __delete__(self, cls) -&gt; None: print(f"{'*'*40} {cls} is deleting") delattr(self, "value") def __delattr__(self, key) -&gt; None: print(f"{'*'*40} {self} is __delattr__") I have test code : class foo3: @my_decorator5 def foo3_str(self) -&gt; str: return "Original foo3 str" print(f"\n{'*'*80}\n{'*'*35} STARTING {'*'*35}\n{'*'*80}\n") print(f"\n--{dir(foo3.foo3_str)}--\n") print(f"\n--{foo3.foo3_str.__class__}--\n") print(f"\n--{dir(foo3.__dict__['foo3_str'])}--\n") print(f"\n--\tatrr: {foo3.foo3_str.__class__}\n\t__dict__{foo3.__dict__['foo3_str'].__class__}\n\t{foo3.__dict__['foo3_str'].__set__(1,2)}--\n") print("&gt;&gt;&gt;&gt; getting &gt;&gt;&gt;&gt;") print(f"foo3_str ==&gt; {foo3.foo3_str}") print(f"&lt;&lt;&lt;&lt; got foo3_str &lt;&lt;&lt;&lt;") print("\n") print(f"\n--\tatrr: {foo3.foo3_str.__class__}\n\t__dict__{foo3.__dict__['foo3_str'].__class__}--\n") print("&gt;&gt;&gt;&gt; settting &gt;&gt;&gt;&gt;") foo3.foo3_…
type: Question
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/89530699
favorite count: 0
tagged with: class
has comment: http://stackoverflow.com/comment/89531008
tagged with: descriptor
tagged with: python-3.x
type: UnansweredQuestion
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/89532765
has title: Python - descriptor on class to *set* attributes
has answer: http://stackoverflow.com/a/51278141
has comment: http://stackoverflow.com/comment/89559483
score: 1

http://stackoverflow.com/comment/89523180
score: 0
comment on: http://stackoverflow.com/q/51272443
type: Comment
type: QuestionComment
has text: That solved it. Thank you so much.

http://stackoverflow.com/comment/107505181
comment on: http://stackoverflow.com/q/51293632
score: 2
has text: Had a similar need. Ended up using [arrow](https://arrow.readthedocs.io/en/latest/#ranges-spans). `arrow.Arrow.span_range('month', start, end)` does the trick.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/121937276
has text: I am having a huge error 10^6, so I normalized my acoustic data before feeding it into autoencoder. As a result my error reduce down to 1.89 with just normalizing it
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51238346
type: Comment

http://stackoverflow.com/q/51237956
upvote count: 6
has body: I'm trying to SSH into a Raspberry Pi on a subnet via ethernet using the Fabric module but I can't figure out how to authenticate the connection. My code so far is as follows import fabric c = fabric.Connection(host = "192.168.3.151", port = 22, user = "pi") c.run("touch Desktop/new_file.txt") Obviously I haven't put in my password, "Raspberry", anywhere in the above code to authenticate the SSH connection. I've been trying to understand the Fabric documentation but it's a little beyond me so I'm hoping someone can tell me how to input the password to authenticate the connection (and also authenticate any commands using sudo). Thanks!
tagged with: paramiko
has answer: http://stackoverflow.com/a/51238157
answer count: 1
has title: Python - How do I authenticate SSH connection with Fabric module?
favorite count: 0
has comment: http://stackoverflow.com/comment/89455097
score: 6
tagged with: ssh
tagged with: fabric
tagged with: python
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/89455072
accepted answer: http://stackoverflow.com/a/51238157
type: Question
tagged with: raspberry-pi

http://stackoverflow.com/a/51217365
has comment: http://stackoverflow.com/comment/89416117
upvote count: 1
has comment: http://stackoverflow.com/comment/89416025
score: 1
answers question: http://stackoverflow.com/q/51217344
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51217344
downvote count: 0
type: Answer
has body: If you iterate over a dictionary, you iterate over the keys. So that means in the first loop, x = 'a', and in the second x = 'b' (or vice versa, since dictionaries are unordered). It thus simply "ignores" the values. It makes no sense to index a string with a string (well there is no straightforward interpretation for 'a'['aa'], or at least not really one I can come up with that would be "logical" for a signifcant number of programmers). Although this may look quite strange, it is quite consistent with the fact that a membership check for example also works on the keys (if we write 'a' in some_dict, it does not look to the values either). If you want to use the values, you need to iterate over .values(), so: for x in test.values(): print(x['aa']) If you however use your second thest, then this works, since then x is a key (for example 'a'), and hence test[x] will fetch you the corresponding value. If you then process test[x] further, you thus process the values of the dictionary. You can iterate concurrently over keys and values with .items(): for k, x in test.items(): # ... pass Here in the first iteration k will be 'a' and x will be {'aa':'value','ab':'value'}, in the second iteration k will be 'b' and x will be {'aa':'value','ab':'value'} (again the iterations can be swapped, since dictionaries are unordered). If you thus are interested in the outer key, and the value that is associated with the 'aa' key of the corresponding subdictionary, you can use: for k, x in test.items(): v = x['aa'] print(k, v)

image
tags question: http://stackoverflow.com/q/51277949
tags question: http://stackoverflow.com/q/51285930
tags question: http://stackoverflow.com/q/51293585
tags question: http://stackoverflow.com/q/51296473
tags question: http://stackoverflow.com/q/51293876
tags question: http://stackoverflow.com/q/51215981
tags question: http://stackoverflow.com/q/51224154
tags question: http://stackoverflow.com/q/51213035
tags question: http://stackoverflow.com/q/51268802
tags question: http://stackoverflow.com/q/51196028
tags question: http://stackoverflow.com/q/51220865
tags question: http://stackoverflow.com/q/51237579
tags question: http://stackoverflow.com/q/51237354
tags question: http://stackoverflow.com/q/51311305
tags question: http://stackoverflow.com/q/51200852
tags question: http://stackoverflow.com/q/51281913
tags question: http://stackoverflow.com/q/51205502
tags question: http://stackoverflow.com/q/51200630
tags question: http://stackoverflow.com/q/51271232
tags question: http://stackoverflow.com/q/51279247
tags question: http://stackoverflow.com/q/51182852
tags question: http://stackoverflow.com/q/51220016
tags question: http://stackoverflow.com/q/51264851
tags question: http://stackoverflow.com/q/51210152
tags question: http://stackoverflow.com/q/51253611
tags question: http://stackoverflow.com/q/51214972
tag name: image
tags question: http://stackoverflow.com/q/51245877
tags question: http://stackoverflow.com/q/51254118
type: Tag
tags question: http://stackoverflow.com/q/51304490
tags question: http://stackoverflow.com/q/51180913

deployment
tags question: http://stackoverflow.com/q/51256446
tag name: deployment
tags question: http://stackoverflow.com/q/51250847
tags question: http://stackoverflow.com/q/51238387
tags question: http://stackoverflow.com/q/51196117
type: Tag
tags question: http://stackoverflow.com/q/51283475

http://stackoverflow.com/comment/89487716
score: 0
type: Comment
type: QuestionComment
has text: so basically `asyncio future` can just be composed when they are sharing a loop right?
comment on: http://stackoverflow.com/q/51254050

http://stackoverflow.com/q/51177738
downvote count: 2
type: Question
score: 10
tagged with: numpy
answer count: 2
has body: What is its purpose? I tried reading the official site but wasn't able to understand.
upvote count: 12
has answer: http://stackoverflow.com/a/51177829
favorite count: 0
possible better answer: http://stackoverflow.com/a/51834595
has answer: http://stackoverflow.com/a/51834595
tagged with: python
has title: What is the use of bincount() method from numpy?
type: AnsweredQuestion
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/51177829

http://stackoverflow.com/comment/89466288
comment on: http://stackoverflow.com/q/51243819
has text: Error in line number..?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51253559
has body: The problem is really simple, a variable created within a function only exists until the function is finished executing, in your case plt is eliminated by what is not shown, the solution is to increase the scope of that data, a form of doing it is to return it and pass it to a variable with a greater scope. import numpy as np import pyqtgraph as pg import pyqtgraph.exporters from pyqtgraph.Qt import QtCore, QtGui import csv import itertools from datetime import datetime as dt app = QtGui.QApplication([]) class TimeAxisItem(pg.AxisItem): def tickStrings(self, values, scale, spacing): return [dt.fromtimestamp(value) for value in values] def Gshow(): # app = QtGui.QApplication([]) x_vals = [dt(2018, 7, 1, 13, 6, 38), dt(2018, 7, 1, 12, 46, 38), dt(2018, 7, 1, 12, 36, 38), dt(2018, 7, 1, 12, 26, 38), dt(2018, 7, 1, 12, 16, 38), dt(2018, 7, 1, 12, 6, 38), dt(2018, 7, 1, 11, 56, 38), dt(2018, 7, 1, 11, 46, 38), dt(2018, 7, 1, 11, 36, 38), dt(2018, 7, 1, 11, 26, 38), dt(2018, 7, 1, 10, 56, 38), dt(2018, 7, 1, 10, 46, 38), dt(2018, 7, 1, 10, 36, 38)] y_vals = [23.5, 20.8, 28.0, 28.1, 28.0, 27.8, 27.3, 27.2, 25.7, 24.7, 25.0, 25.0, 24.9] date_axis = TimeAxisItem(orientation='bottom') plt = pg.PlotWidget(axisItems = {'bottom': date_axis}) # set properties plt.setLabel('left', 'Temperature', units='C') plt.setWindowTitle('Temperature over time') plt.plot(x=[x.timestamp() for x in x_vals], y=y_vals, symbol=None, pen='r', symbolPen='r') plt.show() return plt # &lt;---- var = Gshow() # &lt;---- if __name__ == '__main__': import sys if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'): QtGui.QApplication.instance().exec_()
upvote count: 2
has comment: http://stackoverflow.com/comment/89493718
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51252887
answers question: http://stackoverflow.com/q/51252887
type: Answer
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/89493804
has comment: http://stackoverflow.com/comment/89494734

http://stackoverflow.com/comment/90711390
type: Comment
has text: No problem, that is aesthetic not requiered. I want equal size widget images.
comment on: http://stackoverflow.com/a/51316108
score: 0
type: AnswerComment

http://stackoverflow.com/comment/89502502
score: 0
has text: The power operator in python is, unlike any other, right associative. That means `a ** b ** c == a ** (b ** c)`. Since `5 ** 20 == 9.536743e+13` that means `4 ** 5 ** 20` will be 10^26 bits long. Your computer has about 10^11 bits of memory. Instead of timing out this operation (which would require some kind of thread), just don't do it when you won't get an answer.
type: Comment
comment on: http://stackoverflow.com/q/51262008
type: QuestionComment

http://stackoverflow.com/comment/89560857
comment on: http://stackoverflow.com/a/51291193
score: 0
type: AnswerComment
type: Comment
has text: @user9995331 It works for me, it's a bit difficult to debug without knowing exactly what you did. Try asking another question so the code gets properly formatted.

http://stackoverflow.com/comment/89446410
comment on: http://stackoverflow.com/a/51233572
has text: Did you mean this `for _ in range(2): driver.find_element_by_tag_name("body").send_keys(Keys.END) time.sleep(2)`
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/89482321
comment on: http://stackoverflow.com/q/51251325
type: Comment
type: QuestionComment
score: 0
has text: Ok, I have activated the venv and re-installed the module, however in the IDLE it stills displays the same error message

http://stackoverflow.com/q/51199082
has title: TypeError: can only concatenate list (not "NoneType") to list
type: Question
tagged with: recursion
score: 4
has answer: http://stackoverflow.com/a/51199096
accepted answer: http://stackoverflow.com/a/51199096
answer count: 1
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/89379998
tagged with: python
has body: I tries to write program that will be append to the list recursively def string(times,char): list=[] list.append(char) if times==0: print(list) else: return [list] + string(times-1 ,char) string(3,input('text')) and when I start the code, I got error TypeError: can only concatenate list (not "NoneType") to list
upvote count: 4
type: AnsweredQuestion

http://stackoverflow.com/comment/89581543
comment on: http://stackoverflow.com/q/51302345
has text: Seems strange however that it doesn't still return the last element in the queryset.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51296449
score: 2
upvote count: 2
accepted answer of: http://stackoverflow.com/q/51296442
answers question: http://stackoverflow.com/q/51296442
has body: More groups. &gt;&gt;&gt; re.findall(r'(([a-z])-([a-z]))','a b-c d') [('b-c', 'b', 'c')] And since you don't actually care about the original... &gt;&gt;&gt; re.findall(r'([a-z])-([a-z])','a b-c d') [('b', 'c')]
has comment: http://stackoverflow.com/comment/89570790
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/comment/89452035
comment on: http://stackoverflow.com/q/51227229
type: Comment
score: 0
type: QuestionComment
has text: To clarify, I am running python 3.6 as well with Pandas 0.23.1

http://stackoverflow.com/a/51283438
has comment: http://stackoverflow.com/comment/89544469
has comment: http://stackoverflow.com/comment/89544635
answers question: http://stackoverflow.com/q/51283361
has comment: http://stackoverflow.com/comment/89544646
has comment: http://stackoverflow.com/comment/89544446
type: AcceptedAnswer
downvote count: 0
has body: I suggest change function for return Series and subset of new columns: def ced(x): return pd.Series([x+1, x+2, x+2]) df = pd.DataFrame(data=[[1,2],[10,20]], columns=['a','b']) df'x','y', 'z' = df['a'].apply(lambda x: ced(x)) print(df) a b x y z 0 1 2 2 3 3 1 10 20 11 12 12 Another solution is create DataFrame by constructor: def ced(x): return x+1, x+2, x+2 df = pd.DataFrame(data=[[1,2],[10,20]], columns=['a','b']) df'x','y', 'z' = pd.DataFrame(df['a'].apply(lambda x: ced(x)).values.tolist()) print(df) a b x y z 0 1 2 2 3 3 1 10 20 11 12 12
type: Answer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/51283361
score: 1

http://stackoverflow.com/q/51276878
score: 1
tagged with: api
linked to: http://stackoverflow.com/q/46956952
downvote count: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/51277020
tagged with: flask
favorite count: 0
linked to: http://stackoverflow.com/q/10576386
tagged with: authlib
tagged with: python
has title: How to get a authentication code / token using Authlib 2.0 on Flask?
has body: I have read part of the documentation of Authlib and the example multiple times, I also have read articles about the concept of Auth 2.0, but I can't figure out how to do it. I want my user to make login (Using username and password) and then my application to return a token. After that the user can use the private resources @require_oauth('profile'). My client : *************************** 1. row *************************** client_id: wmahDfsran1jk6CaH1knpi3n client_secret: mnr4j15pZurBPYHq4KW4LY8HC7pS4TwjzMlJAUGmo7Bpy5gP issued_at: 1531271519 expires_at: 0 redirect_uri: http://127.0.0.1:5000/oauth/token token_endpoint_auth_method: client_secret_basic grant_type: authorization_code password response_type: code scope: profile client_name: client_test client_uri: http://127.0.0.1:5000/ logo_uri: NULL contact: NULL tos_uri: NULL policy_uri: NULL jwks_uri: NULL jwks_text: NULL i18n_metadata: NULL software_id: NULL software_version: NULL id: 2 user_id: 1 My POST request (Using Postman): http://127.0.0.1:5000/oauth/authorize?response_type=code&amp;client_id=wmahDfsran1jk6CaH1knpi3n The error after make the request : { "error": "invalid_grant" } Authorize : @routes.route('/oauth/authorize', methods=['GET', 'POST']) def authorize(): user = current_user() try: grant = authorization.validate_consent_request(end_user=user) except OAuth2Error as error: return error.error return authorization.create_authorization_response(grant_user=user) Token : @routes.route('/oauth/token', methods=['POST', 'GET']) def issue_token(): return authorization.create_token_response() Profile : @routes.route('/resource/profile', methods=['GET', 'POST']) @require_oauth('profile') def profile(): user = current_user() return jsonify(id=user.id, username=user.username, secret=user.secret, client_id=user.client_id) The token continues the same of the Auth Example. If I try to access /resource/profile without a token / autorização : {"error": "missing_authorization", "error_description": "Missing \"Author…
tagged with: oauth-2.0
linked to: http://stackoverflow.com/q/26400776
upvote count: 1
has answer: http://stackoverflow.com/a/51277020
type: Question
type: AnsweredQuestion

http://stackoverflow.com/comment/89527808
comment on: http://stackoverflow.com/q/51274847
type: Comment
type: QuestionComment
has text: I really don't think you want to go down this path. I think you need to expand the question to incorporate the task you want to do in a broader sense (put the multiprocessing to one side for now)
score: 2

http://stackoverflow.com/q/51185079
tagged with: machine-learning
tagged with: python
has title: Why the acc of DNN is less than 1%
type: AnsweredQuestion
score: 2
has comment: http://stackoverflow.com/comment/89352312
has comment: http://stackoverflow.com/comment/89356412
type: Question
has body: Im a new in deeplearning. I have a X with 34 dimension, which are some stock technical indicator data. And Y is label, which is binary(1,-1) represent the stock is uptrend or downtrend.Here is my code. import pandas as pd import numpy as np data = pd.read_csv('data/data_week.csv') data.dropna(inplace=True) x = data.loc[:, 'bbands_upperband':'turn_std_5'] y = data['label'] from keras.models import Sequential from keras.layers import Dense, Activation model = Sequential() model.add(Dense(512, activation='relu', input_dim=34)) model.add(Dense(200, activation='relu')) model.add(Dense(200, activation='relu')) model.add(Dense(200, activation='relu')) model.add(Dense(128, activation='relu')) model.add(Dense(1, activation='relu')) model.compile(optimizer='rmsprop', loss='binary_crossentropy', metrics=['accuracy']) model.fit(x, y, epochs=2, batch_size=200) 231200/1041021 [=====&gt;........................] - ETA: 59s - loss: 0.7098 - acc: 0.0086 232000/1041021 [=====&gt;........................] - ETA: 59s - loss: 0.7087 - acc: 0.0086 However, the accuracy is less than 1%. I think this must has something wrong. If you know please tell me and thank you very much!
tagged with: neural-network
downvote count: 0
tagged with: keras
upvote count: 2
tagged with: deep-learning
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/89352196
has answer: http://stackoverflow.com/a/51185245
accepted answer: http://stackoverflow.com/a/51185245

http://stackoverflow.com/a/51181926
accepted answer of: http://stackoverflow.com/q/51181637
answers question: http://stackoverflow.com/q/51181637
type: AcceptedAnswer
has body: You can Beautiful Soup to parse the iframe source code and find the script elements, but from there you're on your own. The file: "xxxxx", line is in JavaScript code, so you'll have to find the function call (to playerInstance.setup() in this case) and decide which of the two such "file:" lines is the one you want, and strip away the unwanted JS syntax around the URL. Regular expressions will help with that, and you're probably better off just looking for the lines in the iframe's HTML. You already have re imported, so I just replaced your last line with: lines = re.findall("file: .*$", inner_content.text, re.MULTILINE) print( '\n'.join(lines) ) ...to get a list of lines with "file:" in them. You can (and should) use a fancier RE to find just the one with "http:// and allows only whitespace before "file:" on the lines. (Python, Java and my text editor all have different ideas about what's in an RE, so I have to go to docs every time I write one. You can do that too--it's your problem, after all.) The requests.get() function doesn't seem to work to get the bytes. Try Vishnu Kiran's urlretrieve approach--maybe that will work. Using the URL in a browser window does seem to get the right video, though, so there may be a user agent and/or cookie setting that you'll have to spoof.
score: 0
type: Answer

http://stackoverflow.com/q/51187888
has comment: http://stackoverflow.com/comment/89357933
score: 2
type: AnsweredQuestion
tagged with: http://stackoverflow.com/tag/json
possible better answer: http://stackoverflow.com/a/51188394
type: Question
answer count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/89358005
has answer: http://stackoverflow.com/a/51188608
linked to: http://stackoverflow.com/q/22219004
tagged with: pandas
has title: Convert dataframe to JSON with 1 common valued column as array field
accepted answer: http://stackoverflow.com/a/51188608
has comment: http://stackoverflow.com/comment/89357702
has comment: http://stackoverflow.com/comment/89357547
favorite count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/89357864
tagged with: python
has body: I am a bit new to Python programming. I have a small requirement where in I need to list down all customers and their amounts for a given fortnight in a JSON format.Currently, I have a dataframe this way - FortNight AmountValue Customer 2018-04-29 339632.00 10992 2018-04-29 27282.00 10994 2018-04-29 26353.00 10995 2018-04-29 24797.00 11000 2018-04-29 21093.00 10990 Expected - "Apr-2FN-2018":[ {"Customer":"10992","AmountValue":"339632.00"}, {"Customer":"10994","AmountValue":"27282.00"}, {"Customer":"10995","AmountValue":"26353.00"}, {"Customer":"11000","AmountValue":"24797.00"}, {"Customer":"10990","AmountValue":"21093.00"} ] I tried using df.(orient = "records", date_format = "iso") But it retrieves values in the below way- {"FortNight":"2018-04-29T00:00:00.000Z","AmountValue":21093.8,"Customer":10990} I tried other ways too, but in vain. Any help is welcome. Thanks in advance!!...
has answer: http://stackoverflow.com/a/51188394

http://stackoverflow.com/comment/89624750
type: Comment
comment on: http://stackoverflow.com/a/51324633
score: 0
type: AnswerComment
has text: I want to append 0s and 1s to the list based on a certain rate, for example 10 bits per second, i don't want my program to sleep for any amount of time. It should append those bits continuously. If program runs for 10 seconds, the list would contain 100 bits if the rate is 10 bits per second, that is, 100 zeros and ones. I hope you get my point.

http://stackoverflow.com/comment/89488562
comment on: http://stackoverflow.com/q/51253056
has text: @JimHunziker, is it possible to just replace `OrderedDict` with `dict` prior to evaluating? They both support a sequence of 2-tuples as the first argument to the constructor.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89448909
type: Comment
has text: @Asim `temp` is an input layer. So it must be fed somehow in your GAN. Therefore, according to the way you have implemented the architecture you must explicitly make it as input of the model, otherwise it is not connected to anything and hence cannot be fed.
score: 0
comment on: http://stackoverflow.com/a/51234801
type: AnswerComment

http://stackoverflow.com/a/51496330
type: Answer
score: 0
has body: The Introduction to Machine Learning course did a batch gradient descent using all of the training examples at each iteration and then used multiple iterations to converge. The code above would only use one training example (batch=1) and the number of iterations (steps) is forever (based on tf.estimator.LinearRegressor.train documentation). I was able to replicate the results from the Introduction to Machine Learning class with a couple of changes. from __future__ import print_function import math from matplotlib import cm from matplotlib import gridspec from matplotlib import pyplot as plt import numpy as np import pandas as pd from sklearn import metrics import tensorflow as tf from tensorflow.python.data import Dataset tf.logging.set_verbosity(tf.logging.ERROR) pd.options.display.max_rows = 10 pd.options.display.float_format = '{:.1f}'.format def my_input_fn(features, labels, batch_size=1, num_epochs=None): features = {key:np.array(value) for key,value in dict(features).items()} ds = Dataset.from_tensor_slices((features,labels)) ds = ds.batch(batch_size).repeat(num_epochs) features, labels = ds.make_one_shot_iterator().get_next() return features, labels ex1_data_df = pd.read_csv('ex1data1.txt') features = ex1_data_df['population'] my_features = ex1_data_df'population' feature_columns = [tf.feature_column.numeric_column('population')] labels = ex1_data_df['profit'] my_optimizer=tf.train.GradientDescentOptimizer(learning_rate=0.0001) linear_regressor = tf.estimator.LinearRegressor( feature_columns = feature_columns, optimizer=my_optimizer) _ = linear_regressor.train( input_fn = lambda:my_input_fn(my_features, labels, batch_size=ex1_data_df.shape[0]), steps=2000 ) predictions = linear_regressor.predict( input_fn=lambda:my_input_fn(my_features,labels, batch_size=1,num_epochs=1) ) predictions = np.array([item['predictions'][0] for item in predictions]) mean_squared_error = metrics.mean_squared_error(predictions, labels) print("Mean Squared Error (on training data)…
answers question: http://stackoverflow.com/q/51302275

http://stackoverflow.com/comment/89346267
comment on: http://stackoverflow.com/q/51181969
type: Comment
has text: I'm using mean squared error for cost function. I'm going to try L2 loss to see if that makes a difference.
score: 0
type: QuestionComment

http://stackoverflow.com/comment/89569044
has text: Thank you for clarifying. I understand the issue now. I've updated the previous post with a workaround. However still could not figure out how to get the `slider` to show-up. Probably missing somthing in the `call` to `updatemenus`. I'll update the post if I am able to find a solution to the slider.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51293907
type: Comment

http://stackoverflow.com/comment/89478679
comment on: http://stackoverflow.com/q/51249811
score: 0
type: Comment
type: QuestionComment
has text: I could generate the same result by setting the seed in the operation as well: `tf.set_random_seed(1234)` and `generate = tf.random_uniform((10,), 0, 10, seed=1234)`. I wonder if there is any other way without requiring to set the seed in the operation level.

http://stackoverflow.com/q/51323679
score: 1
has answer: http://stackoverflow.com/a/51327633
tagged with: simpleitk
tagged with: image-processing
upvote count: 1
type: Question
has body: I am very new to medical image registration. I am trying to register two CT volumes, the first is axial with size of (384,384,31) and spacing of (0.57,0.57,4.8) and the second is a sagittal scan with size of (384,384,15) and spacing (0.67,0.67,2.2) in order to use the area of overlap between them to create super-resolution and obtain an isotropic scan. So the problem is that the volumes have a different orientation as well as the different field of view. I.e. the axial slices in the sagittal scan contain only a small segment of what is present in the axial scan, In other words, I need to crop the axial slices in the axial scan to match the FOV of the sagittal slice and so on to create masks for the simpleitk rigid registration algorithm. I also think that I need the masks for resampling both volumes at some point. My question is, How can I create the mask and can I use any of the metadata available in the nifti file to do that? I have the direction, origin and index point matrix. Thanks a lot.
tagged with: medical
answer count: 1
downvote count: 0
favorite count: 0
type: UnansweredQuestion
has title: Registering non-isotropic CT scans with different field of view
tagged with: python
tagged with: image-registration

http://stackoverflow.com/q/51323781
answer count: 3
has title: Pandas: Replace values in a column with 'Other' based on the count of rows corresponding to the value
has body: I have a dataframe of shape (600,000 * 33) One of the columns, lets call it, 'name', has over 2000 unique values. I have sorted the column using the below code: got.groupby('name').size().sort_values(ascending=False) Below is a sample of each name along with the count of rows in the dataframe Name Count John 90000 Daenerys 50000 Cersei 45000 ... ... Hound 2000 Joffrey 1500 LittleF 1200 ... ... I want to be able to look through the dataframe and replace all the names with less than 2000 rows ( &lt;2000 for count) with 'Other', in this case, 'Joffrey' and 'LittleF'.
has answer: http://stackoverflow.com/a/51323838
accepted answer: http://stackoverflow.com/a/51323838
possible better answer: http://stackoverflow.com/a/51323864
favorite count: 0
tagged with: pandas
tagged with: python
score: 2
type: AnsweredQuestion
tagged with: python-3.x
downvote count: 0
has answer: http://stackoverflow.com/a/51323864
type: Question
has answer: http://stackoverflow.com/a/51323957
upvote count: 2

http://stackoverflow.com/q/51297531
tagged with: numpy
score: 2
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python-3.x
upvote count: 2
type: UnansweredQuestion
tagged with: python
has title: Python detrend 3d dataset with NaNs
has body: I am trying to de-trend my dataset of size 480x2040 = close to 1,000,000 pixels. I have 17 timesteps in this series (years) however I want to move to daily timesteps at some point. This code works, however runs way way way too slow to be functional. I feel that scipy.signal.detrend can do the whole dataset, however I have some NaNs. In some cases, NaN are continents, which means there is a NaN at every timestep, however in some rarer cases, there is some missing data. How can I detrend every pixel of my map over time, while ignoring/skipping the NaNs? It needs to be orders of magnitude quicker than this looping. for i in range(0,nlat): for j in range(0,nlon): pixel = ds[:,i,j] b = ~np.isnan(pixel) detrend[b,i,j]=signal.detrend(pixel[b]) Cheers!
has answer: http://stackoverflow.com/a/51301177
tagged with: scipy
tagged with: signal-processing
type: Question

http://stackoverflow.com/q/51306645
tagged with: scikit-learn
type: UnansweredQuestion
tagged with: python
tagged with: machine-learning
has body: I am trying to cluster timestamps for different speaker embedding, it works best if euclidean is used as affinity and ward as linkage on Agglomerative clustering with k clusters. I am trying to match the output using scipy's hierarchy.flcusterdata and tried different threshold, however I am getting completely random results. However I can match the output from both algorithms if cosine is used as affinity and complete as linkage. What could be the reason behind skewed results on euclidean metric? Here is the code : clt=AgglomerativeClustering(n_clusters=k, affinity='euclidean', linkage='ward') res = clt.fit_predict(embeddings) res=hierarchy.fclusterdata(embeddings,t=0.95,criterion='distance',method='ward',metric='euclidean') I am using the data for both clustering this way, assuming embedding is a numpy array of timestamps
tagged with: hierarchical-clustering
type: Question
has title: Scikit learn and scipy giving different results with Agglomerative clustering with euclidean metric
has answer: http://stackoverflow.com/a/51766992
score: 0
answer count: 1

http://stackoverflow.com/comment/89502804
score: 0
type: Comment
type: QuestionComment
has text: The code you posted doesn't throw an UnboundLocalError.
comment on: http://stackoverflow.com/q/51262426

http://stackoverflow.com/q/51280203
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89540901
has comment: http://stackoverflow.com/comment/89541650
accepted answer: http://stackoverflow.com/a/51290889
has body: I have a large number of independent, parallel horizontal line segments in a numpy array. Each segment has a start and an end (x-coordinates), and a value (y-coordinate). The segments don't necessarily have the same length (length = end - start). An example matrix specifying the segments, one segment per row, could look as follows: Start End Value 0 10 4 5 19 3 6 25 2 7 16 1 12 21 5 In code A = np.array([[0,10,4], [5,19,3], [6,25,2], [7,16,1], [12,21,5]]) I want to figure out the running max over the line segments. That is, in the above example, for x in the range [0,25), I want the corresponding max y. Example output corresponding to the example would be Start End Max 0 10 4 10 12 3 12 21 5 21 25 2 I can do this in a for loop, but this is slow, since I have tens of thousands of segments. I cannot seem to think of a way to vectorize this. Can anyone? Example for loop code: x = np.arange(np.min(A[:,0]), np.max(A[:,1])) maxes = np.zeros((x.shape[0], 2)) maxes[:,0] = x maxes[:,1] = -np.inf for a in A: ix = (x &gt;= a[0]) &amp; (x &lt; a[1]) &amp; (maxes[:,1] &lt; a[2]) maxes[ix,1] = a[2] This code outputs an array with a row for every x in the range, contrary to the output example above. Both are fine (and equivalent).
type: Question
tagged with: numpy
has title: Python vectorized running max of parallel line segments
answer count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/89540474
has comment: http://stackoverflow.com/comment/89538301
favorite count: 0
possible better answer: http://stackoverflow.com/a/51285719
has answer: http://stackoverflow.com/a/51285719
has answer: http://stackoverflow.com/a/51290889
has comment: http://stackoverflow.com/comment/89540042
upvote count: 2
has comment: http://stackoverflow.com/comment/89542088
has comment: http://stackoverflow.com/comment/89537747
tagged with: python
score: 2

http://stackoverflow.com/a/51230694
answers question: http://stackoverflow.com/q/51230544
score: 4
has body: In this answer I will make a python translation of my another answer written in C++. from PyQt5 import QtCore, QtGui, QtWidgets class TabBar(QtWidgets.QTabBar): def tabSizeHint(self, index): s = QtWidgets.QTabBar.tabSizeHint(self, index) s.transpose() return s def paintEvent(self, event): painter = QtWidgets.QStylePainter(self) opt = QtWidgets.QStyleOptionTab() for i in range(self.count()): self.initStyleOption(opt, i) painter.drawControl(QtWidgets.QStyle.CE_TabBarTabShape, opt) painter.save() s = opt.rect.size() s.transpose() r = QtCore.QRect(QtCore.QPoint(), s) r.moveCenter(opt.rect.center()) opt.rect = r c = self.tabRect(i).center() painter.translate(c) painter.rotate(90) painter.translate(-c) painter.drawControl(QtWidgets.QStyle.CE_TabBarTabLabel, opt); painter.restore() class TabWidget(QtWidgets.QTabWidget): def __init__(self, *args, **kwargs): QtWidgets.QTabWidget.__init__(self, *args, **kwargs) self.setTabBar(TabBar(self)) self.setTabPosition(QtWidgets.QTabWidget.West) if __name__ == '__main__': import sys app = QtWidgets.QApplication(sys.argv) w = TabWidget() w.addTab(QtWidgets.QWidget(), "tab1") w.addTab(QtWidgets.QWidget(), "tab2") w.addTab(QtWidgets.QWidget(), "tab3") w.show() sys.exit(app.exec_())
upvote count: 4
accepted answer of: http://stackoverflow.com/q/51230544
type: AcceptedAnswer
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/89440737

http://stackoverflow.com/comment/89388299
type: QuestionComment
comment on: http://stackoverflow.com/q/51203591
score: 2
type: Comment
has text: Please consider adding a code sample, or revising the one you posted in this question. As it currently stands, its formatting and scope make it hard for us to help you; here is a [great resource](http://stackoverflow.com/help/mcve) to get you started on that. Good luck with your code!

http://stackoverflow.com/comment/93192906
has text: For Windows 10, I searched and opened "Windows Defender", clicked on "Firewall and network protection", a Public network connection was active so I clicked "Public network", then turned "Windows Defender firewall" to off.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52509038
type: AnswerComment

http://stackoverflow.com/q/51185093
type: UnansweredQuestion
tagged with: machine-learning
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/51186268
tagged with: autoencoder
has title: How to create an Autoencoder where the encoder/decoder weights are mirrored (transposed)
score: 1
tagged with: tensorflow
type: Question
has body: I am attempting to build my first Autoencoder neural net using TensorFlow. The dimensions of the layers in the encoder and decoder are the same, just reversed. The autoencoder learns to compress and reconstruct image data to a reasonable standard, but I would like to try to improve its performance by instead having the decoder as the exact transpose of the encoder. I am lost with how to do this in TensorFlow. Here is a snippet of the construction of my network: imgW, imgH = 28, 28 encoderDims = [ imgW * imgH, (imgW // 2) * (imgH // 2), (imgW // 3) * (imgH // 3), (imgW // 4) * (imgH // 4) ] decoderDims = list(reversed(encoderDims)) encoderWeights, encoderBiases = [], [] decoderWeights, decoderBiases = [], [] for layer in range(len(encoderDims) - 1): encoderWeights.append( tf.Variable(tf.random_normal([encoderDims[layer], encoderDims[layer + 1]])) ) encoderBiases.append( tf.Variable(tf.random_normal([encoderDims[layer + 1]])) ) decoderWeights.append( tf.Variable(tf.random_normal([decoderDims[layer], decoderDims[layer + 1]])) ) decoderBiases.append( tf.Variable(tf.random_normal([decoderDims[layer + 1]])) ) input = tf.placeholder(tf.float32, [None, imgW * imgH]) encoded = input for layer in range(len(encoderDims) - 1): encoded = tf.add(tf.matmul(encoded, encoderWeights[layer]), encoderBiases[layer]) encoded = tf.nn.sigmoid(encoded) decoded = encoded for layer in range(len(decoderDims) - 1): decoded = tf.add(tf.matmul(decoded, decoderWeights[layer]), decoderBiases[layer]) if layer != len(decoderDims) - 2: decoded = tf.nn.sigmoid(decoded) loss = tf.losses.mean_squared_error(labels=input, predictions=decoded) train = tf.train.AdamOptimizer(learningRate).minimize(loss) The two issues I do not know how to overcome are: How can I adjust only the encoder parameters during training with respect to the loss? How can I create the decoder weights and biases in such a way that after each iteration of training of the encoder parameters, they are set as the transpose of the newly adj…
tagged with: deep-learning
downvote count: 0
answer count: 1
favorite count: 0

http://stackoverflow.com/a/51207551
type: Answer
accepted answer of: http://stackoverflow.com/q/51206981
downvote count: 0
answers question: http://stackoverflow.com/q/51206981
score: 2
upvote count: 2
has body: You can use the cumulative sum function, cumsum(). df = pd.DataFrame([1, 0, 1, 1,1], columns=['Count']) df['Counts'] = df['Count'].cumsum() print(df) giving you the desired output. Count Counts 0 1 1 1 0 1 2 1 2 3 1 3 4 1 4
type: AcceptedAnswer

http://stackoverflow.com/comment/89608076
has text: @RobertL78 But using `while` when there's nothing to loop over isn't actually using the `while`. You might as well just add `while False: assert False, "This is impossible!"` statements every other line to your code. The "Or, alternately" shows how to actually get some use out of a `while`.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51315002
type: Comment

django
tags question: http://stackoverflow.com/q/51187108
tags question: http://stackoverflow.com/q/51295029
tags question: http://stackoverflow.com/q/51168379
tags question: http://stackoverflow.com/q/51302102
tags question: http://stackoverflow.com/q/51172515
tags question: http://stackoverflow.com/q/51311861
tags question: http://stackoverflow.com/q/51226836
tags question: http://stackoverflow.com/q/51206480
tags question: http://stackoverflow.com/q/51191533
tags question: http://stackoverflow.com/q/51322338
tags question: http://stackoverflow.com/q/51206121
tags question: http://stackoverflow.com/q/51237791
tags question: http://stackoverflow.com/q/51268192
tags question: http://stackoverflow.com/q/51223476
tags question: http://stackoverflow.com/q/51200009
tags question: http://stackoverflow.com/q/51263832
tags question: http://stackoverflow.com/q/51254264
tags question: http://stackoverflow.com/q/51247886
tags question: http://stackoverflow.com/q/51179583
tags question: http://stackoverflow.com/q/51292557
tags question: http://stackoverflow.com/q/51287084
tags question: http://stackoverflow.com/q/51288186
tags question: http://stackoverflow.com/q/51250903
tags question: http://stackoverflow.com/q/51202613
tags question: http://stackoverflow.com/q/51200679
tags question: http://stackoverflow.com/q/51288608
tags question: http://stackoverflow.com/q/51191679
tags question: http://stackoverflow.com/q/51255501
tags question: http://stackoverflow.com/q/51315823
tags question: http://stackoverflow.com/q/51308530
tags question: http://stackoverflow.com/q/51231538
tags question: http://stackoverflow.com/q/51252820
tags question: http://stackoverflow.com/q/51178211
tags question: http://stackoverflow.com/q/51264558
tags question: http://stackoverflow.com/q/51238469
tags question: http://stackoverflow.com/q/51268702
tags question: http://stackoverflow.com/q/51309164
tags question: http://stackoverflow.com/q/51189487
tags question: http://stackoverflow.com/q/51239135
tags question: http://stackoverflow.com/q/51216880
tags question: http://stackoverflow.com/q/51278665
tags question: http://stackoverflow.com/q/51289210
tags question: http://stackoverflow.com/q/51230090
type: Tag
tags question: http://stackoverflow.com/q/51249797
tags question: http://stackoverflow.com/q/51300343
tags question: http://stackoverflow.com/q/51178632
tags question: http://stackoverflow.com/q/51220853
tags question: http://stackoverflow.com/q/51194328
tags question: http://stackoverflow.com/q/51222287
tags question: http://stackoverflow.com/q/51238341
tags question: http://stackoverflow.com/q/51218022
tags question: http://stackoverflow.com/q/51190378
tags question: http://stackoverflow.com/q/51186597
tags question: http://stackoverflow.com/q/51278002
tags question: http://stackoverflow.com/q/51312315
tags question: http://stackoverflow.com/q/51259402
tags question: http://stackoverflow.com/q/51194214
tags question: http://stackoverflow.com/q/51299464
tags question: http://stackoverflow.com/q/51314067
tags question: http://stackoverflow.com/q/51227296
tags question: http://stackoverflow.com/q/51243094
tags question: http://stackoverflow.com/q/51281208
tags question: http://stackoverflow.com/q/51217408
tags question: http://stackoverflow.com/q/51320590
tags question: http://stackoverflow.com/q/51180967
tags question: http://stackoverflow.com/q/51255851
tags question: http://stackoverflow.com/q/51223791
tags question: http://stackoverflow.com/q/51187604
tags question: http://stackoverflow.com/q/51312562
tags question: http://stackoverflow.com/q/51257960
tags question: http://stackoverflow.com/q/51234071
tags question: http://stackoverflow.com/q/51247387
tags question: http://stackoverflow.com/q/51265127
tags question: http://stackoverflow.com/q/51183913
tags question: http://stackoverflow.com/q/51191820
tags question: http://stackoverflow.com/q/51187365
tags question: http://stackoverflow.com/q/51172820
tags question: http://stackoverflow.com/q/51287486
tags question: http://stackoverflow.com/q/51315694

http://stackoverflow.com/q/51194627
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51196815
score: 2
has title: Python Naive Bayes with cross validation using GaussianNB classifier
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/55326829
downvote count: 0
tagged with: scikit-learn
favorite count: 0
has body: I would like to apply Naive Bayes with 10-fold stratified cross-validation to my data, and then I want to see how the model performs on the test data I set aside initially. However, the results I am getting (i.e. the predicted outcome and probability values y_pred_nb2 and y_score_nb2) are identical to when I run the code without any cross-validation. QUESTION: How can I correct this? The code is below, where X_train consists of 75% of the entire dataset and X_test consists of 25%. from sklearn.model_selection import StratifiedKFold params = {} #gridsearch searches for the best hyperparameters and keeps the classifier with the highest recall score skf = StratifiedKFold(n_splits=10) nb2 = GridSearchCV(GaussianNB(), cv=skf, param_grid=params) %time nb2.fit(X_train, y_train) # predict values on the test set y_pred_nb2 = nb2.predict(X_test) print(y_pred_nb2) # predicted probabilities on the test set y_scores_nb2 = nb2.predict_proba(X_test)[:, 1] print(y_scores_nb2)
tagged with: python
upvote count: 2

http://stackoverflow.com/q/51176331
type: UnansweredQuestion
tagged with: python
has title: Flake8 uses system python instead of virtualenv
has comment: http://stackoverflow.com/comment/89364365
score: 3
upvote count: 3
type: Question
has comment: http://stackoverflow.com/comment/89370184
has comment: http://stackoverflow.com/comment/89383091
tagged with: flake8
answer count: 1
tagged with: virtualenv
has body: My flake8 is giving different outputs to a colleague's, and the difference seems to be in the python version: (hydro2) andrew@xxx $ flake8 --version 3.5.0 (mccabe: 0.6.1, pycodestyle: 2.3.1, pyflakes: 1.6.0) CPython 2.7.12 on Linux Whereas on his machine it says CPython 3.5.0 or so. I'm running the flake8 installed inside a python 3.5 virtualenv, and everything seems to point to the right place: (hydro2) andrew@xxx $ which python /home/andrew/virtualenvs/hydro2/bin/python (hydro2) andrew@xxx $ python --version Python 3.5.2 (hydro2) andrew@xxx $ which flake8 /home/andrew/virtualenvs/hydro2/bin/flake8 So I'm just confused as to why it's using CPython 2.7.12 (which is my OS's default) instead of the virtualenv's version? I have tried uninstalling and reinstalling flake8 in the virtualenv.
downvote count: 0
has answer: http://stackoverflow.com/a/72929654
has comment: http://stackoverflow.com/comment/106444991
favorite count: 0
has comment: http://stackoverflow.com/comment/89337948

http://stackoverflow.com/q/51319105
downvote count: 1
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/51319480
has answer: http://stackoverflow.com/a/51319371
accepted answer: http://stackoverflow.com/a/51319371
type: Question
has answer: http://stackoverflow.com/a/51320624
has comment: http://stackoverflow.com/comment/89614422
has title: Read lines from a txt. file and write all except 6 first lines on another, then flush the first file
score: 0
has answer: http://stackoverflow.com/a/51319480
answer count: 3
has body: I'm trying to create a Python code that reads data from an email, saves it onto a temporary txt. file. There will be another permanent txt. file, where the temporary txt. files contents will be written in a form that skips the first 6 lines. During this loop the temporary file gets flushed, so the same data will not be written multiple times. Here is the code I have worked with: for part in email_message.walk(): if part.get_content_type() == 'text/plain': body = part.get_payload(decode=True) save_string = str('C:/Email/file.txt') myfile = open(save_string, 'a') myfile.write(str(body)) ## Write to file 2 and then flush this open ('C:/Email/file.txt','w+') as f: lines = f.readlines() open ('C:/Email/newfile.txt','a') as g: g.writelines(lines[6:]) f.close() g.close() myfile.close()# Clear first file else: continue Currently the issue is that it writes the email to the first txt. file, but does not update the second txt. file. However, when I run the code again, the previous data gets written to the second txt. This is something I don't quite understand why it happens, since the order should be correct. Thanks in advance! More of the code here: @view_config(route_name='update-data') def update_view(request): m = imaplib.IMAP4_SSL('imap.gmail.com') m.login('gmail@gmail.com', 'password') m.list() m.select('inbox') result, data = m.uid('search', None, 'UNSEEN') # Only unseen mail i = len(data[0].split()) #space separate string if i == 0: return Response(' Data cannot be updated No new emails Return to the main page ') for x in range(i): latest_email_uid = data[0].split()[x] result, email_data = m.uid('fetch', latest_email_uid, '(RFC822)') raw_email = email_data[0][1] raw_email_string = raw_email.decode('utf-8') email_message = email.message_from_string(raw_email_string) for part in email_message.walk(): if part.get_content_type() == 'text/plain': body = part.get_payload(decode=True) save_string = str('C:/Email/file.txt') myfile = open(save_string, 'a') myfile.write(str(bod…
favorite count: 0
tagged with: pyramid
upvote count: 1
tagged with: python

http://stackoverflow.com/comment/89474875
type: Comment
comment on: http://stackoverflow.com/a/51236592
has text: Thanks Stephen. If I want to add meta data using the pandas json_normalize function how would that be done?
score: 0
type: AnswerComment

http://stackoverflow.com/comment/89602896
type: AnswerComment
score: 0
type: Comment
has text: Thanks a lot for your answer. But in my case I have multiple X values in order to predict Y. So I was trying to plot actual Y versus predicted Y, not X versus Y
comment on: http://stackoverflow.com/a/51263440

http://stackoverflow.com/comment/89599973
score: 0
comment on: http://stackoverflow.com/a/51311324
has text: @mb567 oops, sorry. Edited
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/89502699
comment on: http://stackoverflow.com/q/51262225
score: 0
type: QuestionComment
has text: Welcome to Stackoverflow. Can you provide some minimal, verfiable code and data example? *Please edit your question accordingly.* For guidance check the link in the previous comment. Thank you
type: Comment

http://stackoverflow.com/q/51229188
has comment: http://stackoverflow.com/comment/89438097
type: Question
tagged with: network-programming
has comment: http://stackoverflow.com/comment/89438226
has comment: http://stackoverflow.com/comment/89456315
has comment: http://stackoverflow.com/comment/89451611
has comment: http://stackoverflow.com/comment/89438118
has comment: http://stackoverflow.com/comment/89438079
has comment: http://stackoverflow.com/comment/89438106
has title: How can I have two clients behind NATs communicate without port forwarding or hole punching?
has comment: http://stackoverflow.com/comment/89438154
tagged with: p2p
has comment: http://stackoverflow.com/comment/89438131
type: UnansweredQuestion
tagged with: python
has body: I want to make a peer-to-peer program in Python, but I keep running into the same issue of how to get them to communicate. I always run into the same answers. Use a central server UDP hole punching, or use UPnP to tell the router to open a port. The second and third I haven't gotten to work despite hours of trying. Multiple libraries simply didn't work, and for the second I have no rendezvous server. For the first, I have tried to use the freenode IRC server as the central server, but it is quite unreliable and complicated, and just doesn't feel like a good solution. Is there any other way? Or solutions to the above problems?
answer count: 0
score: 0
has comment: http://stackoverflow.com/comment/89438112

http://stackoverflow.com/comment/89413856
score: 0
type: AnswerComment
type: Comment
has text: Hi and thanks for the answer. I am the administrator on my computer^^ The code can actually access the file without running it with privileges. It's just like that: Code: a b c works fine. as soon as I do like: Code: a d b c It can't access it anymore. Deleting the D doesn't change anything. I have to copy paste the code again (exactly as it is when having this error). I'm not closing the .py or anything. I just overwrite ABC with ABC and it works again... edit: I'm working with pycharm
comment on: http://stackoverflow.com/a/51216317

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

http://stackoverflow.com/comment/89612628
has text: check my updated answer
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51317262

http://stackoverflow.com/a/51233637
score: 2
downvote count: 0
upvote count: 2
accepted answer of: http://stackoverflow.com/q/51233622
has comment: http://stackoverflow.com/comment/89446688
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51233622
type: Answer
has body: Well you here basically check if: word1 &lt;= check &lt;= word2 But here, it is the opposite: word2 is less, and word1 is greater, we can however compbine the two possibilities with: word1 &lt;= check &lt;= word2 or word2 &lt;= check &lt;= word1 So here regardless of what the order is between word1 and word2, it checks if check is "sandwiched" in between.

http://stackoverflow.com/a/51322041
downvote count: 0
answers question: http://stackoverflow.com/q/51321960
upvote count: 2
type: Answer
has body: I had a similar Problem, this post helped me: How to insert an image in python What they basically use is: import Image myImage = Image.open("your_image_here"); myImage.show(); For more help I would need your full code. Even after the edit it is not quite clear to me what is your code, what is the error and what you are actually trying to do.
score: 2

http://stackoverflow.com/comment/119759301
comment on: http://stackoverflow.com/a/51241776
score: 3
type: Comment
has text: its 'guild_permissions' now
type: AnswerComment

http://stackoverflow.com/comment/89457681
comment on: http://stackoverflow.com/q/51238905
score: 0
has text: could you please add a small template that reproduces this issue ?
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/89381960
type: QuestionComment
score: 0
type: Comment
has text: Would having two virtual environments, identical but for the presence of `rapidjson`, be an acceptable answer? Or, if you prefer a tool that builds a virtualenv out of a `requirements.txt`, two separate `requirements.txt` files?
comment on: http://stackoverflow.com/q/51200093

http://stackoverflow.com/q/51188675
has comment: http://stackoverflow.com/comment/89359795
tagged with: python
type: AnsweredQuestion
tagged with: image-processing
accepted answer: http://stackoverflow.com/a/51191246
type: Question
has answer: http://stackoverflow.com/a/51191246
score: 0
answer count: 1
has body: I was given a list of string which represents an encoded image in a csv file. The string previously were encoded from the images which were exported from MS SQL Server 'image' column. The task is to figure out which encoding is used so the strings can be decoded to an image again. I've have posted one of the string here: https://pastebin. com/BfjdTqdr May I know how I can approach this problem using python. I apologize in advance if this does not make a good question. You may leave a comment and I'll get back to you.
has title: Image Encoding/Decoding using python

http://stackoverflow.com/comment/104885490
has text: How can I interpret the returned similarity measure from sims (sims[query_doc_tf_idf])? For example, how can I show the percentage similarity between two documents?
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/51289825
type: Comment

http://stackoverflow.com/comment/89387275
comment on: http://stackoverflow.com/q/51203070
has text: Possible duplicate of [Error converting .ui file to .py file](https://stackoverflow.com/questions/13551316/error-converting-ui-file-to-py-file)
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89345657
type: Comment
comment on: http://stackoverflow.com/q/51181674
type: QuestionComment
has text: Your first approach is written in a way that incredibly waste resources. It creates lists and pops elements all the time!! Maybe rewrite it using a set and generator functions, it will be closer to what `groupby()` does
score: 4

http://stackoverflow.com/comment/89524760
score: 0
type: AnswerComment
type: Comment
has text: @kashmoney without a [mcve] I could not tell you where the error is
comment on: http://stackoverflow.com/a/51250908

http://stackoverflow.com/comment/89619987
score: 0
type: AnswerComment
has text: @shmee : I've modified it
type: Comment
comment on: http://stackoverflow.com/a/51322099

http://stackoverflow.com/q/51259233
has comment: http://stackoverflow.com/comment/89515345
linked to: http://stackoverflow.com/q/230751
has title: How to compare histogram in real time with camera?
tagged with: histogram
favorite count: 0
has comment: http://stackoverflow.com/comment/89504995
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89502232
tagged with: python
tagged with: computer-vision
tagged with: opencv
has comment: http://stackoverflow.com/comment/89497255
answer count: 0
score: 1
tagged with: image-processing
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/89501816
has comment: http://stackoverflow.com/comment/89501619
has body: I try this code for detecting object histogram realtime with the camera and its work : import cv2 import numpy as np from matplotlib import pyplot as plt camera = cv2.VideoCapture(1) base1 = cv2.imread('base1.png') base2 = cv2.imread('base2.png') base3 = cv2.imread('base3.png') #Set hist parameters hist_height = 64 hist_width = 256 nbins = 32 bin_width = hist_width/nbins hrange = [0,180] srange = [0,256] ranges = hrange+srange # ranges = [0,180,0,256] #Create an empty image for the histogram h = np.zeros((hist_height,hist_width)) while 1: grabbed, img = camera.read() cam = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) if not grabbed: "Camera could not be started." break histcam = cv2.calcHist([cam], [0], None, [nbins], [0,256]) cv2.normalize(histcam,histcam, hist_height, cv2.NORM_MINMAX) hist=np.int32(np.around(histcam)) for x,y in enumerate(hist): cv2.rectangle(h,(x*bin_width,y),(x*bin_width + bin_width-1,hist_height), (255), -1) #Flip upside down h=np.flipud(h) #Show the histogram cv2.imshow('Color Histogram',h) h = np.zeros((hist_height,hist_width)) cv2.imshow('img',img) k = cv2.waitKey(30) &amp; 0xff if k == 27: break camera.release() cv2.destroyAllWindows() and I add this code under the code above to compare the histogram : #Compare the Histogram base1hsv = cv2.cvtColor(base1,cv2.COLOR_BGR2HSV) base2hsv = cv2.cvtColor(base2,cv2.COLOR_BGR2HSV) base3hsv = cv2.cvtColor(base3,cv2.COLOR_BGR2HSV) histbase1 = cv2.calcHist([base1hsv], [0], None, [nbins], [ranges]) cv2.normalize(histbase1,histbase1,hist_height,cv2.NORM_MINMAX) hist=np.int32(np.around(histbase1)) histbase2 = cv2.calcHist([base2hsv], [0], None, [nbins], [ranges]) cv2.normalize(histbase2,histbase2,hist_height,cv2.NORM_MINMAX) histbase3 = cv2.calcHist([base3hsv], [0], None, [nbins], [ranges]) cv2.normalize(histbase3,histbase3,hist_height,cv2.NORM_MINMAX) for i in xrange(1): if i == 0 : print ("Correlation", cv2.HISTCMP_CORREL) base1_base1 = cv2.compareHist(histbase1,histbase1, cv2.HISTCMP_CORREL) base1_cam = cv2.co…
downvote count: 0

http://stackoverflow.com/q/51236232
has answer: http://stackoverflow.com/a/51237382
type: AnsweredQuestion
tagged with: pymc3
score: 1
upvote count: 1
type: Question
tagged with: anaconda
has body: EDIT: Solution found, in answers below. Leaving question up for others who may have the same problem. I just installed pymc3, and it is only 'partially' working for me. I'm using Anaconda on 64bit installation on windows, but I don't think that is the issue (i.e., I don't think the issue is a need to switch to 32 bit anaconda). Various examples are not working for me, so I tried working through this example: http://docs.pymc.io/notebooks/getting_started.html#A-Motivating-Example:-Linear-Regression everything works fine until: with basic_model: # draw 500 posterior samples trace = pm.sample(500) at that point, I get an error. Edit: I do have reason to believe it's loky, because I've gotten further by reinstalling theanos and something else. But I am still getting this: C:\Users\Yurik\Anaconda3\lib\site-packages\h5py\__init__.py:36: FutureWarning: Conversion of the second argument of issubdtype from `float` to `np.floating` is deprecated. In future, it will be treated as `np.float64 == np.dtype(float).type`. from ._conv import register_converters as _register_converters Running on PyMC3 v3.4.1 WARNING (theano.gof.compilelock): Overriding existing lock by dead process '26576' (I am process '27640') Auto-assigning NUTS sampler... Initializing NUTS using jitter+adapt_diag... Multiprocess sampling (2 chains in 2 jobs) NUTS: [sigma_log__, beta, alpha] Traceback (most recent call last): File "&lt;ipython-input-1-1ef2ccded6b8&gt;", line 1, in &lt;module&gt; runfile('C:/Users/Yurik/.spyder-py3/temp.py', wdir='C:/Users/Yurik/.spyder-py3') File "C:\Users\Yurik\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 705, in runfile execfile(filename, namespace) File "C:\Users\Yurik\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 102, in execfile exec(compile(f.read(), filename, 'exec'), namespace) File "C:/Users/Yurik/.spyder-py3/temp.py", line 57, in &lt;module&gt; trace = pm.sample(500) File "C:\Users\Yurik\Anaconda3\lib\site-packages\pymc3\…
accepted answer: http://stackoverflow.com/a/51237382
tagged with: pymc
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python-3.x
has title: pymc3 not working, getting nan and none type errors using Anaconda3
tagged with: python

http://stackoverflow.com/comment/89440365
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51230457
has text: Well, why did you not simply try it out?

http://stackoverflow.com/q/51213774
score: 1
linked to: http://stackoverflow.com/q/42116143
has comment: http://stackoverflow.com/comment/89408558
type: Question
upvote count: 2
tagged with: numpy
has comment: http://stackoverflow.com/comment/89464767
tagged with: pyspark
answer count: 1
favorite count: 0
tagged with: apache-spark
has comment: http://stackoverflow.com/comment/89416719
downvote count: 1
linked to: http://stackoverflow.com/q/38384347
has body: I am having dataframe which has a column of dense vectors i.e. Multiclass classification prediction probabilities. I want to convert that column to numpy array and facing issues of shape mismatch. There are the things I tried. One answer I found on here did converted the values into numpy array but in original dataframe it had 4653 observations but the shape of numpy array was (4712, 21). I dont understand how it increased and in another attempt with same code numpy array shape desreased the the count of original dataframe. I dont understand why? I also tried predictions.select("probability").toPandas().values.shape but again the shape was mismatched. I used count() method of pyspark dataframe to check the lenght of dataframe. I also tried UTF with toArray() method of column of pyspark dataframe which resulted in strange error like this org.apache.spark.SparkException: Job aborted due to stage failure: Task 2 in stage 116.0 failed 4 times, most recent failure: Lost task 2.3 in stage 116.0 (TID 6254, 10.2.1.54, executor 0): net.razorvine.pickle.PickleException: expected zero arguments for construction of ClassDict (for numpy.core.multiarray._reconstruct) Here is what I am doing rf = RandomForestClassifier( featuresCol="features", labelCol=TARGET_COL, predictionCol=TARGET_COL + "_predicted", # impurity="entropy" # maxDepth=5, # numTrees=1000, # minInfoGain=0.2, # subsamplingRate=0.8 ) evaluator = MulticlassClassificationEvaluator( predictionCol=TARGET_COL + "_predicted", labelCol=TARGET_COL, metricName="accuracy" ) paramGrid = ParamGridBuilder(). \ addGrid(rf.maxDepth, [3, 5, 7, 9, 11]). \ addGrid(rf.numTrees, [20, 50, 100, 200, 500]). \ addGrid(rf.minInfoGain, [0.0, 0.2, 0.5, 1.0]). \ addGrid(rf.subsamplingRate, [0.5, 0.8, 1.0]). \ addGrid(rf.impurity, ["entropy", "gini"]). \ build() paramGrid = ParamGridBuilder(). \ addGrid(rf.maxDepth, [3]). \ addGrid(rf.numTrees, [2]). \ addGrid(rf.minInfoGain, [0.0]). \ addGrid(rf.subsamplingRate, [0.5]). \ addGrid(rf.impurity, […
has answer: http://stackoverflow.com/a/51242824
accepted answer: http://stackoverflow.com/a/51242824
tagged with: classification
has comment: http://stackoverflow.com/comment/89465390
tagged with: python
linked to: http://stackoverflow.com/q/38984775
has comment: http://stackoverflow.com/comment/89464676
has title: Convert pyspark dataframe column of dense vector into numpy array
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89422292

http://stackoverflow.com/a/51243137
has body: We can generalize this to a basic "group-fold" approach: from operator import add, itemgetter def group_fold(data, fold=add, key=itemgetter('key'), vals=itemgetter('vals')): result = {} for entry in data: ky = key(entry) vlb = vals(entry) vla = result.get(ky, None) if vla: for subk, subv in vl.items(): if subk in vla: vla[subk] = fold(vla[subk], subv) else: vla[subk] = subv else: result[ky] = dict(vlb) return result We can thus now use this as group_fold(d), but we can customize the fold function, for example to multiply instead of add: from operator import mul group_fold(d, fold=mul)
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/51242725
upvote count: 1
type: Answer

http://stackoverflow.com/comment/89373063
comment on: http://stackoverflow.com/q/51187719
score: 0
type: QuestionComment
type: Comment
has text: [pip dependency tree](https://pypi.org/project/pipdeptree/)

http://stackoverflow.com/q/51214853
has comment: http://stackoverflow.com/comment/89422407
has comment: http://stackoverflow.com/comment/89463112
answer count: 0
has comment: http://stackoverflow.com/comment/89427973
type: UnansweredQuestion
tagged with: selenium
tagged with: web-scraping
upvote count: 1
has comment: http://stackoverflow.com/comment/89596176
type: Question
has title: Scrape embedded tweets from a webpage with Selenium and BeautifulSoup
score: 1
has comment: http://stackoverflow.com/comment/89421073
has comment: http://stackoverflow.com/comment/89434202
downvote count: 0
favorite count: 0
tagged with: beautifulsoup
has body: I need to extract tweets embedded in text articles. The problem with the pages I'm testing is that they load tweets in ~5 out of 10 runs. So I need to use Selenium to wait for the page to load but I cannot make it work. I followed steps from their official website: url = 'https://www.bbc.co.uk/news/world-us-canada-44648563' options = webdriver.ChromeOptions() options.add_argument("headless") driver = webdriver.Chrome(executable_path='/Users/ME/Downloads/chromedriver', chrome_options=options) driver.implicitly_wait(15) driver.get(url) html = driver.page_source soup = BeautifulSoup(html, "lxml") tweets_soup = [s.get_text() for s in soup.find_all('p', {'dir': 'ltr'})] tweets = '\n'.join(tweets_soup) print(tweets) I cannot use the option to wait for a certain element to appear because I'm scanning different pages and not all of them have embedded tweets. So to check if Selenium actually works or not I run the above script together with the script which doesn't use Selenium and compare their results: url = 'https://www.bbc.co.uk/news/world-us-canada-44648563' r = requests.get(url) soup = BeautifulSoup(r.content, "html.parser") tweets_soup = [s.get_text() for s in soup.find_all('p', {'dir': 'ltr'})] tweets = '\n'.join(tweets_soup) print(tweets) I will really appreciate the help of this wonderful community!
tagged with: python

http://stackoverflow.com/comment/89391018
score: 0
type: Comment
has text: Since all this goes via `tnsnames.ora`, the connection string is the same for both `sqlplus` and `cx_Oracle` I believe. The problem was solved by restarting the machine on which I'm working (yay!). I can then connect directly in python by simply `cx_Oracle.connect("/@THE_USER_NAME_FROM_TNSNAMES_ORA")`. Btw, the `cx_Oracle` documentation doesn't seem to touch on these things.
comment on: http://stackoverflow.com/a/51195324
type: AnswerComment

http://stackoverflow.com/a/51295683
has comment: http://stackoverflow.com/comment/89601304
upvote count: 0
has comment: http://stackoverflow.com/comment/89577113
answers question: http://stackoverflow.com/q/51295666
score: -1
has body: Wow, do I feel stupid. It's always the same thing: what's evaluated vs. what's just a list of symbols. The answer (see the eval): (define mask_cube (let ([leng 5]) (eval `(make-array #(,leng ,leng) 0)))) Still open to other answers that are coded with better style and am looking to modify this into a function/macro that translates np.zeros() and np.ones() into Lisp
downvote count: 1
type: Answer

http://stackoverflow.com/q/51205502
has comment: http://stackoverflow.com/comment/89401109
has comment: http://stackoverflow.com/comment/89408683
has answer: http://stackoverflow.com/a/51206104
tagged with: image-processing
has comment: http://stackoverflow.com/comment/89392289
downvote count: 1
tagged with: numpy
tagged with: opencv
has comment: http://stackoverflow.com/comment/89401111
accepted answer: http://stackoverflow.com/a/51207135
score: 8
upvote count: 9
has comment: http://stackoverflow.com/comment/89392385
tagged with: image
answer count: 4
has comment: http://stackoverflow.com/comment/89400782
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/51207248
favorite count: 0
has body: Like the image above suggests, how can I convert the image to the left into an array that represent the darkness of the image between 0 for white and decimals for darker colours closer to 1? as shown in the image usingpython 3`? Update: I have tried to work abit more on this. There are good answers below too. # Load image filename = tf.constant("one.png") image_file = tf.read_file(filename) # Show Image Image("one.png") #convert method def convertRgbToWeight(rgbArray): arrayWithPixelWeight = [] for i in range(int(rgbArray.size / rgbArray[0].size)): for j in range(int(rgbArray[0].size / 3)): lum = 255-((rgbArray[i][j][0]+rgbArray[i][j][1]+rgbArray[i][j][2])/3) # Reversed luminosity arrayWithPixelWeight.append(lum/255) # Map values from range 0-255 to 0-1 return arrayWithPixelWeight # Convert image to numbers and print them image_decoded_png = tf.image.decode_png(image_file,channels=3) image_as_float32 = tf.cast(image_decoded_png, tf.float32) numpy.set_printoptions(threshold=numpy.nan) sess = tf.Session() squeezedArray = sess.run(image_as_float32) convertedList = convertRgbToWeight(squeezedArray) print(convertedList) # This will give me an array of numbers.
has answer: http://stackoverflow.com/a/51207248
has comment: http://stackoverflow.com/comment/89395582
type: Question
has answer: http://stackoverflow.com/a/51207135
has answer: http://stackoverflow.com/a/51206116
has title: Convert a black and white image to array of numbers?
tagged with: python

http://stackoverflow.com/q/51179320
tagged with: beautifulsoup
type: UnansweredQuestion
tagged with: web-scraping
tagged with: python
tagged with: python-requests
downvote count: 1
score: -1
type: Question
tagged with: reddit
has body: This is the code I used to take all the pics from r/pics on reddit and put it into a directory. I want to be able to take the actual files in the directory and put it into a list. Stuck on how to do this. import requests from bs4 import BeautifulSoup as bs import os url = "https://www.reddit.com/r/pics/" r = requests.get(url) data = r.text soup = bs(data,'lxml') image_tags = soup.findAll('img') if not os.path.exists('direct'): os.makedirs('direct') os.chdir('direct') x = 0 for image in image_tags: try: url = image['src'] source = requests.get(url) if source.status_code == 200: img_path = 'direct-' + str(x) +'.jpg' with open(img_path, 'wb') as f: f.write(requests.get(url).content) f.close() x+=1 except: pass Edit: Here is updated code but still dealing with problem import requests from bs4 import BeautifulSoup as bs import os url = "https://www.reddit.com/r/drawing" r = requests.get(url) data = r.text soup = bs(data,'lxml') image_tags = soup.findAll('img') if not os.path.exists('directory'): os.makedirs('directory') os.chdir('directory') x = 0 mylist = [] for image in image_tags: url = image['src'] source = requests.get(url) if source.status_code == 200: img_path = 'direct-' + str(x) +'.jpg' with open(img_path, 'wb') as f: f.write(requests.get(url).content) mylist.append(img_path) f.close() x += 1 print(mylist)
upvote count: 0
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/51179433
has title: How to put the image files I scraped using Beautiful soup into a list?

http://stackoverflow.com/comment/89827029
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51424098
has text: I think the telegram does not allow downloading too old files. That's why you'll be faced with this exception.

http://stackoverflow.com/a/51322403
score: 1
upvote count: 1
has body: Don't use quad on a function that returns a list of two functions--instead, use it twice on two functions then compose the results into a list. The documentation for scipy.integrate.quad gives the possible signatures for the function to be integrated, and each signature shows that the function must return a double value (called float in Python), not a list. If you cannot change the definitions of time_start or fun or the parameters or return value of integral, you could use this code. from math import cos, sin from scipy.integrate import quad # Global variables and constants used in function `integral` time_start = 0 fun = lambda time: [cos(time), sin(time)] # The desired function def integral(time): """Return a list of two items containing the integrals of the two components of the `fun` function from `start_time` to `time`. """ def fun0(time): return fun(time)[0] def fun1(time): return fun(time)[1] integral0 = quad(fun0, time_start, time)[0] integral1 = quad(fun1, time_start, time)[0] return [integral0, integral1] Then the result of the statement print(integral(0), integral(pi/2), integral(pi)) is [0.0, 0.0] [0.9999999999999999, 0.9999999999999999] [3.6775933888827275e-17, 2.0] which is what you want, within precision error. By the way, using a lambda expression to create a function then assigning it to a name is considered to be poor programming practice in Python. See here, the fifth bullet point. Use a regular def block instead: def fun(time): return [cos(time), sin(time)] def integral(time): # as shown above Of course, the use of time_start and fun as global variables, rather than as parameters of integral, is also bad practice, but I kept to the way you used them.
downvote count: 0
answers question: http://stackoverflow.com/q/51321650
type: Answer

http://stackoverflow.com/q/51287807
has answer: http://stackoverflow.com/a/51889184
type: Question
tagged with: networkx
tagged with: graph
has body: I am attempting to run node2vec on a directed networkx network I have created. The network looks like this: OutEdgeDataView([(7, 1, {'senderId': 7, 'weight': 273}), (7, 8, {'senderId': 7, 'weight': 319}), (7, 9, {'senderId': 7, 'weight': 137}).... With each node having an integer ID and a weight linking one node to another. I am trying to use the node2vec module on this network as: from node2vec import Node2Vec node2vec = Node2Vec(mail_n_basic, dimensions=64, walk_length=30, num_walks=200, workers=4) And am returned with this error, any help explaining the error would be much appreciated: --------------------------------------------------------------------------- _RemoteTraceback Traceback (most recent call last) _RemoteTraceback: """ Traceback (most recent call last): File "C:\Users\Andrew\Anaconda3\lib\site-packages\joblib\externals\loky\process_executor.py", line 398, in _process_worker r = call_item.fn(*call_item.args, **call_item.kwargs) File "C:\Users\Andrew\Anaconda3\lib\site-packages\joblib\_parallel_backends.py", line 561, in __call__ return self.func(*args, **kwargs) File "C:\Users\Andrew\Anaconda3\lib\site-packages\joblib\parallel.py", line 224, in __call__ for func, args, kwargs in self.items] File "C:\Users\Andrew\Anaconda3\lib\site-packages\joblib\parallel.py", line 224, in &lt;listcomp&gt; for func, args, kwargs in self.items] File "C:\Users\Andrew\Anaconda3\lib\site-packages\node2vec\node2vec.py", line 51, in parallel_generate_walks walk_to = np.random.choice(walk_options, size=1)[0] File "mtrand.pyx", line 1126, in mtrand.RandomState.choice ValueError: a must be non-empty """ The above exception was the direct cause of the following exception: ValueError Traceback (most recent call last) &lt;ipython-input-58-3ac160061528&gt; in &lt;module&gt;() 1 ----&gt; 2 node2vec = Node2Vec(mail_n_basic, dimensions=64, walk_length=30, num_walks=200, workers=4) ~\Anaconda3\lib\site-packages\node2vec\node2vec.py in __init__(self, graph, dimensions, walk_length, num…
score: 0
answer count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/51889184
type: AnsweredQuestion
has title: Node2vec and networkx

http://stackoverflow.com/a/51228709
has comment: http://stackoverflow.com/comment/89447825
score: 0
answers question: http://stackoverflow.com/q/51227148
has body: Simple, so if your text is: text = "NC don’t like working together www.linktowtweet.org" text = re.sub(r'https?:\/\/.*[\r\n]*', '', text, flags=re.MULTILINE) #to remove any URL text = text.split() #splits sentence into words with delimiter=" " last_word = text[-1] So there you go!! Now you'll get the last word "together".
type: Answer

http://stackoverflow.com/q/51235920
accepted answer: http://stackoverflow.com/a/51260189
tagged with: python
has answer: http://stackoverflow.com/a/51260189
type: AnsweredQuestion
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/89467890
type: Question
score: 0
has comment: http://stackoverflow.com/comment/89479602
has title: Plot for each fold of classifier
has body: This is my code for kfolds kf = KFold(class_label.shape[0], n_folds=5, shuffle=True). for train_index, test_index in kf:. print("Train:", train_index, "Validation:",test_index). X_train, X_test = np.array(x)[train_index], np.array(x)[test_index]. y_train, y_test = np.array(class_label)[train_index], np.array(class_label)[test_index] the plot should look like this but with 10 lines I want to plot a line for each fold so there should be ten lines in all: test_score = []. train_score = []. for depth in range(20):. clf = DecisionTreeClassifier(max_depth = depth + 1). clf.fit(X_train,y_train). train_score.append(clf.score(X_train,y_train)). test_score.append(clf.score(X_test,y_test)). plt.figure(figsize = (8,8)). plt.plot(range(20),train_score). plt.plot(range(20), test_score). plt.xlabel('Tree Depth'). plt.ylabel('Accuracy'). plt.legend(['Training set','Test set']).
answer count: 1

http://stackoverflow.com/comment/89582917
has text: I tried with the 'autoescape' and I got 'autoescape' tag requires exactly one argument and on the other hand, I tried with 'JSON.parse' even it also didn't help me.
comment on: http://stackoverflow.com/a/51299702
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/51295664
has comment: http://stackoverflow.com/comment/89568832
upvote count: 5
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51295644
type: Answer
has body: The function you are looking for is product but you need to set it up first. The problem is that you have your values "sideways"--you want to put all possible values for the first position together, then those for the second, etc. You can "transpose" your data with the *zip() maneuver. from itertools import product list(product(*zip(one, two))) The result from that is [('a1', 'b1', 'c1'), ('a1', 'b1', 'c2'), ('a1', 'b2', 'c1'), ('a1', 'b2', 'c2'), ('a2', 'b1', 'c1'), ('a2', 'b1', 'c2'), ('a2', 'b2', 'c1'), ('a2', 'b2', 'c2')] If you really want lists rather than tuples, use [list(v) for v in product(*zip(one, two))] which gives you [['a1', 'b1', 'c1'], ['a1', 'b1', 'c2'], ['a1', 'b2', 'c1'], ['a1', 'b2', 'c2'], ['a2', 'b1', 'c1'], ['a2', 'b1', 'c2'], ['a2', 'b2', 'c1'], ['a2', 'b2', 'c2']] Note that these are not exactly what you listed as the desired output, since you left out a couple of possibilities.
has comment: http://stackoverflow.com/comment/89568830
answers question: http://stackoverflow.com/q/51295644
score: 5

http://stackoverflow.com/q/51260909
has answer: http://stackoverflow.com/a/77244741
has body: I'm trying to install Jupyter on Python 3.7 and seem to be stumbling over this error again and again; winpty/cywinpty.c(598): fatal error C1083: Cannot open include file: 'winpty.h': No such file or directory error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio\\2017\\BuildTools\\VC\\Tools\\MSVC\\14.14.26428\\bin\\HostX86\\x86\\cl.exe' failed with exit status 2 I get the same error when attempting to install pywinpty via pip. I have installed &amp; reinstalled the build tools to no avail and the command window is elevated - any ideas? UPDATE: Not quite resolved in 3.7 - but it worked fine in 3.6, I've rolled back.
accepted answer: http://stackoverflow.com/a/51431612
upvote count: 21
has title: Error installing Jupyter & pywinpty (Python)
type: AnsweredQuestion
score: 21
type: Question
has answer: http://stackoverflow.com/a/67470545
downvote count: 0
possible better answer: http://stackoverflow.com/a/66954407
has comment: http://stackoverflow.com/comment/104186590
favorite count: 0
has answer: http://stackoverflow.com/a/66954407
has answer: http://stackoverflow.com/a/66327466
answer count: 5
tagged with: python
has answer: http://stackoverflow.com/a/51431612
tagged with: jupyter

http://stackoverflow.com/a/51175261
has comment: http://stackoverflow.com/comment/89333996
has comment: http://stackoverflow.com/comment/89333537
type: AcceptedAnswer
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/89333849
accepted answer of: http://stackoverflow.com/q/51175154
score: 1
upvote count: 1
has body: import numpy as np a = np.asarray([1, 3, 4, 1, 5, 2]) print( a[::2].mean() ) #All Odd Elements print( a[1::2].mean() ) #All Even Elements Output: 3.33333333333 2.0 Edit as per comment(every 24 elements) import numpy as np a = range(1, 73) for i in map(None,*[iter(a)]*24): print( np.array(i).mean() ) Output: 12.5 36.5 60.5
answers question: http://stackoverflow.com/q/51175154

http://stackoverflow.com/comment/89549610
has text: When you don't specify a sort order, you get whatever sort was already there, which may have been influenced by the view the user chose.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51277226

http://stackoverflow.com/q/51195525
has title: extracting IP address from text file and use them as input in Python
has comment: http://stackoverflow.com/comment/89373276
has comment: http://stackoverflow.com/comment/89372751
linked to: http://stackoverflow.com/q/4836375
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89372589
accepted answer: http://stackoverflow.com/a/51235748
type: Question
has answer: http://stackoverflow.com/a/51195794
answer count: 2
has comment: http://stackoverflow.com/comment/89372677
has comment: http://stackoverflow.com/comment/89372767
has answer: http://stackoverflow.com/a/51235748
has body: I am currently trying to get ip address from text. But the code I tried is only getting the last line from the file. I am using the following code import paramiko import time import getpass import sys import socket import re user = raw_input("Enter you username: ") password = getpass.getpass() inp = open(r'ipaddressrouter.txt', 'r') for line in inp: try: ssh_client = paramiko.SSHClient() ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh_client.connect(hostname=line,username=user,password=password) print "Successful Connection to " + line + '\n' stdin, stdout, stderr = ssh_client.exec_command('sh ip int b \n') output = stdout.read() out = open('out.txt', 'a') out.write(line + '\n') out.write(output + '\n') out.write('\n') except (socket.error, paramiko.AuthenticationException): status = 'fail' ssh_client.close help would be appreciated Update: When I removed except I got the following error File "C:\Users\abc\Desktop\Python Test Scripts\newstest2.py", line 20, in ssh_client.connect(hostname=host,username=user,password=password) File "C:\Python27\lib\site-packages\paramiko\client.py", line 329, in connect to_try = list(self._families_and_addresses(hostname, port)) File "C:\Python27\lib\site-packages\paramiko\client.py", line 200, in _families_and_addresses hostname, port, socket.AF_UNSPEC, socket.SOCK_STREAM)socket.gaierror: [Errno 11004] getaddrinfo failed Can some one help me out ?
score: 0
tagged with: python
has comment: http://stackoverflow.com/comment/89373200
tagged with: file-handling
possible better answer: http://stackoverflow.com/a/51195794

http://stackoverflow.com/comment/89340760
score: 0
type: Comment
type: QuestionComment
has text: do you mean [single precision](https://www.wiki-zero.co/index.php?q=aHR0cHM6Ly9lbi53aWtpcGVkaWEub3JnL3dpa2kvU2luZ2xlLXByZWNpc2lvbl9mbG9hdGluZy1wb2ludF9mb3JtYXQ0); and by *throw* you want to omit?
comment on: http://stackoverflow.com/q/51179116

http://stackoverflow.com/comment/89516915
comment on: http://stackoverflow.com/a/51269282
has text: If that would be the case the package `flask-macros` should be found if I search for `project`. Which is not. And if that would be the case a search for `simpleexec` would return one of my packages. Which it does not. And if I search for `macr` the package `flask-macros` is not returned as it should be. See my question above. That's why I'm asking.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/51277949
upvote count: 3
tagged with: image-processing
type: Question
score: 3
has body: I want to apply Gabor filter for feature extraction from image then on the trained data I will be applying NN or SVM.I didn't applied batch processing though but it will be done or if you can help me with the machine learning part it will be great for me.Thank you. Here is my code: import cv2 import numpy as np import glob img=glob.glob("C://Users//USER//Pictures//Saved Pictures//tuhin.jpg") img = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)[1] ret, labels = cv2.connectedComponents(img) label_hue = np.uint8(179*labels/np.max(labels)) blank_ch = 255*np.ones_like(label_hue) labeled_img = cv2.merge([label_hue, blank_ch, blank_ch]) labeled_img = cv2.cvtColor(labeled_img, cv2.COLOR_HSV2BGR) labeled_img[label_hue==0] = 0 cv2.imshow('labeled.png', labeled_img) cv2.waitKey() def build_filters(): filters = [] ksize = 31 for theta in np.arange(0, np.pi, np.pi / 16): kern = cv2.getGaborKernel((ksize, ksize), 4.0, theta, 10.0, 0.5, 0, ktype=cv2.CV_32F) kern /= 1.5*kern.sum() filters.append(kern) return filters def process(img, filters): accum = np.zeros_like(img) for kern in filters: fimg = cv2.filter2D(img, cv2.CV_8UC3, kern) np.maximum(accum, fimg, accum) return accum filters=build_filters() res1=process(img,filters) cv2.imshow('result',res1) cv2.waitKey(0) cv2.destroyAllWindows()
has answer: http://stackoverflow.com/a/51278197
tagged with: gabor-filter
has answer: http://stackoverflow.com/a/51280508
tagged with: image
tagged with: svm
answer count: 2
downvote count: 0
favorite count: 0
has title: How to use Gabor filters for feature extraction from image?
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/89566670
type: QuestionComment
comment on: http://stackoverflow.com/q/51294534
has text: There is no way for us to help you without your code.
score: 0
type: Comment

http://stackoverflow.com/q/51225275
has answer: http://stackoverflow.com/a/75146686
answer count: 2
tagged with: pandas
downvote count: 0
has body: Lists or numpy arrays can be unpacked to multiple variables if the dimensions match. For a 3xN array, the following will work: import numpy as np a,b = [[1,2,3],[4,5,6]] a,b = np.array([[1,2,3],[4,5,6]]) # result: a=[1,2,3], b=[4,5,6] How can I achieve a similar behaviour for the columns of a pandas DataFrame? Extending the above example: import pandas as pd df = pd.DataFrame([[1,2,3],[4,5,6]]) df.columns = ['A','B','C'] # Rename cols and df.index = ['i', 'ii'] # rows for clarity The following does not work as expected: a,b = df.T # result: a='i', b='ii' a,b,c = df # result: a='A', b='B', c='C' However, what I would like to get is the following: a,b,c = unpack(df) result: a=df['A'], b=df['B'], c=df['C'] Is the function unpack already available in pandas? Or can it be mimicked in an easy way?
favorite count: 0
has comment: http://stackoverflow.com/comment/89431259
has comment: http://stackoverflow.com/comment/89430996
accepted answer: http://stackoverflow.com/a/51225561
tagged with: python
has comment: http://stackoverflow.com/comment/89431395
tagged with: syntactic-sugar
has comment: http://stackoverflow.com/comment/89431047
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89431290
has comment: http://stackoverflow.com/comment/89430904
score: 16
has comment: http://stackoverflow.com/comment/89431086
upvote count: 16
type: Question
has comment: http://stackoverflow.com/comment/89430978
has comment: http://stackoverflow.com/comment/89431401
has title: How to unpack the columns of a pandas DataFrame to multiple variables
has comment: http://stackoverflow.com/comment/89431333
possible better answer: http://stackoverflow.com/a/75146686
has answer: http://stackoverflow.com/a/51225561

http://stackoverflow.com/q/51297877
has answer: http://stackoverflow.com/a/51297983
has body: I have multiple .txt files in a directory and I want to merge them into one by importing in python. The catch here is that after the merge I want to convert it into one csv file on which the whole program is based. So far I only had to input one .txt file and converted it into csv file by this code: import io bytes = open('XYZ.txt', 'rb').read() df=pd.read_csv(io.StringIO(bytes.decode('utf-8')), sep='\t', parse_dates=['Time'] ) df.head() Now I need to input multiple .txt files, merge them and then convert them into csv files. Any workaround?
tagged with: python
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89645677
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89572794
has title: Merge multiple .txt/csv files in Python
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/89645744
has answer: http://stackoverflow.com/a/51297961
has comment: http://stackoverflow.com/comment/89572823
score: 0

http://stackoverflow.com/comment/89322962
has text: As for the threadpool acting like a single thread, well, if the "Computational heavy code" is so light that it finishes before the next word is submitted, only one thread will be active while the other threads will keep waiting for something to process. That's probably what happens with multiple processes too.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51168462

pymongo
tags question: http://stackoverflow.com/q/51283260
tags question: http://stackoverflow.com/q/51176651
tags question: http://stackoverflow.com/q/51277787
tags question: http://stackoverflow.com/q/51244068
type: Tag
tag name: pymongo
tags question: http://stackoverflow.com/q/51270810
tags question: http://stackoverflow.com/q/51226234
tags question: http://stackoverflow.com/q/51210367
tags question: http://stackoverflow.com/q/51260177
tags question: http://stackoverflow.com/q/51295266
tags question: http://stackoverflow.com/q/51229817
tags question: http://stackoverflow.com/q/51275815
tags question: http://stackoverflow.com/q/51232936
tags question: http://stackoverflow.com/q/51244329

http://stackoverflow.com/comment/89319672
has text: Your answer happens to be correct for `a.shape[1] == 2` but for any other size of the 2nd dimension it won't. Take for example `a = np.arange(36).reshape(4, 3, 3)`. You will have as many rows as the 2nd dim's size but the OP wants odd and even, i.e. exactly 2.
score: 0
comment on: http://stackoverflow.com/a/51168225
type: AnswerComment
type: Comment

http://stackoverflow.com/q/51179920
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89342250
score: 0
answer count: 1
tagged with: flask
favorite count: 0
has comment: http://stackoverflow.com/comment/89342522
has body: Is there a way to limit the posts per hour a user can make in order to avoid spam? I've thought of making it based on cookies or IP address, but I haven't had any luck finding examples of how to do it that way. EDIT: I want to keep it anonymous, so there will be no registered users.
tagged with: python
has title: How can I add a posting limit to a Flask forum website?
has answer: http://stackoverflow.com/a/51180040
has comment: http://stackoverflow.com/comment/89342257
upvote count: 1
accepted answer: http://stackoverflow.com/a/51180040
downvote count: 1

http://stackoverflow.com/q/51287671
type: Question
tagged with: data-science
has body: I have a dataframe that contains a column of lists. For example, some entries may be: A,B,C A,C,D D,A C G,E,F,D,C,A I would to be able to one-hot-embed this such that I end up with: A B C D E F G 1 0 1 1 0 0 0 1 0 0 1 0 0 0 0 0 1 0 0 0 0 1 0 0 1 0 0 0 1 1 1 1 1 1 1 Is there a clean way to do this? Currently I'm looping through each row, and then each item, to embed, and then sum-combining duplicate columns but there has to be a better way.
tagged with: pandas
has title: Encoding a dataframe of lists
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/46867201
answer count: 0
duplicate of: http://stackoverflow.com/q/46867201
score: 1
upvote count: 1

http://stackoverflow.com/q/51217909
upvote count: 7
downvote count: 1
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
score: 6
tagged with: python
tagged with: emoji
answer count: 4
tagged with: python-unicode
has answer: http://stackoverflow.com/a/72463965
tagged with: unicode-string
has body: This question has been asked here Python : How to remove all emojis Without a solution, I have as step towards the solution. But need help finishing it off. I went and got all the emoji hex code points from the emoji site: https://www.unicode.org/emoji/charts/emoji-ordering.txt I then read in the file like so: file = open('emoji-ordering.txt') temp = file.readline() final_list = [] while temp != '': #print(temp) if not temp[0] == '#' : utf_8_values = ((temp.split(';')[0]).rstrip()).split(' ') values = ["u\\"+(word[0]+((8 - len(word[2:]))*'0' + word[2:]).rstrip()) for word in utf_8_values] #print(values[0]) final_list = final_list + values temp = file.readline() print(final_list) I hoped this would give me unicode literals. It does not, my goal is to get unicode literals so I can use part of the solution from the last question and be able to exclude all emojis. Any ideas what we need to get a solution?
has answer: http://stackoverflow.com/a/57663707
type: Question
linked to: http://stackoverflow.com/q/48860804
has title: Removing all Emojis from Text
has answer: http://stackoverflow.com/a/75521419
has answer: http://stackoverflow.com/a/52571541

http://stackoverflow.com/a/51329195
answers question: http://stackoverflow.com/q/51275426
type: Answer
has comment: http://stackoverflow.com/comment/137766153
has body: In case it would be okay that it's not really stored but calculated dynamically you could use a simple property for it. from typing import NamedTuple class BlockTime(NamedTuple): t_present: float t_pause: float @property def t_each(self): return self.t_present + self.t_pause &gt;&gt;&gt; b = BlockTime(10, 20) &gt;&gt;&gt; b.t_each # only available as property, not in the representation nor by indexing or iterating 30 That has the advantage that you can never (not even accidentally) store a wrong value for it. However at the expense of not actually storing it at all. So in order to appear as if it were stored you'd have to at least override __getitem__, __iter__, __repr__ which is likely too much trouble. For example the NamedTuple approach given by Patrick Haugh has the downside that it's still possible to create inconsistent BlockTimes or lose parts of the namedtuple convenience: &gt;&gt;&gt; b = BlockTime.factory(1.0, 2.0) &gt;&gt;&gt; b._replace(t_present=20) BlockTime(t_present=20, t_pause=2.0, t_each=3.0) &gt;&gt;&gt; b._make([1, 2]) TypeError: Expected 3 arguments, got 2 The fact that you actually have a "computed" field that has to be in sync with other fields already indicates that you probably shouldn't store it at all to avoid inconsistent state.
accepted answer of: http://stackoverflow.com/q/51275426
score: 5
upvote count: 5
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/51182382
tagged with: conda
upvote count: 0
has title: What is the difference between pip search and conda search
answer count: 1
favorite count: 0
tagged with: python
duplicate of: http://stackoverflow.com/q/20994716
type: UnansweredQuestion
tagged with: pip
has body: Pip search says I have Beautifulsoup installed but conda search says I don't have it. What does that mean exactly?
downvote count: 1
type: Question
tagged with: anaconda
linked to: http://stackoverflow.com/q/20994716
score: -1
has answer: http://stackoverflow.com/a/51182402

http://stackoverflow.com/q/51282400
linked to: http://stackoverflow.com/q/41341922
favorite count: 0
type: UnansweredQuestion
score: 6
has body: I have the table which is updated every day. I use this table for analysis. I want to have a static window of 6 months data as input for analysis. I know I can make a filter like this in SQL to have 6 months data every time I run the code. date &gt;= dateadd(mm, -6, getdate()) Can somebody suggest how I can carry on the same action in PySpark. I can only think of this: df.filter(col("date") &gt;= date_add(current_date(), -6))) Thanks in advance!
tagged with: python
upvote count: 6
has answer: http://stackoverflow.com/a/51282633
type: Question
tagged with: apache-spark-sql
downvote count: 0
tagged with: pyspark
has title: How to get today - “6 months” date in PySpark(SQL)
duplicate of: http://stackoverflow.com/q/41341922
tagged with: filter
tagged with: apache-spark
answer count: 1

http://stackoverflow.com/comment/89608859
has text: Do you want to return the first or all pairs? What happens if there is a 3 items that `compute()` to the same, would you expect all 3 or just when you get a pair?
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51316065

http://stackoverflow.com/q/51254772
tagged with: caffe
tagged with: lstm
upvote count: 2
favorite count: 0
has comment: http://stackoverflow.com/comment/90251573
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89488476
tagged with: python
score: 2
answer count: 0
downvote count: 0
type: Question
has body: I have a pre-trained caffemodel and prototxt for a model with LSTMs. I get the U, W and bias parameters from the model but where can I fetch the initial cell state and hidden state from the pre-trained model parameters.
has title: Fetch c_0 and h_0 from LSTM caffe pretrained model

http://stackoverflow.com/a/51198910
has body: Here the proper solution. First have to create a list from random number and go through each number (like push dial numbers on a phone) a = randint(0,99999) # Put in a list random number for exaple 124 will be [1,2,4] list = [int(d) for d in str(a)] # Go through the list where number of iterations is equal to number of elements # Each iteration send value of this element to xpath for item in list: self.driver.find_element_by_xpath("//input[@value={0}]".format(item)).click()
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51185284

http://stackoverflow.com/comment/89424534
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51221986
has text: @WillemVanOnsem I've guessed that. Can it be created by modifying source code(in c++)? I've knowledge of c++ but not experieced.
score: 0

shapes
tags question: http://stackoverflow.com/q/51250210
tags question: http://stackoverflow.com/q/51288736
tag name: shapes
type: Tag

http://stackoverflow.com/comment/89444429
score: 0
has text: Read the `reshape` docs. and make sure you understand why your array is 49 times larger the what the model expects.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51231925

http://stackoverflow.com/comment/89334996
has text: And the question is..?
comment on: http://stackoverflow.com/q/51176030
type: Comment
type: QuestionComment
score: 2

http://stackoverflow.com/a/51212778
type: Answer
has body: cx_Feeze needs compiling to run (this is usually done for you on Windows but it has not been done for 3.7 yet (see the releases on PyPi) so you have two options: Wait until it is (shouldn't be more than a few days/weeks, it wasn't last time python updated in any case) Compile it yourself In the case of compiling, if you have VS installed then you probably have not set the correct environment variables SET DISTUTILS_USE_SDK=1 SET MSSdk=1 Taken from here. I would recomend the answers in this question over the duplicate suggested above.
score: 0
answers question: http://stackoverflow.com/q/51205118

http://stackoverflow.com/comment/89558635
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51290164
type: AnswerComment
has text: Thank you! @Rakesh Just wondering why is "df = pd.read_csv(filename,names=['code'])" the portion names = ['code'] necessary?

http://stackoverflow.com/comment/89591005
type: QuestionComment
has text: Are your raw samples from a stereo file, by any chance ?
comment on: http://stackoverflow.com/q/51305317
score: 0
type: Comment

http://stackoverflow.com/q/51190580
has title: initialize a pandas empty dataframe with data type string
type: UnansweredQuestion
has body: I want to create a Dataframe with given number of rows and columns, and want to initialize every element with data type string. When I'm using : pd.DataFrame(np.empty((3, 4)), dtype = "S100") It gives an empty dataframe but the data type is binary. Is there any other dtype parameter which gives me data type as str.
upvote count: 1
has answer: http://stackoverflow.com/a/51191684
type: Question
linked to: http://stackoverflow.com/q/36462257
score: 1
tagged with: dataframe
duplicate of: http://stackoverflow.com/q/36462257
has comment: http://stackoverflow.com/comment/89363004
downvote count: 0
answer count: 1
favorite count: 0
tagged with: pandas
tagged with: python

http://stackoverflow.com/q/51306488
tagged with: vispy
has title: Transparency with voxels in VisPy
has body: I am attempting to use python and VisPy to display 3D data from a numpy array. I looked up the example here and it was extrememly useful. I've gotten the data to display--but it doesn't look the way I want. The way my data is displaying now I really can't see every voxel. I can see the sides of the shape, but it honestly looks like just a hollowed out cube. It looks like this. I think this is probably due to the fact that many values are negative or that most values are relatively small with a few large outliers. Either way, I would like to be able to set the transparency of values individually--so that positive values, for instance, are 70% transparent, while values less then -2 but greater than -5 are only 30% transparent and a shade of green. I'm hoping this will allow me to see an actual "volume" as opposed to what I have now. Here's a peek of what I have now, in case anyone would like to see (note, heavily copied and pasted from the example vispy code I linked): # Creating volume data (returns a 100x100x100 numpy array) volume_data = func() # Prepare canvas canvas = scene.SceneCanvas(keys='interactive', size=(800, 600), show=True) # Set up a viewbox to display the image with interactive pan/zoom view = canvas.central_widget.add_view() # Creating and assigning camera camera = scene.cameras.ArcballCamera(parent=view.scene, fov=60) view.camera = camera # Create the volume volume = scene.visuals.Volume(volume_data, clim=(0, 1), parent=view.scene, threshold=0.225,emulate_texture=False) volume.cmap = 'blues' if __name__ == '__main__': print(__doc__) app.run()
tagged with: 3d
type: AnsweredQuestion
downvote count: 0
favorite count: 0
type: Question
tagged with: volume
tagged with: python
score: 1
tagged with: voxels
has answer: http://stackoverflow.com/a/51309283
accepted answer: http://stackoverflow.com/a/51309283
upvote count: 1
answer count: 1

http://stackoverflow.com/q/51320590
has comment: http://stackoverflow.com/comment/89617175
has answer: http://stackoverflow.com/a/75110333
score: 6
tagged with: django
has body: I'm junior backend dev. I don't know how to use JS. I can't set true... or reverse i can't set false. My code: Prepared {% for player in players %} {% endfor %} Let's say in 'players' I have 5 players, each player has a value "player_check". Two of them have: player.player_check = True Rest: player.player_check = False I'm trying to initiate checkbox in my table with these values using {{}} or {% %} I've tried: Nothing works... Then i found that checkbox has a parametr checked so: That was ok BUT... now i cant turn it off: So i decided to use django templpates + change in python code: Now player.player_check equals checked or unchecked It still doesn't work! Now i can't put {{ }} without name like "something"={{ foo }} Now i have 0 ideas what i can do more to make it work... Maybe JS? but i cant believe there is no right way to do it just in django/python. ;/
has title: Django template - set checkbox checked if object.val == true
type: Question
type: AnsweredQuestion
tagged with: django-forms
has comment: http://stackoverflow.com/comment/89616705
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/51320636
favorite count: 0
accepted answer: http://stackoverflow.com/a/51320636
tagged with: python
tagged with: checkbox
upvote count: 6
tagged with: django-templates
possible better answer: http://stackoverflow.com/a/75110333

http://stackoverflow.com/comment/89351179
comment on: http://stackoverflow.com/q/51184260
type: Comment
has text: @DyZ Thanks, yes I know, the question is, how do I formulate my filepath variable, created from 'raw_input' so that read_csv recognizes it as a string literal filepath?
type: QuestionComment
score: 0

http://stackoverflow.com/q/51285930
has title: Issues on Height Map to Normal Map with Python OpenCV
downvote count: 1
type: Question
tagged with: opencv
tagged with: image
tagged with: numpy
score: 0
upvote count: 1
answer count: 1
accepted answer: http://stackoverflow.com/a/54206140
favorite count: 0
has answer: http://stackoverflow.com/a/54206140
tagged with: python
has body: I'm trying to generate a tangent space normal map from a height map using opencv and python following this tutorial. The intermediate steps seem to be fine, still I struggle with the final image. Besides the fact that I cannot merge my output- Maybe somebody has an idea what I am doing wrong? I use this as an example image: This is my code: #!/usr/bin/env python from __future__ import division import cv2 as cv import numpy as np import math from matplotlib import pyplot as plt img = cv.imread('sourceimage.jpg') gray_image = cv.cvtColor(img, cv.COLOR_RGB2GRAY) cv.imwrite( "grey.png", gray_image ) rows,cols = gray_image.shape M1 = np.float32([ [1,0, 1], [0,1, 0] ]) M2 = np.float32([ [1,0,-1], [0,1, 0] ]) M3 = np.float32([ [1,0, 0], [0,1,1] ]) M4 = np.float32([ [1,0, 0], [0,1,-1] ]) temp1 = cv.warpAffine(gray_image,M1,(cols,rows), borderMode = cv.BORDER_WRAP) temp2 = cv.warpAffine(gray_image,M2,(cols,rows), borderMode = cv.BORDER_WRAP) temp3 = cv.warpAffine(gray_image,M3,(cols,rows), borderMode = cv.BORDER_WRAP) temp4 = cv.warpAffine(gray_image,M4,(cols,rows), borderMode = cv.BORDER_WRAP) dx = cv.subtract(temp1, temp2) dy = cv.subtract(temp3, temp4) dxNeg = dx * -1 dyNeg = dy * -1 dxSquare = np.power(dx, 2) dySquare = np.power(dy, 2) nxSquareRoot = np.sqrt(dxSquare + dxSquare + 1) nySquareRoot = np.sqrt(dySquare + dySquare + 1) nzSquareRoot = np.sqrt(dxSquare + dxSquare + 1) nx = np.divide(dxNeg,nxSquareRoot) ny = np.divide(dyNeg,nySquareRoot) nz = np.divide(dxNeg,nzSquareRoot) R = np.divide(nx +1,2) G = np.divide(ny +1,2) B = nx new_rgb = np.stack(R,G,B) cv.imwrite( "output.jpg", new_rgb )
tagged with: normals
type: AnsweredQuestion

http://stackoverflow.com/comment/89478856
type: QuestionComment
comment on: http://stackoverflow.com/q/51249797
has text: @WillemVanOnsem required=True did indeed prevent me from submitting my form. With required=False I was able to submit the form without checking the boxes
type: Comment
score: 0

http://stackoverflow.com/comment/89485387
type: AnswerComment
comment on: http://stackoverflow.com/a/51214319
has text: One such example may be when you want to store a collection of `np.ndarrays` of variables types. These tools are here for you to decide when one solution is more appropriate than another. You of course have your own value hierarchy for your code, where convenience in programming may be more important to you than runtime speed or memory usage.
type: Comment
score: 0

http://stackoverflow.com/a/61694647
score: 1
has body: import plotly.express as px It's the latest update.
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/51251188
downvote count: 0

http://stackoverflow.com/a/51315342
answers question: http://stackoverflow.com/q/51315241
upvote count: 2
accepted answer of: http://stackoverflow.com/q/51315241
type: AcceptedAnswer
type: Answer
score: 2
downvote count: 0
has body: &gt;&gt;&gt; import inspect &gt;&gt;&gt; d = {'abc': inspect._empty, 'xyz': None} &gt;&gt;&gt; d {'abc': &lt;class 'inspect._empty'&gt;, 'xyz': None} &gt;&gt;&gt; {k:v if v != inspect._empty else 'x' for k,v in d.items()} {'abc': 'x', 'xyz': None} &gt;&gt;&gt;
has comment: http://stackoverflow.com/comment/89715001

http://stackoverflow.com/a/59322783
upvote count: 0
has comment: http://stackoverflow.com/comment/104845780
type: Answer
score: -1
downvote count: 1
has body: Try to import in this way: from PyQt5 import QtWidgets ... app = QtWidgets.QApplication(sys.argv) w = QMainWindow() w.show() app.exec_() This works for me.
answers question: http://stackoverflow.com/q/51284268

http://stackoverflow.com/q/51315241
tagged with: python
accepted answer: http://stackoverflow.com/a/51315342
type: AnsweredQuestion
has body: how to check whether my key has value of &lt;class 'inspect._empty'&gt; Dictionary looks like : {'abc': &lt;class 'inspect._empty'&gt;, 'xyz': None} Now, I want to set abc equal to x value if it has value &lt;class 'inspect._empty'&gt; def _arg_unset(args_dict: Dict, key: str) -&gt; bool: """return True if key is not set to some actual value in args_dict""" return args_dict.get(key) in {None, Parameter.empty} In above cod, dict needs to be passed as first param and key as second param.
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/51315342
type: Question
upvote count: 1
answer count: 1
has title: How to check condition for key and value in python dictionary for specific value
favorite count: 0

http://stackoverflow.com/comment/89438308
type: Comment
comment on: http://stackoverflow.com/q/51229274
score: 0
type: QuestionComment
has text: You should ask a specific question for a particular programming problem. Since Stack Overflow hides the Close reason from you: *"Many good questions generate some degree of opinion based on expert experience, but answers to this question will tend to be almost entirely based on opinions, rather than facts, references, or specific expertise."*

http://stackoverflow.com/q/51290513
has title: In Django Factory Boy, is it possible to specify custom FactoryOptions for a certain instance?
tagged with: django
tagged with: python
type: AnsweredQuestion
has body: I'm writing unit tests for a Django app which use factory_boy test fixtures. In some cases, one fixture might try to create an object that was already created by another fixture, which leads to error messages similar to the following: django.db.utils.IntegrityError: duplicate key value violates unique constraint "lucy_web_sessiontype_title_c207e4f8_uniq" DETAIL: Key (title)=(Postpartum Doula Support) already exists. To avoid this, my first inclination is to write a try..except block, like so: try: SessionTypeFactory(title='Welcome') except psycopg2.IntegrityError as e: pass However, it seems like it would be more elegant to use the django_get_or_create option described at http://factoryboy.readthedocs.io/en/latest/orms.html#factory.django.DjangoOptions.django_get_or_create. However, as far as I can tell from http://factoryboy.readthedocs.io/en/latest/reference.html#factory.FactoryOptions, options specifie in the factory's Meta class will apply to all instances, whereas I would only like it to only apply to this instance. Is it possible to specify these options in the constructor?
score: 1
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/51294505
tagged with: database
answer count: 2
tagged with: factory-boy
downvote count: 0
favorite count: 0
possible better answer: http://stackoverflow.com/a/51290681
accepted answer: http://stackoverflow.com/a/51294505
has answer: http://stackoverflow.com/a/51290681

http://stackoverflow.com/comment/89393460
type: QuestionComment
has text: time.sleep(3) will create issues for slower network connection if all set of comments are not loaded
comment on: http://stackoverflow.com/q/51206143
score: 0
type: Comment

http://stackoverflow.com/q/51257037
answer count: 1
downvote count: 0
tagged with: keras
favorite count: 0
has answer: http://stackoverflow.com/a/51265433
tagged with: python
accepted answer: http://stackoverflow.com/a/51265433
tagged with: artificial-intelligence
upvote count: 6
type: AnsweredQuestion
score: 6
tagged with: machine-learning
tagged with: tensorflow
type: Question
has body: First of all, I realize from a methodological standpoint why your loss function must be dependent on the output of a neural network. This question comes more from an experiment I've been doing while trying to understand Keras and Tensorflow a bit better. Consider the following: input_1 = Input((5,)) hidden_a = Dense(2)(input_1) output = Dense(1)(hidden_a) m3 = Model(input_1, output) def myLoss (y_true, y_pred): return K.sum(hidden_a) # (A) #return K.sum(hidden_a) + 0*K.sum(y_pred) # (B) m3.compile(optimizer='adam', loss=myLoss) x = np.random.random(size=(10,5)) y = np.random.random(size=(10,1)) m3.fit(x,y, epochs=25) This code induces: ValueError: An operation has `None` for gradient. Please make sure that all of your ops have a gradient defined (i.e. are differentiable). Common ops without gradient: K.argmax, K.round, K.eval. but it runs if you swap line A for line B despite the fact that nothing has changed numerically. The former case seems like it should be perfectly fine to me. The computation graph is well defined and everything should be differentiable in terms of the loss. But it seems that Keras requires y_pred to be in the loss function somehow regardless of whether or not it has any effect. Thanks!
has title: In Keras, why must the loss function be computed based upon the output of the neural network?

http://stackoverflow.com/a/51268836
has body: You seem to permutate only the values of the dicts, so you could do something like from itertools import permutations dicts = [] keys = [1, 2, 3] for values in permutations(['A', 'B', 'C']): new_dict = dict(zip(keys, values)) dicts.append(new_dict)
answers question: http://stackoverflow.com/q/51268745
upvote count: 2
downvote count: 0
type: Answer
score: 2

http://stackoverflow.com/comment/89319323
score: 0
comment on: http://stackoverflow.com/q/51168095
type: Comment
type: QuestionComment
has text: Your **desired result** is inconsistent with your actual *desire* (provided that by "rows" you mean the 0-th index of the array). It looks more like you want to combine the 1-st index odd and even "columns" (or rather row-column combinations)? Is that right?

http://stackoverflow.com/a/51286749
has comment: http://stackoverflow.com/comment/129126098
has comment: http://stackoverflow.com/comment/138076871
has comment: http://stackoverflow.com/comment/106212859
has comment: http://stackoverflow.com/comment/129125981
accepted answer of: http://stackoverflow.com/q/51286748
has comment: http://stackoverflow.com/comment/137166290
answers question: http://stackoverflow.com/q/51286748
score: 242
has comment: http://stackoverflow.com/comment/107919967
upvote count: 242
type: AcceptedAnswer
downvote count: 0
has body: Much like you can add support to the JSON encoder for datetime objects or Decimals, you can also provide a custom encoder subclass to serialize dataclasses: import dataclasses, json class EnhancedJSONEncoder(json.JSONEncoder): def default(self, o): if dataclasses.is_dataclass(o): return dataclasses.asdict(o) return super().default(o) json.dumps(foo, cls=EnhancedJSONEncoder)
has comment: http://stackoverflow.com/comment/122502229
type: Answer
has comment: http://stackoverflow.com/comment/129125924
has comment: http://stackoverflow.com/comment/122502270
has comment: http://stackoverflow.com/comment/111202662
has comment: http://stackoverflow.com/comment/139228876

http://stackoverflow.com/q/51285593
has comment: http://stackoverflow.com/comment/89549711
has comment: http://stackoverflow.com/comment/89549349
has comment: http://stackoverflow.com/comment/89551107
has answer: http://stackoverflow.com/a/51287214
has title: Converting an image to grayscale using numpy
tagged with: numpy
tagged with: opencv
has answer: http://stackoverflow.com/a/51286918
possible better answer: http://stackoverflow.com/a/51286003
has comment: http://stackoverflow.com/comment/89550285
has answer: http://stackoverflow.com/a/51286003
has comment: http://stackoverflow.com/comment/89551368
has comment: http://stackoverflow.com/comment/89550668
upvote count: 4
has body: I have an image represented by a numpy.array matrix nxm of triples (r,g,b) and I want to convert it into grayscale, , using my own function. My attempts fail converting the matrix nxmx3 to a matrix of single values nxm, meaning that starting from an array [r,g,b] I get [gray, gray, gray] but I need gray. i.e. Initial colour channel : [150 246 98]. After converting to gray : [134 134 134]. What I need : 134 How can I achieve that? My code: def grayConversion(image): height, width, channel = image.shape for i in range(0, height): for j in range(0, width): blueComponent = image[i][j][0] greenComponent = image[i][j][1] redComponent = image[i][j][2] grayValue = 0.07 * blueComponent + 0.72 * greenComponent + 0.21 * redComponent image[i][j] = grayValue cv2.imshow("GrayScale",image) return image
type: AnsweredQuestion
tagged with: arrays
downvote count: 0
accepted answer: http://stackoverflow.com/a/51287214
has comment: http://stackoverflow.com/comment/89549046
favorite count: 0
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/89550331
score: 4
has comment: http://stackoverflow.com/comment/89549823
answer count: 3

http://stackoverflow.com/comment/89414367
has text: Is `Players` a list? The above code assumes it's a list. If not, you should adapt the code to make it indexable.
comment on: http://stackoverflow.com/a/51202566
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/51230516
answer count: 2
has answer: http://stackoverflow.com/a/51230558
favorite count: 0
accepted answer: http://stackoverflow.com/a/51230558
tagged with: python
score: 2
type: AnsweredQuestion
upvote count: 3
has title: How to remove row of array which row contain value more than 10
downvote count: 1
type: Question
has body: np.array([[ 0, 1, 2, 0, 4, 5, 6, 7, 8, 9], [ 0, 11, 0, 13, 0, 15, 0, 17, 18, 0]]) How to remove row of array above which row contain value more than 10?
has comment: http://stackoverflow.com/comment/89440417
possible better answer: http://stackoverflow.com/a/51230761
has answer: http://stackoverflow.com/a/51230761
tagged with: numpy

http://stackoverflow.com/comment/89515487
comment on: http://stackoverflow.com/a/51257538
type: Comment
has text: I'm sorry but I don't fully understand your question. So you'd like to create 3 copies of folder `b` under itself?
score: 0
type: AnswerComment

http://stackoverflow.com/q/51249744
type: AnsweredQuestion
tagged with: conv-neural-network
tagged with: max-pooling
tagged with: tensorflow
type: Question
has answer: http://stackoverflow.com/a/51250321
accepted answer: http://stackoverflow.com/a/51250321
tagged with: keras
has body: I am building a 1D Convolutional Neural Network (CNN). From many sources I have understood that performance of the CNN increases if more layers are added. However, at each pooling layer, my output shape is 50% smaller than my input (because I use a pool size of 2). This means that I cant add more layers, once my output has shape 1. Are there ways to overcome this 'decreasing shape problem' or is it just a matter of increasing my input shape?
score: 0
answer count: 1
has title: How can I overcome that my output shape decreases as I keep on Maxpooling per layer?
tagged with: python
has comment: http://stackoverflow.com/comment/89478409

http://stackoverflow.com/comment/89529598
type: Comment
has text: Doesn’t this assume the lists are in the same order? The comment above says they may not be.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/51275756

http://stackoverflow.com/comment/89581964
has text: My apologies, I feel stupid. After hours of switching codes between computers it was just a forgotten ")" at the end of the previous statement... Thanks for the help anyways!
comment on: http://stackoverflow.com/q/51279031
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89546306
type: QuestionComment
comment on: http://stackoverflow.com/q/51250674
has text: Thanks mate. Yeah, I have no idea what a .boto file is either :) Think it's AWS related so was barking up the wrong tree with that one. Cheers.
score: 0
type: Comment

http://stackoverflow.com/comment/135485818
has text: this should be the accepted answer https://stackoverflow.com/a/73038771/391034
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51215904

http://stackoverflow.com/a/51190618
score: 0
answers question: http://stackoverflow.com/q/51190326
has body: Each call to plot() simply adds another artist to the currently opened plot. If you want to save your plots separately, your loop should open a new plot, plot() the graph in it, save it, then close it for each row in the dataframe. Speaking of which - DataFrames have an iterrows method which will give you direct access to each row so that you don't have to locate by index on every iteration of the loop.
type: Answer

http://stackoverflow.com/a/51254358
answers question: http://stackoverflow.com/q/51254282
score: 0
has body: You can use Python's json module for this, or you could just munge the data yourself and turn it into a dict since it is practically one already. Then all you would need to do is loop over it like so: data = {"max_scale": "0", "min_scale": "0", "graph_label": "Light Level", "average": "1", "length_of_time": "3600", "upper_warn": "1000", "lower_warn": "30", "cached": 'false', "values": [{"value": 0.0, "time": 1531170219}, {"value": 0.0, "time": 1531170159}, {"value": 0.0, "time": 1531170099}, {"value": 0.0, "time": 1531170039}, {"value": 0.0, "time": 1531169979}, {"value": 0.0, "time": 1531169919}, {"value": 0.0, "time": 1531169859}, {"value": 0.0, "time": 1531169799}, {"value": 0.0, "time": 1531169739}, {"value": 0.0, "time": 1531169679}, {"value": 0.0, "time": 1531169619}, {"value": 0.0, "time": 1531166679}], "timestamp_to": "1531170222.798", "format_string": "%f Lux"} for item in data['values']: time, value = item['time'], item['value']
type: Answer

http://stackoverflow.com/q/51303321
tagged with: odroid
score: 11
tagged with: opencv
downvote count: 0
has body: i'm trying to take a video with webcam using opencv and python with a simple code import numpy as np import cv2 cap = cv2.VideoCapture(0) print('cap.isOpened') if cap.isOpened(): print ('cap is opened') while(True): re,img=cap.read() cv2.imshow("video output", img) k = cv2.waitKey(10)&amp;0xFF if k==27: break cap.release() cv2.destroyAllWindows() it's working fine if i try to play an existing video such as .mp4 file. but when i try using a webcam i got an error GStreamer-CRITICAL **: gst_element_get_state: assertion 'GST_IS_ELEMENT (element)' failed cap.isOpened for more information i'm using odroid xu4 with ubuntu 16.04, webcam i use logitech c170 ( it work properly in webcamtest and using guvcview) thought it doesn't workon cheese and camorama. need help about this please..
type: Question
has comment: http://stackoverflow.com/comment/89612773
has comment: http://stackoverflow.com/comment/89613566
upvote count: 11
tagged with: ubuntu
has comment: http://stackoverflow.com/comment/93792767
answer count: 1
favorite count: 0
tagged with: gstreamer
has answer: http://stackoverflow.com/a/53543167
type: UnansweredQuestion
has title: gstreamer critical error when trying to capture video using webcam python opencv
has comment: http://stackoverflow.com/comment/89585058
tagged with: python

http://stackoverflow.com/comment/89590959
comment on: http://stackoverflow.com/a/51305108
type: AnswerComment
has text: No, python 2.7 has -m too.
score: 0
type: Comment

http://stackoverflow.com/a/51255663
accepted answer of: http://stackoverflow.com/q/51255560
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 2
has body: With numpy, you can vectorize this by first finding the indices of elements that are in indList and then setting them to be zero. A = np.array([[1, 6, 6], [9, 7, 7], [10 ,2 ,2]]) A[np.where(np.isin(A, [10,1]))] = 0 This gives A = [[0 6 6] [9 7 7] [0 2 2]]
upvote count: 2
answers question: http://stackoverflow.com/q/51255560
has comment: http://stackoverflow.com/comment/89564709

http://stackoverflow.com/a/51307207
downvote count: 0
has comment: http://stackoverflow.com/comment/89609105
score: 3
has comment: http://stackoverflow.com/comment/94858548
type: Answer
answers question: http://stackoverflow.com/q/51300399
has comment: http://stackoverflow.com/comment/89610171
has comment: http://stackoverflow.com/comment/89609385
upvote count: 3
has body: Your log include the line: Can't connect to HTTPS URL because the SSL module is not available Try adding openssl to your requirements in your buildozer.spec file.
has comment: http://stackoverflow.com/comment/89610064

http://stackoverflow.com/a/51238721
accepted answer of: http://stackoverflow.com/q/51229547
answers question: http://stackoverflow.com/q/51229547
upvote count: 2
has comment: http://stackoverflow.com/comment/89458558
type: AcceptedAnswer
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/89456318
downvote count: 0
has body: I tried with Java and javascript everything is working fine. Hope for you it would also work. First get the webelement: WebElement we = driver.findelement(By.xpath("your xpath")) // make sure it should present on DOM, if it not them need to move scroll down or scroll up then again try to find the webElement. if you get the webelement then use below code: JavascriptExecutor jse = (JavascriptExecutor) driver; driver.executeScript("arguments[0].scrollIntoView(true);", we); For scroll down: jse.executeScript("window.scrollBy(0,document.body.scrollHeight || document.documentElement.scrollHeight)", ""); For scroll Up: jse.executeScript("window.scrollBy(0,-document.body.scrollHeight || -document.documentElement.scrollHeight)", ""); Height can be adjusted according to your need like: jse.executeScript("window.scrollBy(0,(-document.body.scrollHeight)/4 || -(document.documentElement.scrollHeight)/4)", "");

http://stackoverflow.com/comment/89548487
has text: @AntonvBR by printing the data and type I am getting 2014-07-30 00:00:00 <class 'datetime.datetime'>....isnt the format ='%Y-%m%-d %H:%M:%S' correct in this case?
score: 0
type: Comment
comment on: http://stackoverflow.com/q/51273823
type: QuestionComment

http://stackoverflow.com/a/51323569
type: Answer
accepted answer of: http://stackoverflow.com/q/51304429
answers question: http://stackoverflow.com/q/51304429
has body: After hours of research we finally did it, hopefully this will help someone to get along faster: We switched from the default Android NDK to CrystaX NDK 10 which has libpython2.7.so already compiled for each arch needed. Then we adjusted our Android.mk to look like this: LOCAL_PATH := $(call my-dir) CRYSTAX_PATH := /home/user/crystax-ndk-10.3.2 ... # Build libpyjni.so (pyjni.c may be an project source file you wrote) include $(CLEAR_VARS) LOCAL_MODULE := pyjni LOCAL_SRC_FILES := pyjni.c LOCAL_SHARED_LIBRARIES += python2.7 crystax LOCAL_LDLIBS += -llog include $(BUILD_SHARED_LIBRARY) # Include libpython2.7.so include $(CLEAR_VARS) LOCAL_MODULE := python2.7 LOCAL_SRC_FILES := $(CRYSTAX_PATH)/sources/python/2.7/libs/$(TARGET_ARCH_ABI)/libpython2.7.so LOCAL_SHARED_LIBRARIES := crystax LOCAL_EXPORT_CFLAGS := -I $(CRYSTAX_PATH)/sources/python/2.7/include/python/ include $(PREBUILT_SHARED_LIBRARY) # Include libcrystax.so (needed by python library) include $(CLEAR_VARS) LOCAL_MODULE := crystax LOCAL_SRC_FILES := $(NDK_PATH)/sources/crystax/libs/$(TARGET_ARCH_ABI)/libcrystax.so LOCAL_EXPORT_CFLAGS := -I $(NDK_PATH)/sources/crystax/include/ include $(PREBUILT_SHARED_LIBRARY) Afterwards we could build the project in Android Studio.
score: 0
type: AcceptedAnswer

http://stackoverflow.com/a/51195971
score: 0
has comment: http://stackoverflow.com/comment/89373755
has comment: http://stackoverflow.com/comment/89388590
type: Answer
answers question: http://stackoverflow.com/q/51194938
has body: From the link you posted: "The difference between basic and advanced integration is scale. Advanced integration can use all available cores for parallel processing of data sets at any size your computer can accommodate. Basic integration is limited to 2 cores and to data sets fitting in memory." So basic integration is similar using the open-source Python or R runtimes. Data Frames must fit in memory, and stuff runs single-threaded. The Advanced integration enables the full functionality of Microsoft Machine Learning Server. Microsoft Machine Learning Server includes a rich set of highly-scalable, distributed set of algorithms such as RevoscaleR, revoscalepy, and microsoftML that can work on data sizes larger than the size of physical memory, and run on a wide variety of platforms in a distributed manner https://learn.microsoft.com/en-us/machine-learning-server/what-is-machine-learning-server

http://stackoverflow.com/comment/89576603
type: Comment
type: QuestionComment
has text: yes i am using virtualenv but i installed postgres using homebrew on a mac
comment on: http://stackoverflow.com/q/51299780
score: 0

http://stackoverflow.com/comment/89431418
has text: it should be keys as rows and columns as values
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51225358

http://stackoverflow.com/comment/89395344
type: Comment
comment on: http://stackoverflow.com/a/51207176
type: AnswerComment
score: 0
has text: I tried that before - it didnt throw an error but didnt show up in pip list either

http://stackoverflow.com/q/51259374
has comment: http://stackoverflow.com/comment/89497155
linked to: http://stackoverflow.com/q/32015356
has comment: http://stackoverflow.com/comment/89497154
has title: Cut specific line of a text python
has comment: http://stackoverflow.com/comment/89497288
tagged with: string
score: 0
has comment: http://stackoverflow.com/comment/89497433
tagged with: python
has body: How can I cut specific text from a python file (around 150 000 000 lines)? I mean that program has to find one word and ending word and cut it what is between these lines. I was trying something like that: with bz2.BZ2File(file, 'r','utf-8') as f: for line in f: counter += 1 if line.strip() == ' Viriato da Cruz ': #or whatever title you need break elif counter > 1000: break print('bla') for line in f: counter += 1 if line.strip() == '</text>' : break print(line)
answer count: 0
type: UnansweredQuestion
type: Question

http://stackoverflow.com/comment/89601870
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51312396
has text: also we haven't learned about "seek" so i'm not able to use that.

http://stackoverflow.com/q/51289003
has comment: http://stackoverflow.com/comment/89555924
type: Question
accepted answer: http://stackoverflow.com/a/51289477
linked to: http://stackoverflow.com/q/624926
has comment: http://stackoverflow.com/comment/89555911
has title: Pass either a string or a value to use as a callback to get a value
answer count: 1
has comment: http://stackoverflow.com/comment/89556007
has comment: http://stackoverflow.com/comment/89555982
has comment: http://stackoverflow.com/comment/89555983
has comment: http://stackoverflow.com/comment/89555877
tagged with: python
has comment: http://stackoverflow.com/comment/89556050
has comment: http://stackoverflow.com/comment/89556003
type: AnsweredQuestion
has body: I'd like to call a function like this: c = selion([{'title': "mytitle1", 'my_field': 'value_1', 'other': 'other_value'}, {'title': "mytitle2", 'my_field': 'value_2', 'other': 'other_value'},]) The problem is that I would like 'my_field' to be sometimes a function to call back. How to test, in the selion() function, if it's a string or a function and call it back? if I want to pass in a function that is inside a class (something like self.calculate('client_x')), does it work out of the box like a normal function? All in all I'd like this code to work: class Test(): def calculate_value(self): return 'test' c = self.selion([{'title': "mytitle1", 'my_field': self.calculate_value, 'other': 'other_value'}, {'title': "mytitle2", 'my_field': 'value_2', 'other': 'other_value'},])
has answer: http://stackoverflow.com/a/51289477
has comment: http://stackoverflow.com/comment/89556117
score: 0

http://stackoverflow.com/comment/89389956
type: QuestionComment
has text: there is no token key, Yasin. I added the exact url to the description of the question, thank you. I tested identical notebooks with different notebook names in firefox and chrome side by side, and only chrome had this issue.
comment on: http://stackoverflow.com/q/51204250
score: 0
type: Comment

http://stackoverflow.com/q/51263807
has title: Python: Parse json data from a list with the same name
tagged with: parsing
has body: So I have the next json and I want to get just the github link and the twitter one without taking the foursquare and gravatar one. Also this in not all, sometimes the json data can change and if doesn't find a foursquare url, github will become first and twitter the second one. With the other ones (github or twitter) will be the same. How can I get the github and twitter url if they are not in the same position as in this json? { "socialProfiles": [ { "type": "foursquare", "typeId": "foursquare", "typeName": "Foursquare", "url": "https://foursquare.com/user/somerandomuser", "id": "554225246246" }, { "type": "github", "typeId": "github", "typeName": "Github", "url": "https://github.com/somerandomuser", "username": "somerandomuser" }, { "type": "gravatar", "typeId": "gravatar", "typeName": "Gravatar", "url": "https://gravatar.com/somerandomuser", "username": "somerandomuser", "id": "132341667" }, { "bio": " This is a bio of a random user", "followers": 543, "following": 222, "type": "twitter", "typeId": "twitter", "typeName": "Twitter", "url": "https://twitter.com/somerandomuser", "username": "somerandomuser", "id": "41414515335" } ] }
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/51263886
tagged with: http://stackoverflow.com/tag/json
accepted answer: http://stackoverflow.com/a/51263930
has answer: http://stackoverflow.com/a/51264016
has answer: http://stackoverflow.com/a/51263886
type: Question
score: 0
answer count: 3
tagged with: python
has answer: http://stackoverflow.com/a/51263930

http://stackoverflow.com/a/51251205
has comment: http://stackoverflow.com/comment/89481685
has body: That's mean that your cgi file script is considerate as a simple text file, so I guess your web server does'nt redirect the file content to python module to be handled and converted to the appropriate html. It may be because the web server is bad configured to use cgi.
has comment: http://stackoverflow.com/comment/89481502
downvote count: 1
score: -1
has comment: http://stackoverflow.com/comment/89481400
upvote count: 0
has comment: http://stackoverflow.com/comment/89481590
answers question: http://stackoverflow.com/q/51251095
has comment: http://stackoverflow.com/comment/89481637
has comment: http://stackoverflow.com/comment/89481287
type: Answer

http://stackoverflow.com/q/51265064
has title: How to send an email on a private telekom smtp?
has comment: http://stackoverflow.com/comment/89508120
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89509625
tagged with: python
has body: I want send an email automatically, but i get this error message: "Connection unexpectedly closed: [Errno 104] Connection reset by peer" I tried a few smtp server methode, but it can't work. My code is here: fromaddr = "test@gmail.com" toaddr = "test2@gmail.com" msg = MIMEMultipart() msg['From'] = fromaddr msg['To'] = toaddr msg['Subject'] = "test" body = "Test" msg.attach(MIMEText(body, 'plain')) #server = smtplib.SMTP('smtp.example.com', 25) server = smtplib.SMTP_SSL('mail.dt-one.com', 443) #server.connect("mail.t-online.hu",2525) server.ehlo() server.starttls() server.ehlo() server.login('myuser','mypassword') text = msg.as_string() server.sendmail(fromaddr, toaddr, text) server.quit()
answer count: 0
type: Question
has comment: http://stackoverflow.com/comment/89513439
has comment: http://stackoverflow.com/comment/89508201
tagged with: smtp
score: 0
tagged with: email

http://stackoverflow.com/q/51222085
type: Question
upvote count: 2
accepted answer: http://stackoverflow.com/a/51222284
has answer: http://stackoverflow.com/a/51222284
tagged with: pyqt
answer count: 1
favorite count: 0
tagged with: qgraphicsview
has title: Making a rectangle box behind text in python
has body: I am working on a text editor. The only problem left for me is to draw a rectangle box (colored with opacity 50%) behind a text that should be able to drag and drop with text anywhere as the text is working. Moreover, the text should always fit in that rectangle box. Thanks in advance. import os from PyQt5 import QtCore, QtGui, QtWidgets from PyQt5.QtGui import * from PyQt5.QtCore import * from PyQt5.QtWidgets import * from PIL import Image, ImageFont, ImageDraw, ImageEnhance class PhotoViewer(QtWidgets.QGraphicsView): photoClicked = QtCore.pyqtSignal(QtCore.QPoint) def __init__(self, parent): super(PhotoViewer, self).__init__(parent) self._zoom = 0 self._empty = True self._scene = QtWidgets.QGraphicsScene(self) self._photo = QtWidgets.QGraphicsPixmapItem() self._textLayer = QtWidgets.QGraphicsSimpleTextItem () #self._textLayer.setFont(QFont ()) self._scene.addItem(self._photo) self._scene.addItem(self._textLayer) self.setScene(self._scene) self.setTransformationAnchor(QtWidgets.QGraphicsView.AnchorUnderMouse) self.setResizeAnchor(QtWidgets.QGraphicsView.AnchorUnderMouse) self.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff) self.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff) self.setBackgroundBrush(QtGui.QBrush(QtGui.QColor(80, 30, 30))) self.setFrameShape(QtWidgets.QFrame.NoFrame) self._textLayer.setFlags(QGraphicsItem.ItemIsMovable) def hasPhoto(self): return not self._empty def fitInView(self, scale=True): rect = QtCore.QRectF(self._photo.pixmap().rect()) if not rect.isNull(): self.setSceneRect(rect) if self.hasPhoto(): unity = self.transform().mapRect(QtCore.QRectF(0, 0, 1, 1)) self.scale(1 / unity.width(), 1 / unity.height()) viewrect = self.viewport().rect() scenerect = self.transform().mapRect(rect) factor = min(viewrect.width() / scenerect.width(), viewrect.height() / scenerect.height()) self.scale(factor, factor) self._zoom = 0 def updateText(self,text,font_size=50): # Load the font: font_db = QFontDatabase() font_id = font_db.addApplic…
tagged with: python
tagged with: qgraphicssimpletextitem
type: AnsweredQuestion
score: 2
downvote count: 0
tagged with: pyqt5

http://stackoverflow.com/q/51292027
downvote count: 0
tagged with: scheduled-tasks
favorite count: 0
tagged with: python-asyncio
score: 20
has answer: http://stackoverflow.com/a/51294509
tagged with: python
type: AnsweredQuestion
has body: My program is supposed to run 24/7 and i want to be able to run some tasks at a certain hour/date. I have already tried to work with aiocron but it only supports scheduling functions (not coroutines) and i have read that is not a really good library. My program is built so most if not all the tasks that i would want to schedule are built in coroutines. Is there any other library that allows for such kind of task scheduling? Or if not, any way of warping coroutines so they run of a normal function?
type: Question
accepted answer: http://stackoverflow.com/a/51294509
upvote count: 20
has title: How to schedule a task in asyncio so it runs at a certain date?
answer count: 1

http://stackoverflow.com/a/51309001
type: Answer
has comment: http://stackoverflow.com/comment/89595373
accepted answer of: http://stackoverflow.com/q/51308827
answers question: http://stackoverflow.com/q/51308827
has body: You can create masks for your conditions and then apply them to your df with a negation since we are looking to delete the rows that meet the conditions. m1 = (df['SessionID'] == df['SessionID'].shift(-1)) m2 = (df['Event Action']=='Action') m3 = (df['Event Action'].shift(-1)=='Filter') m4 = (df['Timestamp']==df['Timestamp'].shift(-1)) df[~(m1 &amp; m2 &amp; m3 &amp; m4)] Output: SessionID Event Action Timestamp 0 S1 Action T1.1 1 S1 Action T1.2 2 S1 Filter T1.3 3 S2 Action T1.1 4 S2 Action T1.2 6 S2 Filter T1.3 7 S2 Filter T1.4 8 S3 Action T1.4 9 S3 Filter T1.5 11 S3 Filter T1.7 12 S3 Filter T1.8 13 S3 Action T1.9
score: 4
upvote count: 4
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/89595298

http://stackoverflow.com/comment/112521618
type: AnswerComment
has text: @Peter I see. Thanks!
comment on: http://stackoverflow.com/a/51245742
score: 0
type: Comment

http://stackoverflow.com/q/51226516
has title: override python arguments when packaging for debian
has body: I am trying to build a debian package of a python module. I have to pass some arguments to setup.py and to remove the --force option that is passed by default. I launch the build process by calling dpkg-buildpackage -us -uc To override the calls to python, I tried to add in debian/rules: override_dh_python2: dh_python2 --lapack-home=/usr But it doesn't change anything, my flag is not passed when compiling. What should I do to override python in the packaging process? Bests
tagged with: debian
favorite count: 0
answer count: 0
type: UnansweredQuestion
tagged with: package
upvote count: 1
tagged with: python
score: 1
type: Question
downvote count: 0

http://stackoverflow.com/comment/89533748
score: 0
type: Comment
type: QuestionComment
has text: What about a `pre_save` signal? That might be what you are looking for.
comment on: http://stackoverflow.com/q/51278016

http://stackoverflow.com/q/51305509
has title: casting Python str to C const char *
has comment: http://stackoverflow.com/comment/89589418
has answer: http://stackoverflow.com/a/51326182
has comment: http://stackoverflow.com/comment/89589561
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89625033
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89624432
score: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/89624888
type: Question
tagged with: swig
has answer: http://stackoverflow.com/a/51306590
has body: i just started some Python Wrapper for a C .dll. And used SWIG for it. I ran into the problem that a C Function from the dll takes a typedef of a const char * as argument. I Wrapped the .h of my C libary as following (the typedef is copied from the header to the interface when trying a lot of stuff to make it work, don't really know if that is necessary): Added: %include "cpointer.i" %pointer_class(signed char, p_char); %apply const char * { chararrayiwant }; //not sure if only should be char Old Code: %include "typemaps.i" %include "windows.i" %module somemodule %{ #include "someheader.h" typedef char chararrayiwant[33]; %} %include "someheader.h" typedef char chararrayiwant[33]; When i try to Execute it in my Python file like this: import mylib as d ... key = b"somereallylongserialkey" # type: str p = ctypes.c_char_p(key) x = d.myfunc(p, 1, None, None) i run into following error: x = d.myfunc(p, 1, None, None) TypeError: in method 'myfunc', argument 1 of type 'chararrayiwant const *' I tried this for 2 days now and have not found any solution to make it work.. Thanks in advance! P.S: does not work with the added lines
tagged with: http://stackoverflow.com/tag/c
upvote count: 3
answer count: 2

http://stackoverflow.com/comment/89553974
has text: Thank you so much for elaborating on bobrobbob's comment, this works precisely as I needed it to!
comment on: http://stackoverflow.com/a/51278540
type: Comment
type: AnswerComment
score: 0

http://stackoverflow.com/comment/89594977
type: Comment
type: QuestionComment
has text: are you asking about sys.args?
score: 1
comment on: http://stackoverflow.com/q/51308999

http://stackoverflow.com/a/51311679
type: Answer
answers question: http://stackoverflow.com/q/51199013
accepted answer of: http://stackoverflow.com/q/51199013
has body: I figure it out. Thank you everyone for your help. z, a , b, c = loadtxt('filename.txt',unpack=True, usecols=[0, 1, 2, 3]) Calculation: d = a*1.6 e = b*3.2 f = c*2.8 ave = (d + e + f)/3 h = z/ave Writing file: import csv zip(z, e, q1, f, ave, h) with open('outfile.txt', 'w') as f: writer = csv.writer(f, delimiter='\t') writer.writerows(zip(z, e, q1, f, ave, h))
type: AcceptedAnswer
score: 0

http://stackoverflow.com/q/51312012
accepted answer: http://stackoverflow.com/a/52753636
favorite count: 0
tagged with: python
possible better answer: http://stackoverflow.com/a/55860082
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/55860082
tagged with: tensorflow
type: Question
has comment: http://stackoverflow.com/comment/89600725
has title: read_data_sets is deprecated and will be removed in a future version. Instructions for updating
has body: This is my code import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("/tmp/data/", one_hot = True) and these are the warnings I am getting when I run it, I am using an online environment, Google Colab to run it WARNING:tensorflow:From &lt;ipython-input-2-0d6f173b16c0&gt;:6: read_data_sets (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version. Instructions for updating: Please use alternatives such as official/mnist/dataset.py from tensorflow/models. WARNING:tensorflow:From /usr/local/lib/python3.6/dist- packages/tensorflow/contrib/learn/python/learn/datasets/mnist.py:260: maybe_download (from tensorflow.contrib.learn.python.learn.datasets.base) is deprecated and will be removed in a future version. Instructions for updating: Please write your own downloading logic. WARNING:tensorflow:From /usr/local/lib/python3.6/dist- packages/tensorflow/contrib/learn/python/learn/datasets/base.py:252: _internal_retry.&lt;locals&gt;.wrap.&lt;locals&gt;.wrapped_fn (from tensorflow.contrib.learn.python.learn.datasets.base) is deprecated and will be removed in a future version. Instructions for updating: Please use urllib or similar directly. Successfully downloaded train-images-idx3-ubyte.gz 9912422 bytes. WARNING:tensorflow:From /usr/local/lib/python3.6/dist- packages/tensorflow/contrib/learn/python/learn/datasets/mnist.py:262: extract_images (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version. Instructions for updating: Please use tf.data to implement this functionality. Extracting /tmp/data/train-images-idx3-ubyte.gz Successfully downloaded train-labels-idx1-ubyte.gz 28881 bytes. WARNING:tensorflow:From /usr/local/lib/python3.6/dist- packages/tensorflow/contrib/learn/python/learn/datasets/mnist.py:267: extract_labels (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will…
tagged with: google-colaboratory
score: 4
has answer: http://stackoverflow.com/a/52753636
upvote count: 4
linked to: http://stackoverflow.com/q/51480927
answer count: 2
tagged with: deep-learning
has comment: http://stackoverflow.com/comment/89600822
downvote count: 0
has comment: http://stackoverflow.com/comment/98380933

http://stackoverflow.com/a/51174782
downvote count: 0
has comment: http://stackoverflow.com/comment/103671037
type: Answer
has comment: http://stackoverflow.com/comment/89332426
upvote count: 1
has comment: http://stackoverflow.com/comment/89333114
has comment: http://stackoverflow.com/comment/89332663
score: 1
has body: Any extra feature you compute from the input data is just another feature so: You feed it just like another feature of series, input_shape=(50, 1+extra_features) and you will have to concatenate those prior to passing to model. So yes, the input shape will now be (9950, 50, 2). Yes it is, you can pre-compute that feature let's say moving average and then concatenate it with the original input. You can also write custom layers to compute these features within the model, but the model would have compute it every time. If you compute it a priori, the advantage is you can save / cache it. If you have non-timeseries features, now you need to move onto the functional API and have multiple inputs: 1 which is timeseries and another which is not: series_in = Input(shape=(50, 2)) other_in = Input(shape(extra_features,)) # not a timeseries just a vector # An example graph lstm_out = LSTM(128)(series_in) merged = concatenate([lstm_out, other_in]) out = Dense(out_dim, activation='sigmoid')(merged) model = Model([series_in, other_in], out) model.compile(...) In this case we have 2 inputs to the model and can use the auxiliary features at any point. In the example, I merge before the final Dense layer to aid the predication along with the timeseries features extracted with the LSTM.
has comment: http://stackoverflow.com/comment/89333573
answers question: http://stackoverflow.com/q/51173801
has comment: http://stackoverflow.com/comment/103689527

http://stackoverflow.com/comment/89356521
has text: If you put `self.x = x` you are calling the setter that you wrote. If you put `self.__x = x` you are assiging to the attribute `self.__x` that the property `x` is wrapping.
score: 0
comment on: http://stackoverflow.com/q/51187318
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89588429
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51272328
type: AnswerComment
has text: I get your point. The problem is, the only operation I need to do is to append, that's it. I know it adds overhead @nosklo; what you are saying is related to my second question, does it worth it? What I have in my mind is to share sublists between let's say 4 different processes and each of the processes attach a single element (let say an integer 1) to each sublist. I guess it might be impossible, but I do not have the knowledge to confirm that.

http://stackoverflow.com/a/73610759
has comment: http://stackoverflow.com/comment/135708506
has comment: http://stackoverflow.com/comment/138116932
downvote count: 0
answers question: http://stackoverflow.com/q/51244223
score: 46
has comment: http://stackoverflow.com/comment/133964967
has comment: http://stackoverflow.com/comment/132809418
type: Answer
has comment: http://stackoverflow.com/comment/138036663
upvote count: 46
has body: If clicking the "Debug python file" doesn't pass the arguments then add "purpose": ["debug-in-terminal"] in the launch.json file {"version": "0.2.0", "configurations": [ { "name": "Python: Current File", "type": "python", "request": "launch", "program": "${file}", "console": "integratedTerminal", "justMyCode": true, "args": ["--experimentName", "Debugging"], "purpose": ["debug-in-terminal"] } ] }

http://stackoverflow.com/q/51225763
type: Question
tagged with: csrf
score: 0
answer count: 1
has body: I am attempting to log in to this website (https://isf.scout7.com/Apps/Login) to then scrape some data using Python and the requests library. In the past I have followed the instructions in Step 1 on this website (http://kazuar.github.io/scraping-tutorial/) which has always worked well for me. I believe to input the username and password, I should use login_form.login_model.username and login_form.login_model.password respectively. However with the website I'm trying to sign in to, I have been unable to find the CSRF token need to log in. I have gone through the html by inspecting the page using Chrome, but I can't find anything that resembles a CSRF token. Am I completely missing it, or do I not need it to log in?
has title: Unable to find CSRF token
tagged with: python
tagged with: python-requests
has answer: http://stackoverflow.com/a/51225878
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51225878

ibm-cloud-functions
tag name: ibm-cloud-functions
type: Tag
tags question: http://stackoverflow.com/q/51281626
tags question: http://stackoverflow.com/q/51184647

http://stackoverflow.com/comment/89481722
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51248527
has text: `coord_list` apparently is `ndarray` like in that it accepts lists and/or arrays as indices, including `np.array([])`. But a `list` does not accept that kind of indexing. The result of `where(...)[0]` does not work with a list, regardless of how many items it finds. `alist[np.array(0)]` works, but `alist[np.array([0])]` does not.
score: 0

http://stackoverflow.com/q/51181371
has title: Sentinel values with while loop
has body: The program I'm writing is to use a given formula to calculate financial assistance for families that loops back and asks the user if they want to do it for another family. Part of the instructs was also to use -1 as a sentinel value for the input. Here is what I have at the moment: def main(): cont = "y" while cont.lower() == "y": try: income = float(input("Please enter the annual household income:")) children = int(input("How many children live in the house?")) amountAssistance = assistanceTotal(income, children) print("For a household making", income, "per year with", children, " children the amount of assistance would be", amountAssistance) cont = input("Would you like to run this again? (Y/N)") except: print("Something went wrong.") print("Did you enter a whole number of children?") cont = input("Would you like to try again? (Y/N)") def assistanceTotal(money, kids): if (money &gt;= 30000 and money &lt;= 40000) and kids &gt;= 3: moneyTotal = 1000 * kids return moneyTotal if (money &gt;= 20000 and money &lt;= 30000) and kids &gt;= 2: moneyTotal = 1500 * kids return moneyTotal if money &lt; 20000: moneyTotal = 2000 * kids return moneyTotal main() I've tried looking up info on using sentinel values with loops like this but I haven't been able to quite grasp if how I'm thinking of using it is correct. For this type of a situation would I need one sentinel value or two, one for income and one for children? I think I would also need to alter my cont statements and change how it reacts if they type in a -1. Any help is appreciated even if it is just directing me to accurate info on how to use sentinels. Edit to add another sort of follow up question: Do sentinel values have to be numbers or are they most commonly numbers? What is the difference between having a continue portion using yes/no inputs to using sentinel values? For an example: In my text book it shows using a sentinel to stop the loop by asking for either an input of an integer or enter -1 to exit, is this …
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/51181420
favorite count: 0
tagged with: python-3.x
tagged with: while-loop
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/51181629
score: 1
upvote count: 1
tagged with: sentinel
type: Question

http://stackoverflow.com/q/51192310
has comment: http://stackoverflow.com/comment/89368900
tagged with: python
has comment: http://stackoverflow.com/comment/89368948
has comment: http://stackoverflow.com/comment/89368991
has comment: http://stackoverflow.com/comment/89368878
answer count: 0
has comment: http://stackoverflow.com/comment/89368918
has comment: http://stackoverflow.com/comment/89366182
type: Question
has title: Rand Index to compare two different labels' size
tagged with: cluster-analysis
has comment: http://stackoverflow.com/comment/89368999
score: 0
has comment: http://stackoverflow.com/comment/89368937
has body: I want to compare two partitions using Adjusted Rand Index. The first partition contains n clusters separated(no-overlap). The 2nd contains m clusters overlapped. When an element exists in 2 different clusters, I count it twice and give it two different indices. That cannot be applied to ARI. This illustration is intended to make the problem clearer : Let S and P be 2 partitions where : S={CLUSTER1, CLUSTER2} CLUSTER1={A,B} CLUSTER2={C} The indices'vector associated to S is : V1=[1,1,2] P={Group1, Group2, Group3} Group1={A} Group2={A,B} Group3={B,C} The indices'vector associated to P is : V1=[1,2,2,3,3] That of course won't work. Because beyond the problem of sizing, there is no order. Do you have ideas about this problems resolution ? I am thinking about testing S with P' and S with P" ... where P' is a partition that looks a bit like P but where there is no overlap. For example : P'=[{}, {A,B}, {C}]
has comment: http://stackoverflow.com/comment/89376905
has comment: http://stackoverflow.com/comment/89367144
type: UnansweredQuestion

http://stackoverflow.com/comment/139536137
score: 0
type: AnswerComment
type: Comment
has text: The answer was correct in not mentioning metaclasses, class objects, and `Type`. They're not relevant to the OP's question, which is a mere problem of an instance being a _subclass_ of a given type vs being that specific type. Every person is a mammal (and an animal) by inheritance, but they're still _humans_.
comment on: http://stackoverflow.com/a/51319372

http://stackoverflow.com/q/51323726
score: 0
has comment: http://stackoverflow.com/comment/89622861
answer count: 0
type: UnansweredQuestion
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/89622775
has comment: http://stackoverflow.com/comment/89622562
type: Question
has comment: http://stackoverflow.com/comment/89622963
has body: when i try that logic it show only last record of my file means all records are overriding in django. with open('persons.csv', 'wb') as csvfile: filewriter = csv.writer(csvfile, delimiter=',',quotechar='|', quoting=csv.QUOTE_MINIMAL) filewriter.writerow(['Name', name],) filewriter.writerow(['emailAddress', emailAddress]) filewriter.writerow(['password', NewcheckPassword])
has comment: http://stackoverflow.com/comment/89622591
has title: using that login i want to store some values like Name,emailAddress in other file

http://stackoverflow.com/q/51236787
has answer: http://stackoverflow.com/a/51237132
has title: Python MySQL-Connector: Error #2003
tagged with: mysql
tagged with: mysql-connector
type: Question
answer count: 1
tagged with: mysql-error-2003
score: 0
tagged with: python
tagged with: mysql-connector-python
has body: I'm making a PyGO-BOT, and going to make integration with MySQL. While connecting to the server, console gave me an error: Traceback (most recent call last): File "F:/PyCharm/projects/vkbot/pygo.py", line 153, in 2003: Can't connect to MySQL server on 'nesdevelopment.xyz:3306' (10061 Подключение не установлено, т.к. конечный компьютер отверг запрос на подключение) connection.close() AttributeError: 'NoneType' object has no attribute 'close' How to solve this problem?
type: UnansweredQuestion

http://stackoverflow.com/q/51227871
upvote count: 0
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/89436818
downvote count: 2
has body: I want to write a python script that is extracting certain conditions which is as follows: a a1 1 2 3 a2 0 1 b b1 1 2 b2 0 3 Until now what I was able to do is create a dictionary of first 2 columns and then create another dictionary for the 2nd and 3rd column. But I want all the 3 columns in one dictionary. Here is the pseudo code that I have written so far: mydict = {} for lines in f: if 'a' or 'b' in lines: key = a if 'a1' in lines: value = a1 mydict.setdefault(key, []).append(value) and something similar for the second dictionary as well. Please help me out ! expected output: { 'a' : [ 'a1': [1,2,3]],'b':['b1': [0,1]} As I mentioned earlier, I want to create this dictionary from 2 existent dictionaries which look something like this {'a': a1, 'b':b1} #First Dictionary {'a1': [1,2,3], 'b1': 123} #Second Dictionary I created these 2 dictionaries from a text file. And the code that is posted, is the code of how I extracted these 2 dictionaries.
has title: Python: Adding significant values to existing values in a dictionary
type: Question
has comment: http://stackoverflow.com/comment/89436023
has comment: http://stackoverflow.com/comment/89449125
score: -2
has answer: http://stackoverflow.com/a/51232511

http://stackoverflow.com/a/51310999
type: AcceptedAnswer
downvote count: 0
score: 4
accepted answer of: http://stackoverflow.com/q/51310599
type: Answer
answers question: http://stackoverflow.com/q/51310599
has comment: http://stackoverflow.com/comment/89598792
has comment: http://stackoverflow.com/comment/89622911
has body: from functools import reduce import operator def log(x): inters = reduce(operator.and_, [set(r) for r in x.str.split()]) if inters: return (' '.join(inters), len(inters)) return (x.iloc[0], 0) df.groupby('address').agg(log).company.apply(pd.Series).rename({0: 'company', 1: 'count'}, axis=1) company count address 1220 N Wendover Rd Charlotte NC 28211 Home Depot 2 123 Main Street Branchburg NJ 08853 Chipotle 1 2805 Whitson St Selma CA 93662 Wendys 0 If pandas 0.20 .rename(columns={0: 'company', 1: 'count'})
upvote count: 4
has comment: http://stackoverflow.com/comment/89598827

http://stackoverflow.com/comment/89394210
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51206553
has text: fix your indentation level, that will solve your problem
score: 0

http://stackoverflow.com/comment/89598043
type: AnswerComment
score: 0
has text: @Scott Computational complexity isn't everything; the constant plays a huge role in vectorized operations, so you need to provide an example closer to your actual use case if that isn't good enough.
type: Comment
comment on: http://stackoverflow.com/a/51310265

http://stackoverflow.com/q/51267790
upvote count: 3
answer count: 3
has body: How can I convert this to a Python Date so I can find the latest date in a list? ["2018-06-12","2018-06-13", ...] to date Then: max(date_objects) min(date_objects)
has answer: http://stackoverflow.com/a/51267855
tagged with: python
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89513895
has answer: http://stackoverflow.com/a/51267851
downvote count: 4
has comment: http://stackoverflow.com/comment/89514375
score: -1
linked to: http://stackoverflow.com/q/466345
has title: Find the earliest and oldest date in a list of dates' string representation
type: Question
has answer: http://stackoverflow.com/a/51267920

http://stackoverflow.com/comment/89403407
type: Comment
has text: More information about data_lactation: def data_lactation(self): for jour in range(1,125): Pu = ….. # several equations to calculate A prop and B prop Aprop = (max(x, 0)) Bprop = 1 – Aprop print("day =", jour,"then proportion of A = ", Aprop*100, "and proportion of B = ", Bprop*100) jour = jour + 1
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51210773

http://stackoverflow.com/comment/89531864
type: Comment
has text: BeautifulSoup isn't a HTML parser, it works with some python html parse libraries. It's a html dom utility. If you want to work with html is the fastest and easiest way.
comment on: http://stackoverflow.com/a/51276234
type: AnswerComment
score: 0

http://stackoverflow.com/comment/90927551
type: QuestionComment
type: Comment
has text: Is there even a way to avoid duplicate logging in debug mode?
comment on: http://stackoverflow.com/q/51318988
score: 0

http://stackoverflow.com/q/51295792
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51295817
score: 0
type: Question
has body: import socket, sys, string if len(sys.argv) !=4: print ("UsageL ./ninjabot.py &lt;server&gt; &lt;port&gt; &lt;channel&gt;") sys.exit(1) irc = sys.argv[1] port = int(sys.argv[2]) chan = sys.argv[3] sck = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sck.connect((irc, port)) sck.send(b'NICK ninjabot\r\n') sck.send(b'USER ninjabot ninjabot ninjabot :ninjabot Script\r\n') sck.send('JOIN ' + " " + chan + '\r\n') data = '' while True: data = sck.recv(1024) if data.find('PING') != -1: sck.send('PONG ' + data.split() [1] + '\r\n') print (data) print (data) I get this error in sck.send('JOIN ' + " " + chan + '\r\n') but when i try this: sck.send(b'JOIN ' + " " + chan + '\r\n') I get TypeError: can't concat str to bytes I know there's similar posts with this same issue, but none of those seem to help me.
accepted answer: http://stackoverflow.com/a/51295817
has title: Python TypeError with sockets
answer count: 1
tagged with: sockets
tagged with: python

http://stackoverflow.com/q/51248218
has answer: http://stackoverflow.com/a/51248288
linked to: http://stackoverflow.com/q/11041405
has answer: http://stackoverflow.com/a/51248296
answer count: 4
possible better answer: http://stackoverflow.com/a/51248288
has body: I would like to count part of speech tags. So far I have the part of speech tags (for German) stored in a dictionary, where the key the POS-tag is, and the value the number of occurrences is. When I count, I want to summarize 'NN' and 'NE' as one variable 'nouns_in_text', because both of them are nouns. I did this partially successfully. When I have an input-text in which I have both 'NN' and 'NE', in this case my code is working, and I get the correct result, meaning the sum of 'NN' and 'NE'. But the problem is, when I have an input text, which for example has only 'NN' and no 'NE', then I get a KeyError. I need the code to look if there are 'NN' or 'NE' in the input-text. If there are 'NN' and 'NE', then sum them up. If there is only 'NN' then return just the number of occurrences for 'NN', and the same if there is only 'NE'. In case there is neither 'NN' nor 'NE' return 0 or "None". I would like a Code, that would work for all three in the following described scenarios, without getting an Error. # First Scenario: NN and NE are in the Input-Text myInput = {'NN': 3, 'NE': 1, 'ART': 1, 'KON': 1} # Second Scenario: Only NN is in the Input-Text #myInput = {'NN': 3, 'ART': 1, 'KON': 1} # Third Scenario: Neither NN nor NE are in the Input-Text #myInput = {'ART': 1, 'KON': 1} def check_pos_tag(document): return document['NN'] + document['NE'] nouns_in_text = check_pos_tag(myInput) print(nouns_in_text) # Output = If NN and NE are in the input text I get 4 as result # But, if NN or NE are not in the input text I get a KeyError I think I could or should solve this problem with if-else conditions or with try-except blocks. But I'm not sure how to realize this ideas... Any suggestions? Thank you very much in advance! :-)
type: AnsweredQuestion
tagged with: try-except
has answer: http://stackoverflow.com/a/51248376
accepted answer: http://stackoverflow.com/a/51248296
type: Question
tagged with: count
tagged with: python
has answer: http://stackoverflow.com/a/51248355
tagged with: dictionary
tagged with: if-statement
score: 0
has title: Python Count Items in Dictionary

http://stackoverflow.com/comment/89370060
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51194171
has text: what is your expected output?

http://stackoverflow.com/a/51259917
score: 16
accepted answer of: http://stackoverflow.com/q/51244068
answers question: http://stackoverflow.com/q/51244068
has comment: http://stackoverflow.com/comment/118117712
type: AcceptedAnswer
upvote count: 16
type: Answer
has body: your query dict is in wrong format, please try this one: query = {"field_to_check_for": {"$exists": True}} cursor = db.collection-name.find(query)
downvote count: 0
has comment: http://stackoverflow.com/comment/96514655

http://stackoverflow.com/comment/89623495
type: AnswerComment
comment on: http://stackoverflow.com/a/51313205
score: 0
type: Comment
has text: This is what I was doing but what I want is to append whole dataframe without looping through each row i.e. `df.to_excel`

http://stackoverflow.com/comment/89574706
type: Comment
has text: Thanks for the reply. That's quite helpful. Just one issue: First two arguments are just pointers but not array pointers. Also when i tried to execute your code i code error: ret = func(usb_dev, dut_select, regs_in, regs_out, reg_enable) ValueError: Procedure called with not enough arguments (20 bytes missing) or wrong calling convention
comment on: http://stackoverflow.com/a/51293382
score: 0
type: AnswerComment

constraints
type: Tag
tags question: http://stackoverflow.com/q/51270715
tag name: constraints

http://stackoverflow.com/q/51168175
has comment: http://stackoverflow.com/comment/89321046
tagged with: python
has body: We decided to migrate our django 1.10.5 project with python 2.7.15 to a newer version of python and django. Now we are using python 3.7 and django 2. After some problems with our email sending script I found something strange. When sending automated mails we took text from a TextField in the database and inserted it into our Mail. content = content.replace('##ENTRY##', entry.text) The text field of entry is a django models.TextField. Now with python 37 it doesn't allow me to use it like that. I have to wrap the entry.text into a str() cast. But shouldn't the TextField be a string? content = content.replace('##ENTRY##', str(entry.text)) With that it works, but it lets my tummy hurt when doing it like that, since i don't understand why. Edit: def send_task_entry_new(entry): content = Email.load_email_template('tasks.watcher.info.entry.new') content = content.replace('##TAG##', entry.task.get_tag()) content = content.replace('##ENTRY##', entry.text) content = content.replace('##SUBJECT##', entry.task.get_subject()) subject = entry.task.get_tag() + " " + entry.task.get_subject() for watcher in entry.task.taskwatcher_set.all(): if watcher.user.last_login: content = content.replace('##LINK##', settings.BASE_URL + entry.task.get_absolute_url()) # If User has never logged in (Dummy for external task user) else: content = content.replace('##LINK##', settings.BASE_URL + reverse('tasks_public', args=[watcher.token])) Email.send(watcher.user.email, '', '', subject, content) Entry is an TaskEntry object which gets created as soon as I create a Task. The TaskEntry model looks like this. At least the attributes of a TaskEntry: task = models.ForeignKey(Task, null=True, on_delete=models.SET_NULL) creator = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True) external = models.EmailField(null=True, blank=True) text = models.TextField(verbose_name="Text") date_created = models.DateTimeField(auto_now_add=True) Edit Flow: Email comes in and get processed: text = get…
has comment: http://stackoverflow.com/comment/89321390
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89329284
has comment: http://stackoverflow.com/comment/89321773
accepted answer: http://stackoverflow.com/a/51239479
tagged with: django
upvote count: 1
type: Question
score: 1
has comment: http://stackoverflow.com/comment/89321110
has comment: http://stackoverflow.com/comment/89319690
downvote count: 0
answer count: 1
has title: Python37 and Django 2 TextField not a string?
has answer: http://stackoverflow.com/a/51239479
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89322483

http://stackoverflow.com/comment/89378903
type: Comment
has text: @BenG-TW I hope the edit is sufficient.
score: 0
comment on: http://stackoverflow.com/q/51198215
type: QuestionComment

http://stackoverflow.com/comment/89580849
has text: This can be resolved by making a [mcve] (try removing each part of the code to see if the problem persists, etc.)
comment on: http://stackoverflow.com/q/51301985
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89608991
type: Comment
has text: np.logical_and will not work well, if i'm having to deal with varying polygon shapes. is there a way to deal without trunking?
comment on: http://stackoverflow.com/a/51280095
score: 0
type: AnswerComment

http://stackoverflow.com/q/51229691
tagged with: nerdtree
has comment: http://stackoverflow.com/comment/89465995
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: python
has title: VIM create new file from nerdtree but then key mapping fail to work
tagged with: vim
answer count: 0
has comment: http://stackoverflow.com/comment/89465829
has body: I have got key mapping nnoremap &lt;buffer&gt; &lt;F9&gt; :exec '!python' shellescape(@%, 1)&lt;cr&gt; and when I press &lt;F9&gt; it can call up python to execute current file. I have NerdTree Plugin can copy a new file from m then c, rename the new file. Everything works fine besides function key, when I press &lt;F9&gt; nothing happened. But when I use !python filename.py then it will call up python to execute function again. May I ask why?
upvote count: 1
has comment: http://stackoverflow.com/comment/89452602
type: Question
has comment: http://stackoverflow.com/comment/89470183
score: 1

http://stackoverflow.com/comment/89476973
score: 0
comment on: http://stackoverflow.com/a/51240113
type: Comment
type: AnswerComment
has text: Excellent! Thank you. Call should be cv2.cvtColor (capital 'C').

http://stackoverflow.com/comment/131077625
type: QuestionComment
comment on: http://stackoverflow.com/q/51315148
score: 0
type: Comment
has text: Please don't vandalize your posts. By posting on the Stack Exchange network, you've granted a non-revocable right, under the [CC BY-SA 4.0 license](https://creativecommons.org/licenses/by-sa/4.0/), for Stack Exchange to distribute that content (i.e. regardless of your future choices). By Stack Exchange policy, the non-vandalized version of the post is the one which is distributed, and thus, any vandalism will be reverted. If you want to know more about deleting a post please see: [How does deleting work?](//meta.stackexchange.com/q/5221). You might be able to delete the post yourself as well.

http://stackoverflow.com/comment/89364854
type: Comment
has text: I just told you what are those two lines of code doing. Without knowing what your code is doing how can you expect it to work according to you. I am Still confused why are you removing those two lines of code.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/51191507

http://stackoverflow.com/comment/89467375
type: Comment
type: QuestionComment
has text: I got you, try `re.findall(r"\b\d{4}$\b(?<!2018)",str,re.MULTILINE)`
comment on: http://stackoverflow.com/q/51244034
score: 0

http://stackoverflow.com/q/51242015
has answer: http://stackoverflow.com/a/51242054
accepted answer: http://stackoverflow.com/a/51242054
favorite count: 0
tagged with: python
has body: The following situation currently appears quite often in my current work. I have a pandas DataFrame with a product-MultiIndex looking like this: cols = pd.MultiIndex.from_product([['foo1', 'foo2'], ['bar1', 'bar2']], names=['foo', 'bar']) df = pd.DataFrame(np.arange(5*4).reshape(5, 4), index=range(5), columns=cols) df foo foo1 foo2 bar bar1 bar2 bar1 bar2 0 0 1 2 3 1 4 5 6 7 2 8 9 10 11 3 12 13 14 15 4 16 17 18 19 Now I want to swap the column levels of the DataFrame, so I tried this: df.reorder_levels(['bar', 'foo'], axis=1) bar bar1 bar2 bar1 bar2 foo foo1 foo1 foo2 foo2 0 0 1 2 3 1 4 5 6 7 2 8 9 10 11 3 12 13 14 15 4 16 17 18 19 But this is not what I want. I want to the order of the columns to change according to this nice canonical product-ordering. My current workaround looks like this: cols_swapped = pd.MultiIndex.from_product([['bar1', 'bar2'], ['foo1', 'foo2']], names=['bar', 'foo']) df.reorder_levels(cols_swapped.names, axis=1).loc[:, cols_swapped]) bar bar1 bar2 foo foo1 foo2 foo1 foo2 0 0 2 1 3 1 4 6 5 7 2 8 10 9 11 3 12 14 13 15 4 16 18 17 19 This works, but is not so nice, e.g. because it is more confusing and a new MultiIndex has to be created. The situation, in which this often occurs to me, is that I compute a new feature for all of my columns. But after concatenating it to my df, it want to "sort" the corresponding new level into a new position. Say the new feature sits in level 0, then the workaround looks like this: new_order = [1, 2, 0, 3, 4] cols_swapped = pd.MultiIndex.from_product( [df.columns.levels[i] for i in new_order], names = [df.columns.names[i] for i in new_order] ) df_swap = df.reorder_levels(cols_swapped.names, axis=1).loc[:, cols_swapped] which is even less nice. Is this supported in pandas? If yes, what would be a more elegant way to do it?
type: AnsweredQuestion
score: 2
downvote count: 0
tagged with: multi-index
has comment: http://stackoverflow.com/comment/89462862
type: Question
upvote count: 2
tagged with: pandas
has title: Reorder levels in pandas from_product-MultiIndex DataFrame, coupled with values?
answer count: 1

http://stackoverflow.com/a/51270590
has body: Use whatever path is your csv file in linux! path = r'/home/x/python_test_files/test_file.csv' file = open(path, newline='') TestFileRaw = csv.reader(file) header = next(TestFileRaw) dataPC = [row for row in TestFileRaw]
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51270537

http://stackoverflow.com/comment/89325672
comment on: http://stackoverflow.com/q/51171428
type: Comment
score: 0
has text: You need something that to "return json object" - which you haven't included in the question. I could make something up - but wondered if there was something more specific than that you hadn't mentioned.
type: QuestionComment

http://stackoverflow.com/comment/89369099
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51193743
has text: You should at least show us what you have tried so far and how it failed. Hint: go through the list backwards.

http://stackoverflow.com/a/51275268
has body: You need to have some data and some headers in a post request. Try this: url = 'https://www.cashpoint.dk/index.php?r=games/oddsupdate' headers = { "X-Requested-With": "XMLHttpRequest", "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36", "Content-Type": "application/x-www-form-urlencoded", "Cookie": "_ga=GA1.2.517291307.1531264976; _gid=GA1.2.1421702183.1531264976; _pk_id.155.9810=7984b0a0e139caba.1531264979.1.1531264979.1531264979.; cookieConsent=1; cpLanguage=en; langid=2; ad_network=DIRECT; PHPSESSID=f4mbbfd8adb3m59gfc1pelo126" } data = "parameters%5Baction%5D=odds_update&amp;parameters%5Bgame_category%5D=live&amp;parameters%5Bsport_id%5D=&amp;parameters%5Btimestamp%5D=1531268162&amp;parameters%5Bgameids%5D=%5B905814%2C905813%2C905815%2C905818%2C905792%5D&amp;formToken=c3fed3ea6b46dae171a6f1a6d21db14fcc21474c" response = requests.post(url, data=data, headers=headers) print response.content Just tested this and it works. The point here is that ALL of this information can be found on the exact same xhr network inspection in google chrome. Next time, please read up on xmlhttprequests before you post a question.
type: Answer
accepted answer of: http://stackoverflow.com/q/51275134
score: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/89529713
type: AcceptedAnswer
downvote count: 1
answers question: http://stackoverflow.com/q/51275134

http://stackoverflow.com/comment/140144806
comment on: http://stackoverflow.com/a/79248153
score: 0
type: AnswerComment
has text: It helps when I try to debug in VS code with multiple args. Supplement docs for `{command:pickArgs}` in https://code.visualstudio.com/docs/python/debugging#_args. The default launch.json generated Python Debugger: Current File with Arguments using `"args": [ "${command:pickArgs}" ]` . I changed it to `"args": "{command:pickArgs}"`.
type: Comment

http://stackoverflow.com/a/51200854
answers question: http://stackoverflow.com/q/51200744
score: 2
accepted answer of: http://stackoverflow.com/q/51200744
has body: As I understand it, the problem is that you have to write a bunch of functions like this: def allAlpha(): for eachVar in alphaCbVars: eachVar.set(allAlphaVar.get()) def allBravo(): for eachVar in bravoCbVars: eachVar.set(allBravoVar.get()) … and so on. What you want is a function that takes the list of vars and the all-var as parameters: def allGroup(listOfVars, groupVar): for eachVar in listOfVars: eachVar.set(groupVar.get()) And now, you can use partial to create all of the individual partial functions: from functools import partial allAlphaCb = tk.Checkbutton(root, text='Alpha', variable=allAlphaCbVar, command=partial(allGroup, alphaCbVars, allAlphaVar) allBetaCb = tk.Checkbutton(root, text='Beta', variable=allBetaCbVar, command=partial(allGroup, betaCbVars, allBetaVar) However, you can reduce the duplication even further by writing a function that does all the stuff for building a group together in one place. It's hard to show that without more of your code to use, but it would look something like this: def makeGroup(name): # maybe some more params needed for the individual cbs allCbVars = [] allCbs = [] # some loop that generates the individual variables and checkboxes # and puts them in those lists cbVar = tk.IntVar() cb = tk.Checkbutton(root, text=name, variable=cbVar, command=partial(allGroup, allCbVars) return allCbVars, allCbs, cbVar, cb alphaCbVars, alphaCbs, allAlphaVar, allAlphaCb = makeGroup('Alpha') Or, alternatively, maybe just a function to group a bunch of cbs together: def groupify(name, cbVars): cbVar = tk.IntVar() cb = tk.Checkbutton(root, text=name, variable=cbVar, command=partial(allGroup, cbVars) return cbVar, cb # now build all your individual alpha cbs the same as in your current code alphaCbVar, alphaCb = groupify('Alpha', alphaCbVars) And maybe you don't even want to store alphaCbVars, betaCbVars, etc. as separate variables. Maybe it makes more sense to have a list of groups, or a dict mapping names to groups, or some kind of object with …
downvote count: 0
type: AcceptedAnswer
upvote count: 2
type: Answer

http://stackoverflow.com/q/51232600
has comment: http://stackoverflow.com/comment/89444772
answer count: 1
favorite count: 0
has title: How to run a python program in a loop with different arguments
tagged with: argparse
has comment: http://stackoverflow.com/comment/89444461
tagged with: python
linked to: http://stackoverflow.com/q/38219531
score: 2
has answer: http://stackoverflow.com/a/51232981
duplicate of: http://stackoverflow.com/q/38219531
type: UnansweredQuestion
upvote count: 3
downvote count: 1
has comment: http://stackoverflow.com/comment/89444308
linked to: http://stackoverflow.com/q/7974849
has body: I am using argparse to pass arguments on the command line, while executing the program. There is one argument that I need to change every time I run the program. I was thinking of storing all the instances of that particular argument in a list and write a program that executes my python program,say test.py taking one instance of that list every time it runs. python test.py --arg1 a1 --arg2 a2 List of instances of arg2 : [a2_1,a2_2,a2_3]. I want to automate the process, such that the following gets executed: python test.py --arg1 a1 --arg2 a2_1 followed by python test.py --arg1 a1 --arg2 a2_2 then python test.py --arg1 a1 --arg2 a2_3 automatically and I dont have to pass the next arguments manually every time one gets executed. Thanks a lot
type: Question

http://stackoverflow.com/a/51203995
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/89853028
has body: As I understood, this is what you expected. However, I renamed time names as time1 &amp; time2, otherwise it won't let to create the dictionary with same name. df = {'time1': [0.0,0.1,0.2,0.3,0.4], 'time2': [1.1,2.2,3.3,4.4,5.5],'b':[21,22,23,24,24]} su = {'time1':'sal', 'time2':'zulu', 'b':'m/s'} indexes = df[su.keys()[su.values().index('sal')]] df = pd.DataFrame(df, index=indexes, columns=['time1', 'time2', 'b']) print df
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/51201249

http://stackoverflow.com/comment/89481390
score: 1
has text: Sarcastic, yes, but I'm serious: Why CGI? This has enormous risks associated with it and makes your life far more difficult than it should be. Unless this is a purely academic experiment there's far better ways to achieve these goals.
comment on: http://stackoverflow.com/q/51251095
type: QuestionComment
type: Comment

http://stackoverflow.com/a/51187752
answers question: http://stackoverflow.com/q/51187553
downvote count: 1
has body: Your code works on my terminal: &gt;&gt;&gt; a = "input sub_clk ;" &gt;&gt;&gt; if ";" in a: ... a = a.replace(";", "]") ... &gt;&gt;&gt; a 'input sub_clk ]' &gt;&gt;&gt; Maybe there are some invisible characters in your string? At least, I cannot see any issue in your code. If you want to replace semicolon and remove the spaces before it, you can try do it like this: &gt;&gt;&gt; import re &gt;&gt;&gt; a = "input sub_clk ;" &gt;&gt;&gt; a = a.rstrip() &gt;&gt;&gt; a = re.sub("\\s*;$","]",a) &gt;&gt;&gt; a 'input sub_clk]'
type: AcceptedAnswer
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/89358099
accepted answer of: http://stackoverflow.com/q/51187553
upvote count: 1

http://stackoverflow.com/a/51312710
score: 1
has comment: http://stackoverflow.com/comment/89602244
upvote count: 1
has body: your file object is named csvfile but you're passing the csv module to DictWriter writer = csv.DictWriter(csv, fieldnames=fieldnames) should be writer = csv.DictWriter(csvfile, fieldnames=fieldnames) Also if you have a single dict you should use writerow - writerows is for when you have a iterable or list of multiple dicts to write: writer.writerows(ADSclassObj.authorDict) should be writer.writerow(ADSclassObj.authorDict)
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/51312690
has comment: http://stackoverflow.com/comment/89602319

http://stackoverflow.com/a/51196511
has comment: http://stackoverflow.com/comment/89375560
type: Answer
answers question: http://stackoverflow.com/q/51196166
upvote count: 2
has body: A slice of a memory mapped array creates another memory mapped array with the same underlying file, so you could create a new array that is the slice defined by the user input, and use the new array from then on. If a is the memory mapped array, define b = a[:, :, user_start:user_end] and then use b instead of repeatedly making the same slice of a. That is, instead of a[i, :, user_start:user_end], use b[i, :, :] (or b[i, :] or even just b[i], since the final : in a numpy index is optional).
score: 2
downvote count: 0

http://stackoverflow.com/comment/89351654
score: 0
type: Comment
type: QuestionComment
has text: Hi, in CPLEX_Studio128\python\examples\cp\visu you may find a few flowshop examples
comment on: http://stackoverflow.com/q/51183477

http://stackoverflow.com/q/51205948
tagged with: command-line-arguments
has body: I want to change the value that comes after -args option in the help message to "arg1 arg2 .." instead of "[arg [arg ...]]". I've tried changing the metavar value but it only changes the output to "[arg1 arg2 ... [arg1 arg2 ... ...]]". Here is my code:- arg_parser.add_argument('-args', action='store', default=None, nargs='*' ,dest='arg', help = "arguments passed to the program.") and the exact output is :- -args [arg [arg ...]] arguments passed to the program. the output that I want:- -args [arg1 arg2 ..] arguments passed to the program
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51207426
has title: How to change the metavar value for nargs=* in argparse?
favorite count: 0
tagged with: python-3.x
type: Question
tagged with: argparse
answer count: 2
tagged with: python
score: 0
possible better answer: http://stackoverflow.com/a/51218704
upvote count: 1
has answer: http://stackoverflow.com/a/51207426
has answer: http://stackoverflow.com/a/51218704
downvote count: 1

http://stackoverflow.com/q/51214022
tagged with: python
has comment: http://stackoverflow.com/comment/89409163
score: 4
has body: I successfully created a pyinstaller executable, but it refuses to open when I double click it. When I drag it into a terminal window, however, it works perfectly. This happens regardless of whether I import modules or not. How can I resolve this issue? I'm using pyinstaller 3.3.1, Python 2.7 and Ubuntu 18.04.
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89409055
upvote count: 4
downvote count: 0
has comment: http://stackoverflow.com/comment/89432235
favorite count: 0
has title: PyInstaller: Executable runs only in command line
type: Question
tagged with: pyinstaller

http://stackoverflow.com/q/51313002
type: AnsweredQuestion
has title: Python 3.7: Initialize objects with dataclasses module?
upvote count: 10
has body: Here is the my code in python 3.6 class A(object) def __init__(self, a: str): self._int_a: int = int(a) # desired composition def get_int_a(self) -&gt; int: return self._int_a I want to rewrite this code in python 3.7, how can i initialize self._int_a: int = int(a) with dataclasses module? I know that i can do something like that but i can't get how to initialize _a: int = int(a) or similar to that. from dataclasses import dataclass @dataclass class A(object): _a: int = int(a) # i want to get initialized `int` object here def get_int_a(self) -&gt; int: return self._a Thanks in advance for your ideas and suggestions.
type: Question
score: 9
tagged with: python-3.7
answer count: 1
tagged with: python
tagged with: python-dataclasses
favorite count: 0
linked to: http://stackoverflow.com/q/53376099
has answer: http://stackoverflow.com/a/51313184
downvote count: 1
accepted answer: http://stackoverflow.com/a/51313184

http://stackoverflow.com/comment/89337614
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51177423
has text: Edited my answer as suggested. Thanks.
score: 0

http://stackoverflow.com/q/51271812
tagged with: netcdf
has title: Python: KeyError: u'key' when analyzing multiple netCDF files
type: Question
has comment: http://stackoverflow.com/comment/89524378
upvote count: 1
answer count: 1
favorite count: 0
tagged with: keyerror
has comment: http://stackoverflow.com/comment/89538645
has comment: http://stackoverflow.com/comment/89522602
tagged with: python
type: AnsweredQuestion
has body: I'm relatively new to Python and am trying to analyze an entire folder of netCDF files. When I try to run my code I get the key error: u'satcode'. Here is my code: import netCDF4 as nc import glob import numpy as np filenames = [] for name in glob.glob("/Users/my_name/Desktop/ISCCP/*"): print name filenames.append(name) # below reads multiple files (file_list) f = nc.MFDataset(filenames) I know the error is with f = nc.MFDataset(filenames), but I don't know why. My traceback says: runfile('/Users/my_name/.spyder/West_Coast_Model.py', wdir='/Users/my_name/.spyder') /Users/my_name/Desktop/ISCCP/ISCCP-Basic.HGG.v01r00.GLOBAL.1983.07.01.0000.GPC.10KM.CS00.EA1.00 (5).nc /Users/my_name/Desktop/ISCCP/ISCCP-Basic.HGH.v01r00.GLOBAL.1983.07.99.0300.GPC.10KM.CS00.EA1.00.nc /Users/my_name/Desktop/ISCCP/ISCCP-Basic.HGH.v01r00.GLOBAL.1983.07.99.0600.GPC.10KM.CS00.EA1.00.nc /Users/my_name/Desktop/ISCCP/ISCCP-Basic.HGH.v01r00.GLOBAL.1983.07.99.0900.GPC.10KM.CS00.EA1.00.nc /Users/my_name/Desktop/ISCCP/ISCCP-Basic.HGH.v01r00.GLOBAL.1983.07.99.1200.GPC.10KM.CS00.EA1.00.nc /Users/my_name/Desktop/ISCCP/ISCCP-Basic.HGH.v01r00.GLOBAL.1983.07.99.1500.GPC.10KM.CS00.EA1.00.nc /Users/my_name/Desktop/ISCCP/ISCCP-Basic.HGH.v01r00.GLOBAL.1983.07.99.1800.GPC.10KM.CS00.EA1.00.nc /Users/my_name/Desktop/ISCCP/ISCCP-Basic.HGH.v01r00.GLOBAL.1983.07.99.2100.GPC.10KM.CS00.EA1.00.nc /Users/my_name/Desktop/ISCCP/ISCCP-Basic.HGH.v01r00.GLOBAL.1983.08.99.0000.GPC.10KM.CS00.EA1.00.nc Traceback (most recent call last): File "", line 1, in runfile('/Users/my_name/.spyder/West_Coast_Model.py', wdir='/Users/my_name/.spyder') File "/Users/my_name/anaconda2/lib/python2.7/site-packages/spyder/utils/site/sitecustomize.py", line 705, in runfile execfile(filename, namespace) File "/Users/my_name/anaconda2/lib/python2.7/site-packages/spyder/utils/site/sitecustomize.py", line 94, in execfile builtins.execfile(filename, *where) File "/Users/my_name/.spyder/West_Coast_Model.py", line 20, in f = MFDataset(filenames) File "…
has comment: http://stackoverflow.com/comment/89559203
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/51292114
accepted answer: http://stackoverflow.com/a/51292114

http://stackoverflow.com/comment/89383351
has text: It's extremely unclear what you're trying to accomplish here.
comment on: http://stackoverflow.com/q/51200849
type: Comment
type: QuestionComment
score: 2

http://stackoverflow.com/a/51263548
answers question: http://stackoverflow.com/q/51263436
score: 1
type: Answer
upvote count: 1
has body: def validate_input(q): res = None while not res: res = validate(raw_input(q)) return res a = validate_input('Enter a') b = validate_input('Enter b')
downvote count: 0

http://stackoverflow.com/comment/89427962
comment on: http://stackoverflow.com/q/51223320
score: 0
type: Comment
type: QuestionComment
has text: I also tried CUDA v9.0 and cuDNN 7.0.4 as well.... still doesn't work

http://stackoverflow.com/comment/89474156
type: AnswerComment
type: Comment
score: 0
comment on: http://stackoverflow.com/a/51246806
has text: @hyst329 I think you should rewritte your whole answer because it is a bit unclear.

http://stackoverflow.com/q/51254065
has answer: http://stackoverflow.com/a/59251375
has comment: http://stackoverflow.com/comment/89487208
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89487092
answer count: 5
score: 6
tagged with: python
has body: A recursive function that takes an integer and shuffles it. Shuffle one digit from the front and one digit from the back, then the second from the front and the second from the back, and so on until the shuffled number is the same as that original. For example, 123456 would print as 162534 or 130 would print as 103. Any help would be appreciated. On the string, it's easy, need the suggestion for integer. A = '130' def shuffle(A): if len(A) &lt;= 2: return A return (A[0] + A[-1]) + shuffle(A[1:-1]) Output: 103
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51254092
upvote count: 7
has comment: http://stackoverflow.com/comment/89487191
downvote count: 1
has answer: http://stackoverflow.com/a/60951676
has comment: http://stackoverflow.com/comment/89487233
type: Question
has comment: http://stackoverflow.com/comment/89487258
has comment: http://stackoverflow.com/comment/89487088
has title: Shuffle a integer using recursive function
possible better answer: http://stackoverflow.com/a/51254263
has comment: http://stackoverflow.com/comment/89487083
has answer: http://stackoverflow.com/a/55606861
has comment: http://stackoverflow.com/comment/89487309
has answer: http://stackoverflow.com/a/51254263
accepted answer: http://stackoverflow.com/a/51254092

http://stackoverflow.com/comment/89432006
comment on: http://stackoverflow.com/a/51222419
has text: One important part of this answer: when you launch the C program from the Python script, its output is not a tty, and so `printf()` will buffer up all of its output until a newline is written. That is, it's not necessarily a problem with the wiring on the Python side, the subprocess is probably not actually writing anything to its stdout, and adding the newlines in the printf calls will fix it.
type: AnswerComment
type: Comment
score: 1

http://stackoverflow.com/comment/89335422
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/51175813
type: Comment
has text: And speaking about ```var1 is var2``` - it is surely correct, but I guess it is not that Imapler expects (his function is surely expected to work with different variables, not the only one).

http://stackoverflow.com/q/51312408
type: AnsweredQuestion
has body: I think I'm doing some asynchronous like programming and I'm not sure how to approach this problem. I have a function X running on a new thread and a twisted tcp server on the main thread. I want to pass a message to the client when function X finishes its job. The code looks something like this: val = None def x(): global val #do something to val and send message to client that val is ready class Server(protocol.Protocol): def connectionMade(self): self.transport.write(b'REDPY*') def dataReceived(self, data): print("Packet: ",data) class EchoFactory(protocol.Factory): def buildProtocol(self, addr): print("new client") return Server() threading.Thread(target=x).start() endpoints.serverFromString(reactor, "tcp:1235").listen(EchoFactory()) reactor.run() I've looked into deferred in twisted and event handling, im not really sure what to use.
score: 0
answer count: 2
tagged with: twisted
has answer: http://stackoverflow.com/a/51315898
tagged with: python
has title: Monitor function completion and talk to client
has answer: http://stackoverflow.com/a/51326974
accepted answer: http://stackoverflow.com/a/51326974
possible better answer: http://stackoverflow.com/a/51315898
type: Question

http://stackoverflow.com/q/51236510
has comment: http://stackoverflow.com/comment/89452184
has answer: http://stackoverflow.com/a/51236631
accepted answer: http://stackoverflow.com/a/51236631
type: Question
tagged with: numpy
tagged with: arrays
linked to: http://stackoverflow.com/q/50959180
has comment: http://stackoverflow.com/comment/89452131
has body: I have a numpy array as follows array([[ 6, 5], [ 6, 9], [ 7, 5], [ 7, 9], [ 8, 10], [ 9, 10], [ 9, 11], [10, 10]]) I want to pick elements such that y coordinates are unique. If two y coordinates are same I want to pick element with lesser x coordinate. Expected output array([[ 6, 5], [ 6, 9], [ 8, 10], [ 9, 11]]) Explanation pick [6,5] over [7,5] pick [8,10] over [9,10] and [10,10] pick [9, 11] Thanks
has answer: http://stackoverflow.com/a/51236600
has comment: http://stackoverflow.com/comment/89452150
has comment: http://stackoverflow.com/comment/89452044
has answer: http://stackoverflow.com/a/51236630
answer count: 3
has comment: http://stackoverflow.com/comment/89452217
upvote count: 7
favorite count: 0
has comment: http://stackoverflow.com/comment/89452065
has comment: http://stackoverflow.com/comment/89452270
tagged with: python
has title: Numpy remove duplicate column values
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/51236630
downvote count: 0
has comment: http://stackoverflow.com/comment/89452205
score: 7

http://stackoverflow.com/comment/89549241
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51284405
has text: So the idea is to have some other text-like content in the dataframe as well?! In that case I suppose my answer to [this question](https://stackoverflow.com/questions/47038538/insert-matplotlib-images-into-a-pandas-dataframe) would solve your problem?
score: 0

frequency-distribution
tag name: frequency-distribution
type: Tag
tags question: http://stackoverflow.com/q/51280121
tags question: http://stackoverflow.com/q/51175871

http://stackoverflow.com/a/51255278
score: 2
has comment: http://stackoverflow.com/comment/89489699
has comment: http://stackoverflow.com/comment/89490567
has body: If you're trying to grab a list and append it to the end of a dataframe, why not initialize df_tmp with the data, like this: df_master = pd.DataFrame([]) for i in PI_tags: df_tmp = pd.DataFrame(ReadPiValues(i, interval, start_date, end_date)) df_master = df_master.append(df_tmp)
has comment: http://stackoverflow.com/comment/89489952
has comment: http://stackoverflow.com/comment/89489726
downvote count: 0
has comment: http://stackoverflow.com/comment/89489520
upvote count: 2
type: Answer
answers question: http://stackoverflow.com/q/51255249

http://stackoverflow.com/q/51168268
has comment: http://stackoverflow.com/comment/89423419
score: 0
has answer: http://stackoverflow.com/a/51221475
has title: Setting pixels values in OpenCV Python
answer count: 1
has comment: http://stackoverflow.com/comment/89319695
has comment: http://stackoverflow.com/comment/89457380
accepted answer: http://stackoverflow.com/a/51221475
tagged with: python
has comment: http://stackoverflow.com/comment/89319913
tagged with: opencv
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89319512
has comment: http://stackoverflow.com/comment/89319766
has body: How fast change pixels values? In C# what i need to do is only use GetPixel() to get pixel value and SetPixel() to change it (its pretty easy to use but slow, MarshallCopy and Lock/UnlockBits is much faster). In this code, i marking black pixels as 1 and white pixels as 0 import tkFileDialog import cv2 import numpy as np from matplotlib import pyplot as plt path = tkFileDialog.askopenfilename() bmp = cv2.imread(path) #reading image height, width, channels = bmp.shape if channels == 3: bmp = cv2.cvtColor(bmp, cv2.COLOR_BGR2GRAY) #if image have 3 channels, convert to BW bmp = bmp.astype('uint8') bmp = cv2.adaptiveThreshold(bmp,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,\ cv2.THRESH_BINARY,11,2) #Otsu thresholding imageData = np.asarray(bmp) #get pixels values pixelArray = [[0 for y in range(height)] for x in range(width)] #set size of array for pixels for y in range(len(imageData)): for x in range(len(imageData[0])): if imageData[y][x] == 0: pixelArray[y][x] = 1 #if black pixels = 1 else: pixelArray[y][x] = 0 #if white pixels = 0 In c#, it can looks like this: for (y = 0; y &lt; bmp.Height-1; y++) { for (x = 0; x &lt; bmp.Width-1; x++) { if (pixelArray[y, x] == 1) newImage.SetPixel(x, y, Color.Black); //printing new bitmap else newImage.SetPixel(x, y, Color.White); } } image2.Source = Bitmap2BitmapImage(newImage); In the next step i will marking countour pixels as "2", but now i want to ask you, how to set new image in python from my specific value and then, display it? For experimental purpose, i want to invert image (from B&amp;W to W&amp;B) only by byte valuse. Can you help me how to do it? EDIT1 I think i found a solution, but i have GREYSCALE image with one channel (i think thats how it works when i using cv2.cvtColor to convert 3 channels image to greyscale image). The function like this: im[np.where((im == [0,0,0]).all(axis = 2))] = [0,33,166] Could work pretty well, but how to make that function work with greyscale image? I want to set some black pixels (0) into White…
type: Question
has comment: http://stackoverflow.com/comment/89319756
has comment: http://stackoverflow.com/comment/89320467
linked to: http://stackoverflow.com/q/50580779
has comment: http://stackoverflow.com/comment/89320755

http://stackoverflow.com/comment/92388208
score: 5
comment on: http://stackoverflow.com/a/51289105
type: AnswerComment
has text: prefix_default_language should be set in the root urls.py, inside i18n_patterns, not settings.py or admin.py. LANGUAGE_CODE should be set in settings.py, not admin.py.
type: Comment

http://stackoverflow.com/comment/89413648
type: QuestionComment
has text: Can you also add your JSON? Errors suggest the problem might be there.
comment on: http://stackoverflow.com/q/51216219
score: 4
type: Comment

http://stackoverflow.com/a/51332745
has comment: http://stackoverflow.com/comment/89647502
answers question: http://stackoverflow.com/q/51323887
type: Answer
has comment: http://stackoverflow.com/comment/89647575
accepted answer of: http://stackoverflow.com/q/51323887
downvote count: 0
score: 1
has body: The simple solution to your problem is to create a new connection for each file. The code below does that. Sender from __future__ import print_function import socket HOST = 'localhost' PORT = 12345 BUFSIZE = 4096 def send_file(fname): with open(fname, 'rb') as f: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: sock.connect((HOST, PORT)) except socket.error as err: print(err, HOST, PORT) sock.close() return while True: data = f.read(BUFSIZE) if not data: break while data: sent = sock.send(data) data = data[sent:] sock.close() fnames = [ 'test0.jpg', 'test1.jpg', 'test2.jpg', 'test3.jpg', ] def main(): for fname in fnames: send_file(fname) if __name__ == '__main__': main() Receiver from __future__ import print_function import socket HOST = 'localhost' PORT = 12345 BUFSIZE = 4096 def main(): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) try: sock.bind((HOST, PORT)) except socket.error as err: print('Bind failed', err) return sock.listen(1) print('Socket now listening at', HOST, PORT) file_number = 0 try: while True: conn, addr = sock.accept() print('Connected with', *addr) fname = 'image%d.jpg' % file_number with open(fname, 'wb') as f: while True: data = conn.recv(BUFSIZE) if not data: break f.write(data) conn.close() print(fname, 'saved\n') file_number += 1 # Hit Break / Ctrl-C to exit except KeyboardInterrupt: print('\nClosing') sock.close() if __name__ == '__main__': main() You need to hit CtrlC or Break (depending on your OS) to exit the receiver. But using those numeric file names at the receiver isn't very satisfactory , so I decided to make it a little more complicated. :) In the following version we send the file name before the file data. That's slightly tricky because the receiver needs to separate the file name from the actual file data. If each socket.recv call corresponded to a socket.send call that would be easy, but that's not guaranteed to happen: the received bytes may…
has comment: http://stackoverflow.com/comment/92192116
upvote count: 1
type: AcceptedAnswer

http://stackoverflow.com/q/51297568
has body: I have a usecase where I have to create multiple sub dictionaries to split a nested dictionary upto 5 levels Lets assume that my dictionary looks like below. [{ person: [{ "id" : "abc", "name" : "xyz", "address" : {"co-ord" : "123", "place" : "world"}, "previous companies" :[{"comp1" : "name1"}, {"comp2":"name2"}] }] }] Now I need to create a list like [ person: { "id" : "abc", "name" : "xyz", } person_address:{ "id" : "abc", "co-ord" : "123", "place" : "world" } person_companies: { "id" : "abc", [{"comp1" : "name1"}, {"comp2":"name2"}] } ] Every sub directory needs to have a id field. I tried traversing the nested dict and extracting each value and adding the same to sub dictionary but i am not even close to the solution. Is there any better way to do this.
has title: Create multiple sub dictionaries from a nested dictionary
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/89572691
type: Question
has comment: http://stackoverflow.com/comment/89573237
has answer: http://stackoverflow.com/a/51298111
has answer: http://stackoverflow.com/a/51298276
has comment: http://stackoverflow.com/comment/89573067
has comment: http://stackoverflow.com/comment/89574758
has comment: http://stackoverflow.com/comment/89573094
score: 0
answer count: 3
has comment: http://stackoverflow.com/comment/89573194
has answer: http://stackoverflow.com/a/51321730
has comment: http://stackoverflow.com/comment/89572323
type: UnansweredQuestion

http://stackoverflow.com/a/79497292
has comment: http://stackoverflow.com/comment/140199646
type: Answer
upvote count: 0
has body: from PIL import Image # Load the uploaded image image_path = "/mnt/data/WhatsApp Image 2025-02-23 at 22.24.21_eed154c8.jpg" image = Image.open(image_path) # Display the original image image.show()
answers question: http://stackoverflow.com/q/51321960
score: -1
downvote count: 1

http://stackoverflow.com/a/73328286
upvote count: 1
answers question: http://stackoverflow.com/q/51211055
has body: I have needed to minimize the departure of a complex valued model function upon complex valued parameters, over a real domain. A toy example: def f(x, a, b): ab = complex(a,b); return np.exp(x*ab) And suppose that I have data DATA for x = np.arange(N). Note that x is real. What I did was this: def helper(x, a, b): return abs(f(x,a,b) - DATA[x]) and then I can use curve_fit(): curve_fit(helper, np.arange(N), np.zeros(N), p0 = [1,0]) What is happening is this: By subtracting the data from the model function, the new "ideal" output is all zeroes, which can be (must be) real in order for curve_fit() to work. The complex parameter ab = a + jb has been broken into its real and imaginary parts. The helper() function returns the absolute value of the difference between the model and the data. A critical issue is that curve_fit() doesn't evaluate any other x values than those you give it. Otherwise DATA[x] would fail. Note that by using abs() I'm achieving an L1 fit (more or less). One could just as well use abs()**2 to get an L2 fit ... but why one would use L1 or L2 is a topic for another day. You could fret, "suppose that the x[] aren't integers (but are real)?" which my code requires. Well, that's doable, simply by putting them into an array, and indexing that. There's probably some clever hack using a dictionary that would address this issue, too. Sorry about the code formatting; haven't figured out the markup yet.
downvote count: 0
type: Answer
score: 1

http://stackoverflow.com/q/51253315
upvote count: 3
type: Question
has comment: http://stackoverflow.com/comment/89485723
has comment: http://stackoverflow.com/comment/89486264
has title: Groupby-Transform over an empty data frame raises exception
has comment: http://stackoverflow.com/comment/89486112
tagged with: dataframe
has comment: http://stackoverflow.com/comment/89486521
has comment: http://stackoverflow.com/comment/89486590
has comment: http://stackoverflow.com/comment/89486471
tagged with: pandas-groupby
tagged with: pandas
accepted answer: http://stackoverflow.com/a/51253978
has body: Why does the following code raise an exception: # creates empty data frame with two columns my_df = pd.DataFrame([], columns=["a", "b"]) # groups by the values in column "a" and transforms the values in "b" to be the sum my_df.groupby("a")["b"].transform(lambda x: x.sum()) However this results in this error: ValueError: No objects to concatenate It works if my_df is not empty: list_of_numbers = [[0, 1], [0, 2], [1, 10]] my_df = pd.DataFrame(list_of_numbers, columns=["a", "b"]) my_df.groupby("a")["b"].transform(lambda x: x.sum()) 0 3 1 3 2 10 Name: b, dtype: int64 but my_df is coming from some other parts of the application so it can be empty. I'm using Pandas 0.20.3.
answer count: 1
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/89486350
has comment: http://stackoverflow.com/comment/89486463
has answer: http://stackoverflow.com/a/51253978
has comment: http://stackoverflow.com/comment/89485704
tagged with: python
has comment: http://stackoverflow.com/comment/89485961
has comment: http://stackoverflow.com/comment/89486177
type: AnsweredQuestion
score: 3

http://stackoverflow.com/a/51308817
type: Answer
has comment: http://stackoverflow.com/comment/89595914
answers question: http://stackoverflow.com/q/51307807
accepted answer of: http://stackoverflow.com/q/51307807
score: 1
upvote count: 1
type: AcceptedAnswer
downvote count: 0
has body: In Cart.new_or_get, here: if qs.count() == 1: # ... else: # ... return cart_obj, new_obj if a cart exists you do not return anything, so the function ends up returning None, which is indeed not iterable, so when trying to unpack the result in your view here: cart_obj, new_obj = Cart.objects.new_or_get(request) you get this exception. TL;DR: you should unindent the return statement so it executed for both branches. This being said, your Cart.new_or_get method is plain wrong - model code should not depend on the request, session etc. All this code should live either in your view (if that's the only place it's used) or as an utility function (or in an utility class acting as proxy over the model).

http://stackoverflow.com/q/51266268
has title: Exception thrown when running tf.app.run()
possible better answer: http://stackoverflow.com/a/53878561
linked to: http://stackoverflow.com/q/33703624
tagged with: python
has body: I am toying around with flags at the moment and came across some weird behavior when using tf.app.run(). The following code snippet should simply print the string given via the command line. import tensorflow as tf # command line flags tf.app.flags.DEFINE_string('mystring', 'Hello World!', '''String to print to console.''') FLAGS = tf.app.flags.FLAGS def main(): print(FLAGS.mystring) if __name__ == '__main__': tf.app.run() During execution, this error is thrown: Traceback (most recent call last): File "", line 1, in runfile('/path/flags.py', wdir='/path') File "/home/abc/anaconda3/envs/tensorflow/lib/python3.5/site-packages/spyder/utils/site/sitecustomize.py", line 710, in runfile execfile(filename, namespace) File "/home/abc/anaconda3/envs/tensorflow/lib/python3.5/site-packages/spyder/utils/site/sitecustomize.py", line 101, in execfile exec(compile(f.read(), filename, 'exec'), namespace) File "/path/flags.py", line 19, in tf.app.run() File "/home/abc/anaconda3/envs/tensorflow/lib/python3.5/site-packages/tensorflow/python/platform/app.py", line 126, in run _sys.exit(main(argv)) TypeError: main() takes 0 positional arguments but 1 was given ...which is strange because I do not give a single argument to main(). However, if I add an underscore def main(_):, it works without any errors. I couldn't find a doc where this is use of the underscore is described. Does anybody know what happens here? Thank you!
type: AnsweredQuestion
tagged with: flags
has answer: http://stackoverflow.com/a/51269497
tagged with: tensorflow
has answer: http://stackoverflow.com/a/53932204
type: Question
upvote count: 4
downvote count: 0
has comment: http://stackoverflow.com/comment/89511598
score: 4
favorite count: 0
answer count: 3
has answer: http://stackoverflow.com/a/53878561
accepted answer: http://stackoverflow.com/a/51269497
has comment: http://stackoverflow.com/comment/89511216
has comment: http://stackoverflow.com/comment/89510635

http://stackoverflow.com/comment/89374918
type: QuestionComment
comment on: http://stackoverflow.com/q/51195951
score: 0
type: Comment
has text: inneed kali is a Linux distribution

http://stackoverflow.com/q/51203670
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89388474
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89388588
has comment: http://stackoverflow.com/comment/89471517
downvote count: 1
type: Question
has body: I have installed visual studio code and code runner extension. I then have this piece of code: text: str = "slkdfjsd" I click CTRL-ALT-N and I get: text: str = "slkdfjsd" ^ SyntaxError: invalid syntax I like using types, and this program worked, it looks like its complaining about the types how can I have it understand that types are ok? more details: $ /usr/bin/env python3 --version Python 3.6.6 :: Anaconda, Inc. and when it's running it with: [Running] /usr/bin/env python3 "/home/myuser/dev/projects/python-snippets/text-summarization" File "/home/myuser/dev/projects/python-snippets/text-summarization", line 44 text: str = "slkdfjsd" ^ SyntaxError: invalid syntax Code runner plugin docs says: $pythonPath: The path of Python interpreter (set by Python: Select Interpreter command) but when I run print the path as comments suggested, I get a different version: sys.version_info(major=3, minor=5, micro=2, releaselevel='final', serial=0) which is different as you can see above from the &gt;python: select interpreter which I have chosen. Note also that when I run this code in visual studio code with run in terminal instead of CTRL-ALT-N then the python version chosen is 3.6 and it runs fine without any syntax error, so it I think it's something with the code runner not seeing the same python version that I see when selecting &gt;python: select interpreter Update: I see indeed that code-runner is using the wrong python interpreter as stated above, so I opened my user settings and tried to update python to point to the correct interpreter however it did not change anything it's still using the same wrong interpreter here is what I tried: { "git.autofetch": true, "terminal.integrated.rendererType": "dom", "code-runner.executorMap": { "javascript": "node", "java": "cd $dir &amp;&amp; javac $fileName &amp;&amp; java $fileNameWithoutExt", "c": "cd $dir &amp;&amp; gcc $fileName -o $fileNameWithoutExt &amp;&amp; $dir$fileNameWithoutExt", "cpp": "cd $dir &amp;&amp; g++ $fileName -…
has answer: http://stackoverflow.com/a/51203926
tagged with: visual-studio-code
upvote count: 9
has comment: http://stackoverflow.com/comment/89388509
has comment: http://stackoverflow.com/comment/89388714
has comment: http://stackoverflow.com/comment/89456954
has title: SyntaxError: invalid syntax with variable annotation
has comment: http://stackoverflow.com/comment/89593769
has comment: http://stackoverflow.com/comment/89443796
answer count: 1
accepted answer: http://stackoverflow.com/a/51203926
favorite count: 0
score: 8
has comment: http://stackoverflow.com/comment/89441823

http://stackoverflow.com/a/51173725
type: Answer
has comment: http://stackoverflow.com/comment/89330871
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51173659
score: 3
answers question: http://stackoverflow.com/q/51173659
has body: Use 2 dict comprehensions with select first and second value of tuple by indexing [0] and [1] with map: d = {'Czech Republic': (14.4212535, 50.0874654), 'Zimbabwe': (31.045686, -17.831773), 'Hungary': (19.0404707, 47.4983815), 'Nigeria': (7.4892974, 9.0643305)} df = pd.DataFrame({'COUNTRY':['Zimbabwe','Hungary', 'Slovakia']}) df['LAT'] = df['COUNTRY'].map({k:v[0] for k, v in d.items()}) df['LON'] = df['COUNTRY'].map({k:v[1] for k, v in d.items()}) print (df) COUNTRY LAT LON 0 Zimbabwe 31.045686 -17.831773 1 Hungary 19.040471 47.498382 2 Slovakia NaN NaN
type: AcceptedAnswer
upvote count: 3

http://stackoverflow.com/a/51211402
answers question: http://stackoverflow.com/q/51211261
type: Answer
upvote count: 1
has body: You've called the function def add_student(...) and the variable add_student = .... How is the interpreter supposed to know you want the function when the variable is called that? In fact, you've overwitten the function. By the time you call it, it no longer exists. Rename the variable or function to something else. I'll let the comments help you with certain other issues (global lists...) in your code.
type: AcceptedAnswer
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/51211261

http://stackoverflow.com/q/51170000
type: UnansweredQuestion
tagged with: python
has title: AttributeError: 'NoneType' object has no attribute 'content'
has body: I want to download a zip file using python, I am getting the while running following code import requests, zipfile, StringIO zip_file_url = "http://www.blog.pythonlibrary.org/wp-content/uploads/2012/06/wxDbViewer.zip" r = None try: r = requests.get(zip_file_url, stream=True) except requests.exceptions.ConnectionError: print "Connection refused" z = zipfile.ZipFile(StringIO.StringIO(r.content)) How should I declare "r"?
tagged with: python-requests
tagged with: global-variables
type: Question
score: 0
answer count: 1
tagged with: http://stackoverflow.com/tag/zip
tagged with: stringio
has answer: http://stackoverflow.com/a/51170375

http://stackoverflow.com/a/51223467
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51223174
has comment: http://stackoverflow.com/comment/89428574
has body: If I right understand you, you are locating a bunch of elements like this: elements = driver.find_elements_by_xpath("//a") it will give you a list of elements. Some of this elements are visible, some of them not. To prove it you can use this: for element in elements: print(element.is_displayed()) # prints true if displayed, otherwise false Try this code snippet: driver = webdriver.Chrome("C:\\path\\to\\chromedriver.exe") url = "https://stackoverflow.com/" driver.get(url) elements = driver.find_elements_by_xpath("//a") # finds all elements by given xPath for element in elements: # for every element in elements list print(element.is_displayed()) # print 'true' if displayed, or 'false' if not print("DONE") Output: False True False True True True True True True False False False False ... DONE NOTE: it is only an example, normally you have to wait until the page fully loads to locate all elements correctly and also get the correct state of them. EDIT: I have found a nice solution in this question and the sample code in this case would be like this: driver = webdriver.Chrome("C:\\path\\to\\chromedriver.exe") url = "https://stackoverflow.com/" driver.get(url) time.sleep(3) elements = driver.find_elements_by_xpath("//span") def element_in_viewport(driver, elem): elem_left_bound = elem.location.get('x') elem_top_bound = elem.location.get('y') elem_width = elem.size.get('width') elem_height = elem.size.get('height') elem_right_bound = elem_left_bound + elem_width elem_lower_bound = elem_top_bound + elem_height win_upper_bound = driver.execute_script('return window.pageYOffset') win_left_bound = driver.execute_script('return window.pageXOffset') win_width = driver.execute_script('return document.documentElement.clientWidth') win_height = driver.execute_script('return document.documentElement.clientHeight') win_right_bound = win_left_bound + win_width win_lower_bound = win_upper_bound + win_height return all((win_left_bound &lt;= elem_left_bound, win_right_bound &gt;= elem_rig…
downvote count: 0
has comment: http://stackoverflow.com/comment/89428258
upvote count: 2
type: Answer
has comment: http://stackoverflow.com/comment/89428389
score: 2
has comment: http://stackoverflow.com/comment/89428231
accepted answer of: http://stackoverflow.com/q/51223174

http://stackoverflow.com/q/51245432
type: UnansweredQuestion
has title: rolling window with 50% overlapping on window size in pandas
tagged with: python
score: 0
has answer: http://stackoverflow.com/a/53117502
has comment: http://stackoverflow.com/comment/89498331
has comment: http://stackoverflow.com/comment/89479090
type: Question
tagged with: numpy
tagged with: pandas
answer count: 1
has body: I have a data frame like this which is imported from a CSV. Data frame I would like to create a sliding window of size 256 with overlapping of 50%. For example, window1 should contain data from index 0-255, window2 should contain data from index 128-383 and so on until all the data is split in their respective windows. I am trying rolling.windows from pandas to create windows without any success. I want to achieve something like this. Overlapping windows How can I do that using the optimized methods included in Pandas or Numpy?
has comment: http://stackoverflow.com/comment/89469284
tagged with: data-analysis

http://stackoverflow.com/comment/89348141
comment on: http://stackoverflow.com/q/51182988
type: Comment
type: QuestionComment
score: 0
has text: Something like this: `df['Col1inCol2']=np.where(df.Col1.isin(df.Col2), 'True','False')`. do you want to account for NaNs as well?

http://stackoverflow.com/comment/89474226
comment on: http://stackoverflow.com/a/51224875
score: 0
type: AnswerComment
has text: Hello @jieter sorry for the late response. For some reason I got this error when using aggregation: `unsupported operand type(s) for +=: 'int' and 'NoneType' ` on the `self.column_total += total` line. But the footer is working great, exactly what I needed. Django-tables2 is awesome. Thanks for the help! Quick question: Is there a way to include the footer when exporting the table to an xlsx file?
type: Comment

sparse-matrix
tags question: http://stackoverflow.com/q/51287735
tag name: sparse-matrix
tags question: http://stackoverflow.com/q/51179290
tags question: http://stackoverflow.com/q/51305905
tags question: http://stackoverflow.com/q/51202024
tags question: http://stackoverflow.com/q/51175184
type: Tag
tags question: http://stackoverflow.com/q/51316161

http://stackoverflow.com/q/51219859
has body: I have this number which is a product of 2 prime numbers P and Q. Example p=5 q=7 prod = int(p)*int(q) #output: 35 and I have another set of numbers example: num = [5, 49, 10, 27] I Want to find the number of possible subsets that the product(P*Q) can have from the list of given numbers, example: These subsets are (5,49),(5,49,10),(5,49,27),(5,49,10,27), (49,10),(49,10,27). There are 6 subsets, and the output is 6.
has answer: http://stackoverflow.com/a/51220238
has answer: http://stackoverflow.com/a/51220459
answer count: 2
has title: How to find the number of subsets of a number with given list of numbers?
upvote count: 0
favorite count: 0
tagged with: python
tagged with: list
type: UnansweredQuestion
tagged with: multiplication
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/89420655
has comment: http://stackoverflow.com/comment/89420704
score: -1

http://stackoverflow.com/comment/89341373
type: Comment
type: QuestionComment
has text: In addition to naming your file `turtle.py`, you also did not import the module as such. You imported all functions, etc., but not the module. Therefore, `turtle.Pen(9999999)` must be `Pen(9999999)`.
score: 0
comment on: http://stackoverflow.com/q/51179446

http://stackoverflow.com/a/51305804
has body: That is a big file you are working with. If you need to process the data then you can't really get around the long read and write times.
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51305199

http://stackoverflow.com/a/51251978
answers question: http://stackoverflow.com/q/51251909
has comment: http://stackoverflow.com/comment/89483008
has body: You're generating the regex for each line with consume a lot of CPU, you should compile the regex at the beginning of the search instead that would save some cycles.
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/89483259
has comment: http://stackoverflow.com/comment/89484175

http://stackoverflow.com/q/51313593
has title: how to import a function from parent directory into test directory
downvote count: 0
tagged with: directory
has body: I am trying to import a function from the directory in the same project. how can i do that ? .|____project/ | |_____src/ | | |____myproject/ | | | | __init__.py | | | |____funtion.py | |_____test/ | | |___ testmyproject.py | | |____data/ | | |___testdata How can i import the the file function.py or the functions in the function.py file in my test/testmyproject.py to test the fucntions? i am not able to import the module from function.py
favorite count: 0
has comment: http://stackoverflow.com/comment/135194582
linked to: http://stackoverflow.com/q/30669474
tagged with: path
tagged with: python
has comment: http://stackoverflow.com/comment/89604565
answer count: 0
type: UnansweredQuestion
score: 1
tagged with: file
upvote count: 1
has comment: http://stackoverflow.com/comment/89603989
type: Question
tagged with: testing
linked to: http://stackoverflow.com/q/714063

http://stackoverflow.com/a/51237521
downvote count: 0
type: Answer
has body: The problem: If you look at the docs for imread, the function takes an integer flag called imreadmodes. This flag seems to accept information about resizing the image, rather than changing color spaces. The solution: I believe you are looking for the cv2.cvtColor function which uses a flag to determine the source and destination colorspaces. Both flags are simple integer enumerations. I assume the imread function is simply doing the best it can with the wrong type of flag. You probably want to do something like: BGRImage = cv2.imread(imageName) YCrCbImage = cv2.cvtColor(BGRImage, cv2.COLOR_BGR2YCR_CB)
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/51237354

http://stackoverflow.com/a/51212961
has comment: http://stackoverflow.com/comment/89442805
type: Answer
answers question: http://stackoverflow.com/q/51206567
score: 0
has body: In the search API, try -filter:safe

http://stackoverflow.com/comment/89605713
type: Comment
has text: This gives a weird Dataframe with lots of NaN values. I'm not sure what's happening, though
comment on: http://stackoverflow.com/q/51314292
score: 0
type: QuestionComment

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

http://stackoverflow.com/q/51230046
type: UnansweredQuestion
tagged with: sockets
tagged with: python
has title: Server- Server communication Python socket- OSError: [Errno 99] Cannot assign requested address
linked to: http://stackoverflow.com/q/47286678
answer count: 0
linked to: http://stackoverflow.com/q/48306528
type: Question
has comment: http://stackoverflow.com/comment/89447091
linked to: http://stackoverflow.com/q/6380057
score: 0
has comment: http://stackoverflow.com/comment/89440390
has comment: http://stackoverflow.com/comment/89440818
has body: I have tried to create a simple socket program where I can enable back and forth communication between two server sockets. The first iteration runs successfully and then there is one set of message passing that is possible. When it comes to second round of message passing I get the error. I feel there is some mistake in the IP Address but I could not resolve it. I have looked here but could not find a solution OSError: [Errno 99] Cannot assign requested address - py Python - socket.error: Cannot assign requested address Any help is deeply appreciated This is Server 1: import socket import requests host = "127.0.0.1" #ip address port_other_send = 5007 #Other's port while sending port_own_send = 5006 #Our port for sending port_other_recieve = 5009 #other port for recieving port_own_recieve = 5008 #our port for recieving #s = socket.socket() #s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) #s.bind(("", port_own)) #binds the socket element to the IP address and the Port def main(): send() def send(): s = socket.socket() s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind((host, port_own_send)) s.connect((host,port_other_recieve)) message = input("Type message to be sent ") while message != "q": s.send(message.encode('utf-8')) break receive() def receive(): print("This works yo") socketva = socket.socket() socketva.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) socketva.bind((host, port_own_recieve)) socketva.listen() c,addr=socketva.accept() x = True while x ==True: print("Connection from",(addr)) data = c.recv(1024) print ("Data recieved ", str(data)) response= ("Data recieved") c.send(data) x = False c.close send() if __name__ == "__main__": main() This is server 2: import socket import flask host = "127.0.0.1" #ip address port_other_send= 5006 #Other's port while sending port_own_send= 5007 #Our port for sending port_other_recieve = 5008 #other port for recieving port_own_recieve=5009 #our port for recieving #binds the socket element to the …
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89443873
has comment: http://stackoverflow.com/comment/89440493

http://stackoverflow.com/comment/89358517
has text: @Sraw : Thanks! Added update to the question.
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51170784

http://stackoverflow.com/q/51240866
has comment: http://stackoverflow.com/comment/89461525
tagged with: python
has title: read xlsx file with sheet named as None. pandas xlrd
type: UnansweredQuestion
tagged with: excel
type: Question
score: 0
has comment: http://stackoverflow.com/comment/89462646
tagged with: xlrd
tagged with: pandas
has body: I have a bunch of xlsx files with sheets named as None (empty string) When I trying to read the files using pandas, the xlrd raises a list index out of range error. Traceback (most recent call last): File "/usr/local/bin/runxlrd.py", line 332, in main ragged_rows=options.ragged_rows, File "/Library/Python/2.7/site-packages/xlrd/__init__.py", line 416, in open_workbook ragged_rows=ragged_rows, File "/Library/Python/2.7/site-packages/xlrd/xlsx.py", line 791, in open_workbook_2007_xml x12sheet.process_stream(zflo, heading) File "/Library/Python/2.7/site-packages/xlrd/xlsx.py", line 528, in own_process_stream self_do_row(elem) File "/Library/Python/2.7/site-packages/xlrd/xlsx.py", line 667, in do_row value = self.sst[int(tvalue)] IndexError: list index out of range I found this issue in xrld github that I think is related. If I change the name of the sheet, pandas successfully reads the file. I can't share the files as an example (privacy issue), and when I tried to create a demo file with None as the sheet name, the Excel raised an invalid name error. Packages version. pkg_resources.get_distribution("xlrd").version Out[3]: '1.1.0' pd.__version__ Out[4]: '0.23.0' Is there a way to read this file with pandas or a script (in any language) that can change the sheet names?
answer count: 1
has answer: http://stackoverflow.com/a/51242118

http://stackoverflow.com/comment/89419969
comment on: http://stackoverflow.com/q/51219293
score: 0
has text: Second: the error isn't telling you that you need to upgrade `pip` to a later version. There's a *recommendation* that "you should consider upgrading", then there's a completely separate error about not being able to find a distribution for `virtualenv`. This _could_ be because you have a truly ancient `pip`, but I don't think 6.1.1 is ancient enough for that to be the case. So, you may well be trying to fix an irrelevant problem.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51188015
type: Answer
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/89358696
has comment: http://stackoverflow.com/comment/89358562
has body: Using a simple iteration. Demo: mydict = {'HEALTH': {'NumberOfTimes': 2, 'Score': 12}, 'branch': {'NumberOfTimes': 4, 'Score': 34}, 'transfer': {'NumberOfTimes': 1, 'Score': 5}, 'deal': {'NumberOfTimes': 1, 'Score': 10}} newdict = {} for k, v in mydict.items(): newdict[k] = {"word": k, 'AvgScore': v['Score']/v['NumberOfTimes']} print(newdict.values()) Output: [{'word': 'transfer', 'AvgScore': 5}, {'word': 'HEALTH', 'AvgScore': 6}, {'word': 'branch', 'AvgScore': 8}, {'word': 'deal', 'AvgScore': 10}]
downvote count: 0
answers question: http://stackoverflow.com/q/51187967
has comment: http://stackoverflow.com/comment/89358107

http://stackoverflow.com/a/51236928
accepted answer of: http://stackoverflow.com/q/51236885
answers question: http://stackoverflow.com/q/51236885
upvote count: 5
type: Answer
downvote count: 0
has comment: http://stackoverflow.com/comment/89453631
score: 5
has comment: http://stackoverflow.com/comment/89479224
has body: It causes a memory leak. When you create an object, it starts off with a refcount of 1. The object only gets deleted if the refcount goes to 0. First example: When you pass your new object to a function that steals a reference (takes ownership), like PyTuple_SetItem, the refcount is not incremented, so it's still 1. When the tuple eventually gets destroyed and decrefs all of its elements, the count will drop to 0, so it'll be destroyed. All is good. Third example: When you pass your new object to a function that does not steal a reference (makes a new reference), like PySequence_SetItem, the refcount is incremented, so it's 2. When the tuple eventually gets destroyed and decrefs all of its elements, the count will drop to 1, so it won't be destroyed. And, since nobody else has a reference to it anymore (unless you stored it somewhere), there's no way anyone can ever decref it. So it's leaked. Second example: When you pass your new object to a function that does not steal a reference (makes a new reference), like PySequence_SetItem, but then call Py_DECREF on it, the refcount is incremented to 2 and decremented back to 1. So, when the tuple eventually gets destroyed and decrefs all of its elements, the count will drop to 0. All is good again. If you're wondering why Python would both with any non-stealing functions, you just need to think of a less trivial case. What if you wanted to put the item in two tuples instead of one? Or if you wanted to put it in a tuple, but also store it in a C static pointer, or in some module's globals, or somewhere else? You want the reference count to be bumped up by 2 if you want to store it in two places, and them dropped back down by 1 when your local variable goes away. For the really simple case where you're just creating something and immediately handing it off, reference-stealing functions let you avoid that one-incref-and-one-decref, as well as being nice and convenient for one-lines. But for anything more complicated, that doe…
type: AcceptedAnswer

http://stackoverflow.com/comment/89536747
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51279537
has text: @Vidhya can you elaborate little more so i can help with
type: Comment

http://stackoverflow.com/q/51297972
has body: I have a severe space limitation on my deployment device that mean I cannot fit the entire "Keras" package. Is there a way to get a prediction from a trained keras model without the entire keras package? I have noted that the Keras docker is ~1GB. I would need it to be &lt; 650MB
type: Question
downvote count: 0
answer count: 1
tagged with: keras
has comment: http://stackoverflow.com/comment/89573281
favorite count: 0
linked to: http://stackoverflow.com/q/36720498
tagged with: python
upvote count: 3
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89573657
has comment: http://stackoverflow.com/comment/89573048
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/89573324
score: 3
has title: "Mini Keras" Is there a way get a prediction form a trained keras model without the entire keras package?
has comment: http://stackoverflow.com/comment/89573462
has answer: http://stackoverflow.com/a/51536067

http://stackoverflow.com/comment/89513863
comment on: http://stackoverflow.com/q/51208669
score: 0
type: Comment
type: QuestionComment
has text: You should definitely use other names for instances of classes than the class name itself. I refer to `MainWindow = MainWindow()`. Here you do something very weird. In the current namespace you overwrite the definition of the class with an instance of this class. Better do something like `main = MainWindow()`.

http://stackoverflow.com/q/51304738
has answer: http://stackoverflow.com/a/51305805
accepted answer: http://stackoverflow.com/a/51305805
tagged with: pandas
upvote count: 1
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/89586219
tagged with: python
tagged with: dictionary
type: AnsweredQuestion
downvote count: 0
score: 1
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/89586693
type: Question
has body: I am a bit new to Python programming. I have a small requirement where in I need to list down all customers and their amounts for a given fortnight in a JSON format. Currently, I have a dataframe this way: FortNight Amount Customer Parameter Apr-2FN-2018 339632.00 10992 CustomerSales Apr-2FN-2018 27282.00 10994 CustomerSales Apr-2FN-2018 26353.00 10995 CustomerSales Apr-2FN-2018 24797.00 11000 CustomerSales Apr-2FN-2018 21093.00 10990 CustomerSales Expected JSON: "CustomerSales" : [ {"FortNight" : "Apr-2FN-2018", "Details" :[ {"Customer": "10992","Amount" : 339632.00}, {"Customer": "10994","Amount" : 27282.00}, {"Customer": "10995","Amount" : 26353.00}, {"Customer": "11000","Amount" : 24797.00}, {"Customer": "10990","Amount" : 21093.00} ] } ] I tried: dict(df.set_index('Parameter').groupby(level=0).apply(lambda x : ast.literal_eval(x.to_json(orient = 'records', date_format = "iso")))) It retrieves this: [{'CustomerSales': [{'Customer': '10992', 'Amount': 339632.00, 'FortNight': 'Apr-2FN-2018'}, {'Customer': '10994', 'Amount': 27282.00, 'FortNight': 'Apr-2FN-2018'},{'Customer': '10995', 'Amount': 26353.00, 'FortNight': 'Apr-2FN-2018'}, {'Customer': '11000', 'Amount': 24797.00, 'FortNight': 'Apr-2FN-2018'}, {'Customer': '10990', 'Amount': 21093.00, 'FortNight': 'Apr-2FN-2018'}]}] I tried other ways too but in vain. Any help is welcome. Thanks in advance!
has title: Convert dataframe to JSON with 2 level nested array

http://stackoverflow.com/q/51312923
tagged with: pyqtgraph
type: AnsweredQuestion
score: 3
upvote count: 3
tagged with: scipy
tagged with: signal-processing
accepted answer: http://stackoverflow.com/a/51439437
type: Question
tagged with: spectrogram
has comment: http://stackoverflow.com/comment/89610403
answer count: 1
downvote count: 0
has title: plotting the spectrum of a wavfile in pyqtgraph using scipy.signal.spectrogram
favorite count: 0
has answer: http://stackoverflow.com/a/51439437
tagged with: python
has body: I have a PyQt plus pyqtgraph program for music and speech analysis and I want to plot the spectrum of a wav file (calculated using scipy python package). I can do it in matplotlib but due to matplotlib's performance I need to switch to pyqtgraph but I cant find any consistent method to plot the output of scipy.signal.spectrogram in to pyqtgraph Thanks!

http://stackoverflow.com/comment/89591606
score: 1
type: Comment
type: QuestionComment
has text: Also note that one should not pop() items from a sequence while iterating over said sequence.
comment on: http://stackoverflow.com/q/51293558

http://stackoverflow.com/comment/89459000
type: QuestionComment
comment on: http://stackoverflow.com/q/51239428
has text: Also if i set uuid=false, django creates an id field with primary_key=true in migration file. But i dont need an id field.
score: 0
type: Comment

win32gui
type: Tag
tag name: win32gui
tags question: http://stackoverflow.com/q/51287338

http://stackoverflow.com/comment/89551675
comment on: http://stackoverflow.com/q/51286702
score: 0
type: Comment
type: QuestionComment
has text: This is what is printed : donald trump - Αναζήτηση Google

http://stackoverflow.com/q/51199759
type: Question
tagged with: python
has body: I'm trying to perform a cross tab query on a Pandas data frame. It looks something like this: | Category | Score1 | Score2 | Score3 | Score4 | 1 | 2 | 3 | 5 | 12 | 1 | 3 | 4 | 2 | 5 | 2 | 1 | 6 | 8 | 6 I want to create a cross tab query that get's me something like this, with category as a column and the scores as rows: Category| 1 | 2 | 3 | Score 1 | | | | Score 2 | | | | Score 3 | | | | The values in the blank spaces will be the averages for each category for each score. The existing data file is a csv that is read into a Pandas DataFrame. I looked at the pd.crosstab() function, but I can't seem to tie it in to the dataframe. Also it has a parameter for aggfunc, which I set (using numpy) aggfunc=np.average, however I can't figure out the value parameter. I'm I missing something, or should I be using Pandas at all for this?
has title: Pandas crosstab averages
upvote count: 1
answer count: 1
tagged with: numpy
has answer: http://stackoverflow.com/a/51199963
accepted answer: http://stackoverflow.com/a/51199963
tagged with: pandas
type: AnsweredQuestion
tagged with: crosstab
downvote count: 0
score: 1
favorite count: 0

http://stackoverflow.com/q/51269242
tagged with: regex
possible better answer: http://stackoverflow.com/a/51269287
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51269329
has answer: http://stackoverflow.com/a/51269287
accepted answer: http://stackoverflow.com/a/51269329
type: Question
has body: Using Python 2.6.6, I'm trying to format each element in a list using regex. Example of elements in an array: test1;apple;-fgnsldfgsbfdgb test2;watermelon;-iwerunvfgkjsfg test3;orange;wervxddgjbdhnf I'd like to format the text to just grab what is in between the semicolons ; apple watermelon orange The regex to capture that is the following: (?&lt;=\;)(.*?)(?=\;) I tried different variations of the following code: for member in fruits: parseFruit = re.compile(member) member = member.sub( (\.),((?&lt;=\;)(.*?)(?=\;)) ) print("Fruit: ", member) Nothing seems to work...
tagged with: arrays
has answer: http://stackoverflow.com/a/51269547
score: 0
answer count: 3
has title: Python formatting elements in an array with regex
tagged with: scripting
tagged with: python

http://stackoverflow.com/comment/89489180
has text: Is there a benefit in using the zip version vs. the timedelta version>
type: AnswerComment
comment on: http://stackoverflow.com/a/51254708
score: 0
type: Comment

http://stackoverflow.com/comment/89578733
comment on: http://stackoverflow.com/a/51300422
type: Comment
has text: row0: stats.percentileofscore([4,7,6], 4)); row1: stats.percentileofscore([4,7,6], 7)); row3: stats.percentileofscore([4,7,6], 6)). The [score] should be one scale value from the 'Value' column for that row.
type: AnswerComment
score: 0

http://stackoverflow.com/comment/89570825
type: Comment
comment on: http://stackoverflow.com/a/51295353
score: 0
type: AnswerComment
has text: @M Hossain, I edited my code. Please try it again and let me know if it works. I basically converted float to string at 1st step.

http://stackoverflow.com/comment/89524504
score: 1
type: AnswerComment
has text: The reduceat solution is perfect. I've found a way to do the slicing one without temp arrays though.
type: Comment
comment on: http://stackoverflow.com/a/51273114

http://stackoverflow.com/comment/89446387
type: Comment
type: QuestionComment
has text: Do you only want to open the link when a specific key is pressed or do you want to open it when any key is pressed?
score: 0
comment on: http://stackoverflow.com/q/51233057

http://stackoverflow.com/comment/89459616
score: 0
type: Comment
has text: if you want to return as a json, use `json.dumps(result_list)`.
type: AnswerComment
comment on: http://stackoverflow.com/a/51240412

http://stackoverflow.com/comment/89449272
has text: @DanielMiller I don't get why you want this but I added something shorter
type: Comment
comment on: http://stackoverflow.com/a/51234952
score: 0
type: AnswerComment

http://stackoverflow.com/q/51300833
tagged with: oop
score: -1
answer count: 2
downvote count: 2
upvote count: 1
has comment: http://stackoverflow.com/comment/89579071
has answer: http://stackoverflow.com/a/51301351
accepted answer: http://stackoverflow.com/a/51301351
favorite count: 0
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/51300888
has answer: http://stackoverflow.com/a/51300888
has title: Method to change class variable in python 3
tagged with: python
has comment: http://stackoverflow.com/comment/89578626
has comment: http://stackoverflow.com/comment/89578884
has comment: http://stackoverflow.com/comment/89579809
has comment: http://stackoverflow.com/comment/89579355
has body: I'm trying to change class variable with a method: class Test(): someVar = 0 def __init__(self, val1): self.val1 = val1 def changeVar(self): Test.someVar = self.val1**2 val = 2 var1 = Test(val) print(var1.someVar) However, I get the "0" as the output. Somehow I have an error in reasoning.
has comment: http://stackoverflow.com/comment/89578611
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89578832

http://stackoverflow.com/comment/89341501
comment on: http://stackoverflow.com/a/51179433
type: AnswerComment
score: 0
type: Comment
has text: Or maybe `image_tags` is empty

http://stackoverflow.com/a/51217046
has comment: http://stackoverflow.com/comment/89415366
score: 0
answers question: http://stackoverflow.com/q/51217028
has comment: http://stackoverflow.com/comment/89415336
type: Answer
has comment: http://stackoverflow.com/comment/89415643
has comment: http://stackoverflow.com/comment/89415360
has body: you could do matches = {x for x in port_list if x == output}

http://stackoverflow.com/a/51262498
downvote count: 0
score: 8
upvote count: 8
type: Answer
answers question: http://stackoverflow.com/q/51262101
has body: This is one approach using df.apply. import pandas as pd import numpy as np df = pd.DataFrame({"a": [[np.nan, np.nan, np.nan, "a", np.nan], [np.nan, np.nan], ["a", "b"]]}) df["a"] = df["a"].apply(lambda x: [i for i in x if str(i) != "nan"]) print(df) Output: a 0 [a] 1 [] 2 [a, b]

http://stackoverflow.com/comment/89606508
type: Comment
type: QuestionComment
score: 3
comment on: http://stackoverflow.com/q/51314944
has text: My compliment. You are one of the rare users with your reputation value, which read their own questions and check for appropriate formatting. That was a quick and good edit. Very much welcome to StackOverflow.

http://stackoverflow.com/a/51211864
accepted answer of: http://stackoverflow.com/q/51207382
has body: In lmfit, arguments to the model function are expected to be scalar, floating point parameter values, except for "independent variables" which can be any python objects. By default, the first function argument is assumed to be an independent variable, as is any keyword argument with a non-numeric default value. But, you can specify which arguments are the independent variables (and there can be more than one) when creating your model. I think what you want is: m = Model(corr.__lin_iteration3__, independent_vars=['xref', 'yref_scaled', 'xobs', 'yobs']) But also: You could also pass is any Python object, so you could pack your ref and obs data into other structures and do something like def lin_iteration(Data, slope, offset, verbose=False, niter=None): Acal = 1 + (offset + slope*Data['xref'])/Data['xref'] xr_new = Data['xref'] * Acal # or maybe that would be clearer as just # xr_new = offset + (1+slope)* Data['xref'] obs_interp1d = interp1d(Data['xobs'], Data['yobs'], kind='cubic') yobs_new = scale_vector(obs_interp1d(xr_new)) rho = Pearson(Data['yref_scaled'], yobs_new) return rho and m = Model(lin_iteration) par = m.make_params(offset=0, scale=0) Data = {'xref': xref, 'yref_scaled': yref_scaled, 'xobs': xobs, 'yobs': yobs} result = m.fit(Data, params) Of course, that's all untested but it might make your life easier...
type: AcceptedAnswer
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51207382

http://stackoverflow.com/q/51180858
score: 0
answer count: 2
tagged with: pandas
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51180918
has answer: http://stackoverflow.com/a/51180946
tagged with: python
has body: I have a list: list = ['firstname', 'lastname', 'email', 'phonenumber'] I want to iterate for this list as: import pandas as pd df = pd.read_csv(filepath) df[ pd.notnull(df[firstname]) | pd.notnull(df[lastname]) | pd.notnull(df[email]) | pd.notnull(df[phonenumber])] How do I perform the above process using a loop?
type: UnansweredQuestion
type: Question
has title: How to filter data in python using pandas?
tagged with: dataframe

http://stackoverflow.com/q/51195276
tagged with: anaconda
answer count: 0
has comment: http://stackoverflow.com/comment/89374773
type: Question
linked to: http://stackoverflow.com/q/18675907
has comment: http://stackoverflow.com/comment/89374885
has comment: http://stackoverflow.com/comment/89374018
has comment: http://stackoverflow.com/comment/89372157
score: 0
has title: Adding anaconda to PATH
has comment: http://stackoverflow.com/comment/89375046
has comment: http://stackoverflow.com/comment/89372942
has comment: http://stackoverflow.com/comment/89374937
type: UnansweredQuestion
has body: I downloaded both Anaconda 2 and 3 and added them to my PATH, but when I open a new terminal and check the anaconda version, my computer says command not found: conda. I have added the commands to show what I am experiencing. # added by Anaconda2 5.2.0 installer export PATH="/anaconda2/bin:$PATH" ➜ ~ export PATH="/anaconda3/bin:$PATH" ➜ ~ export PATH="/anaconda2/bin:$PATH" ➜ ~ conda --version zsh: command not found: conda ➜ ~ ports -v zsh: command not found: ports ➜ ~
tagged with: path
tagged with: python
has comment: http://stackoverflow.com/comment/89374043

http://stackoverflow.com/a/51243823
accepted answer of: http://stackoverflow.com/q/51243533
answers question: http://stackoverflow.com/q/51243533
score: 0
has body: Try using flags=re.MULTILINE Ex: import re with open(filename, "r") as infile: print( re.findall(r'^Id:\s*(\d*)', infile.read(), flags=re.MULTILINE))
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/a/51300888
answers question: http://stackoverflow.com/q/51300833
has comment: http://stackoverflow.com/comment/89578819
score: 0
has body: Refer it as Test.somevar def changeVar(self): Test.someVar = self.val1**2 Optionally you can refer it as self.__class__.x or even shortly as self.somevar (when you dont have any other object var under the same name)
type: Answer
has comment: http://stackoverflow.com/comment/89578743

http://stackoverflow.com/a/51296069
has body: Here's a way using a trie, or prefix tree (technically a suffix tree in this situation). If we had three potential suffixes CA, CB, and BA, our suffix tree would look like e / \ A B / \ | B C C (e is the empty string) We start at the end of the input string and consume characters. If we run across the beginning of the string or a character that is not a child of the current node, then we reject the string. If we reach a leaf of the tree, then we accept the string. This lets us scale better to very many potential suffixes. def build_trie(suffixes): head = {} for suffix in suffixes: curr = head for c in reversed(suffix): if c not in curr: curr[c] = {} curr = curr[c] return head def is_suffix(trie, s): if not trie: return True for c in reversed(s): try: trie = trie[c] except KeyError: return False if not trie: return True return False trie = build_trie(['QWE','QQQQ','TYE','YTR','TY']) gives us a trie of {'E': {'W': {'Q': {}}, 'Y': {'T': {}}}, 'Q': {'Q': {'Q': {'Q': {}}}}, 'R': {'T': {'Y': {}}}, 'Y': {'T': {}}} If you want to return the matching suffix, that's just a matter of tracking the characters we see as we descend the trie. def has_suffix(trie, s): if not trie: return '' letters = [] for c in reversed(s): try: trie = trie[c] letters.append(c) except KeyError: return None if not trie: return ''.join(letters) return None It's worth noting that the empty trie can be reached by both build_trie(['']) and build_trie([]), and matches the empty string at the end of all strings. To avoid this, you could check the length of suffixes and return some non-dict value, which you would check against in has_suffix
accepted answer of: http://stackoverflow.com/q/51295864
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51295864
has comment: http://stackoverflow.com/comment/89570728
type: Answer
has comment: http://stackoverflow.com/comment/89630169
score: 1
upvote count: 1

http://stackoverflow.com/a/75074599
has comment: http://stackoverflow.com/comment/136443119
answers question: http://stackoverflow.com/q/51286748
type: Answer
downvote count: 1
has body: pydantic With pydantic models you get a dataclasses-like experience and full support for dict and Json conversions (and much more). Note: Everything below is for Pydantic V1. for Pydantic V2 please see the Migration Guide. Python 3.9 and above: from typing import Optional from pydantic import BaseModel, parse_obj_as, parse_raw_as class Foo(BaseModel): count: int size: Optional[float] = None f1 = Foo(count=10) # Parse to dict print(f1.dict()) # OUT: {'count': 10, 'size': None} # Load from dict f2 = Foo.parse_obj({"count": 20}) # Parse to json print(f2.json()) # OUT: {"count": 20, "size": null} More options: # Load from json string f3 = Foo.parse_raw('{"count": 30}') # Load from json file f4 = Foo.parse_file("path/to/data.json") # Load from list of dicts f_list1 = parse_obj_as(list[Foo], [{"count": 110}, {"count": 120}]) print(f_list1) # OUT: [Foo(count=110, size=None), Foo(count=120, size=None)] # Load from list in json string f_list2 = parse_raw_as(list[Foo], '[{"count": 130}, {"count": 140}]') print(f_list2) # OUT: [Foo(count=130, size=None), Foo(count=140, size=None)] Complex hierarchical data structures class Bar(BaseModel): apple = "x" banana = "y" class Spam(BaseModel): foo: Foo bars: list[Bar] m = Spam(foo={"count": 4}, bars=[{"apple": "x1"}, {"apple": "x2"}]) print(m) # OUT: foo=Foo(count=4, size=None) bars=[Bar(apple='x1', banana='y'), Bar(apple='x2', banana='y')] print(m.dict()) # OUT: # { # 'foo': {'count': 4, 'size': None}, # 'bars': [ # {'apple': 'x1', 'banana': 'y'}, # {'apple': 'x2', 'banana': 'y'}, # ], # } Pydantic supports many standard types (like datetime) and special commonly used types (like EmailStr and HttpUrl): from datetime import datetime from pydantic import HttpUrl class User(BaseModel): name = "John Doe" signup_ts: datetime = None url: HttpUrl = None u1 = User(signup_ts="2017-07-14 00:00:00") print(u1) # OUT: signup_ts=datetime.datetime(2017, 7, 14, 0, 0) url=None name='John Doe' u2 = User(url="http://example.com") print(u2) # OUT: signu…
upvote count: 5
score: 4

http://stackoverflow.com/comment/89415036
has text: I know this sounds like a long shot but try using it on a virtual machine of an old software. Like an older version of Windows.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51216238

http://stackoverflow.com/q/51273699
has comment: http://stackoverflow.com/comment/89525616
type: Question
has comment: http://stackoverflow.com/comment/89525870
answer count: 2
has comment: http://stackoverflow.com/comment/89525636
has comment: http://stackoverflow.com/comment/89525606
tagged with: python
tagged with: python-3.x
has title: Creating a function that provides the greatest Fibonacci number that is less than or equal to 'n'?
has comment: http://stackoverflow.com/comment/89525638
has body: I am trying to create a function that takes an input 'n' and provides an output which is the highest Fibonacci number that's less than or equal to 'n'. For example, if n = 5, then output is 5. If n = 6, then output is 5. My solution is workable but it does not seem "efficient" and I am looking for an alternative method. Here is what I did: def fib(n): if n&lt;0: print("Invalid input") x , y = 0 , 1 while x &lt;= n: x , y = y , y + x return abs(x-y) I don't think that using abs(x-y) seems very efficient so I would like to ask if anybody has a different way to solving this problem. Thank you.
score: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89526093
has answer: http://stackoverflow.com/a/51282520
has comment: http://stackoverflow.com/comment/89525684
tagged with: fibonacci
has answer: http://stackoverflow.com/a/51273734

http://stackoverflow.com/comment/89601666
score: 0
type: Comment
has text: @J0hn just to make sure, the way that I simulating keyboard press (`PressKey`) is sending and `Direct Input` type of input, right?
type: QuestionComment
comment on: http://stackoverflow.com/q/51312300

http://stackoverflow.com/q/51171813
favorite count: 0
upvote count: 2
tagged with: python
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89326362
has answer: http://stackoverflow.com/a/51171896
type: Question
has comment: http://stackoverflow.com/comment/89326392
answer count: 1
downvote count: 0
has body: I am trying to filter out rows in my data frame column 'PRODUCT' while using str.contains('DE'). DE ranges from DE001 up to DE999. How do I filter out DE998 and DE999? I have been trying this code but I can't seem to figure out a way to remove DE998 and DE999 without having to do it manually on another line. I am using df2[df2['PRODUCT'].str.contains("DE")]. Can anyone suggest a code for this or a more efficient way to do this? Thank you for answering. Sorry, still a newbie programmer.
accepted answer: http://stackoverflow.com/a/51171896
tagged with: pandas
has title: Filtering data frame using str.contains('') but with an exception

http://stackoverflow.com/q/51268671
type: Question
score: 1
has comment: http://stackoverflow.com/comment/89519398
has comment: http://stackoverflow.com/comment/89516942
linked to: http://stackoverflow.com/q/667640
answer count: 1
downvote count: 0
favorite count: 0
has title: Python IRC Bot silent timeout(?) - Stops working suddenly
has answer: http://stackoverflow.com/a/51282645
tagged with: sockets
tagged with: irc
tagged with: python
type: AnsweredQuestion
has body: I recently started writing my own IRC Bot, nothing fancy, just reads a channel and posts contents of a text file for specific commands. # let's connect irc_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) irc_socket.connect((server, 6667)) # now we login and send a test message irc_socket.send(str.encode('PASS ' + pw + '\r\n')) irc_socket.send(str.encode('NICK ' + bot + '\r\n')) irc_socket.send(str.encode('USER ' + bot + '\r\n')) irc_socket.send(str.encode('JOIN #' + channel + '\r\n')) while 1: text = irc_socket.recv(2040).decode() if text.startswith('!ideen'): do stuff #lot of code, shouldn't be of importance The weird thing is that everything works as I want it to, but for some reasons it stops working after some time. It doesn't timeout or give any errors, it just stops reacting at all. First I thought it gets overload by too many messages, but it also happens if the channel simply stays empty for 20 mins or so. Happens the same, when I run it from Pycharm or the command line (not sure why it'd make a difference). I'm probably not the only one with the problem, but I couldn't find anything. Thank you for your help, even hints for how to debug something like this. The IRC Channel is a Twitch-IRC Chat if that is of any importance. Edit: Tried @matt-m hint for debugging, it seems he stops getting the messages. The text-messages always are empty strings.
upvote count: 1
accepted answer: http://stackoverflow.com/a/51282645

http://stackoverflow.com/comment/89362855
type: QuestionComment
score: 0
has text: @jezrael please check the question again, something is wrong with the code which you gave.
type: Comment
comment on: http://stackoverflow.com/q/51189456

http://stackoverflow.com/q/51222009
has body: from pymodbus.client.sync import ModbusSerialClient as ModbusClient import logging def readModbusData(): logging.basicConfig() log = logging.getLogger() log.setLevel(logging.DEBUG) client=ModbusClient(method='rtu',port='COM3', baudrate=9600,timeout=1,parity='N',stopbits=2) print(client.connect()) client.debug_enabled() log.debug("Read holding registers") response=client.read_holding_registers(0,1) print(response) #This returns the response for whole length of registers # print(response.getRegister(0)); #This returns value of only one client.close() readModbusData() Console logs: DEBUG:pymodbus.transaction:SEND: 0x0 0x3 0x0 0x0 0x0 0x1 0x85 0xdb DEBUG:pymodbus.client.sync:New Transaction state 'SENDING' DEBUG:pymodbus.transaction:Changing transaction state from 'SENDING' to 'WAITING FOR REPLY' Modbus Error: [Input/Output] Modbus Error: [Invalid Message] Incomplete message received, expected at least 2 bytes (0 received)
favorite count: 0
tagged with: python-3.x
tagged with: modbus
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/18784931
tagged with: python
tagged with: pymodbus
has title: Modbus RTU using pymodbus - unable to read holding register from modbus data
score: 1
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/89428384
has comment: http://stackoverflow.com/comment/89447848
has comment: http://stackoverflow.com/comment/89429830
has answer: http://stackoverflow.com/a/52787790
answer count: 1
downvote count: 0

http://stackoverflow.com/comment/89365874
type: QuestionComment
type: Comment
has text: And you are matching against *each individual line*, so no, you can't then use a regex that requires there to be at least *two* lines to work.
comment on: http://stackoverflow.com/q/51192126
score: 0

http://stackoverflow.com/a/51677037
downvote count: 0
score: 1
upvote count: 1
has body: I cannot really see your code, so my answer is pretty limited. I am assuming that you want to know how to delete a range of elements in a list (please correct me if I am wrong). In the code below, you have to give the value of the index range that you have to delete. dataset = [10, 20, 50, 15, 50, 50, 901, 1000, 800] #whatever your dataset is startpop = 3 #the starting index of the data to be erased endpop = 7 #the ending index of the data to be erased del dataset[startpop:endpop]
type: Answer
answers question: http://stackoverflow.com/q/51224225

http://stackoverflow.com/q/51293196
tagged with: attributeerror
upvote count: 12
has comment: http://stackoverflow.com/comment/89563987
tagged with: pandas
answer count: 1
accepted answer: http://stackoverflow.com/a/51293275
favorite count: 0
has comment: http://stackoverflow.com/comment/89564028
has comment: http://stackoverflow.com/comment/89564541
has title: AttributeError: 'numpy.ndarray' object has no attribute 'drop'
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89563938
tagged with: delete-row
score: 11
has comment: http://stackoverflow.com/comment/89564124
downvote count: 1
has body: I'm trying to delete the first 24 rows of my pandas dataframe. Searching on the web has led me to believe that the best way to do this is by using the pandas 'drop' function. However, whenever I try to use it, I get the error: AttributeError: 'numpy.ndarray' object has no attribute 'drop' This is how I created my pandas dataframe: import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn.decomposition import PCA from sklearn.preprocessing import StandardScaler %matplotlib inline import os cwd = os.getcwd() df = pd.read_csv('C:/Users/.../Datasets/Weather/temperature4.csv') Then: df.fillna(df.mean()) df.dropna() The head of my dataframe looks like this: And then: df = StandardScaler().fit_transform(df) df.drop(df.index[0, 23], inplace=True) This is where I get the attributeerror. Not sure what I should do to delete the first 24 rows of my dataframe. (This was all done using Python 3 on a Jupyter notebook on my local machine)
type: Question
has answer: http://stackoverflow.com/a/51293275

http://stackoverflow.com/a/51308726
has comment: http://stackoverflow.com/comment/89596269
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51308352
has comment: http://stackoverflow.com/comment/89595461
answers question: http://stackoverflow.com/q/51308352
type: Answer
has comment: http://stackoverflow.com/comment/89595208
has body: One way would be to sort the list based on the length of the elements and process it in the reverse order: lis = ["Hello", "Hello1", "Test"] dict1 = {"/****Hello****/": ["C://test/hello/one.c", "C://test/hello/two.c"], "/****Hello1****/": ["C://test/helloNext/one.c", "C://test/helloNext/two.c"], "/****Test****/": ["C://test/bye/one.c", "C://test/bye/two.c"]} for x in sorted(lis, key=len, reverse=True): for y in dict1: if x in y and y not in lis: dict1[x] = dict1.pop(y) break print(dict1) # {'Hello1': ['C://test/helloNext/one.c', 'C://test/helloNext/two.c'], 'Hello': ['C://test/hello/one.c', 'C://test/hello/two.c'], 'Test': ['C://test/bye/one.c', 'C://test/bye/two.c']}
has comment: http://stackoverflow.com/comment/89595038

http://stackoverflow.com/a/51963175
upvote count: 2
has body: Python 3.7 is supported now by pylint and astroid 2.X, you can grab them with pip. Currently pylint is at 2.1.1 while astroid is at 2.0.4.
answers question: http://stackoverflow.com/q/51212795
type: Answer
score: 2
downvote count: 0

http://stackoverflow.com/q/51167593
score: 1
has comment: http://stackoverflow.com/comment/89318599
has comment: http://stackoverflow.com/comment/89318477
has comment: http://stackoverflow.com/comment/89318560
type: Question
has comment: http://stackoverflow.com/comment/89318647
has comment: http://stackoverflow.com/comment/89318388
has comment: http://stackoverflow.com/comment/89318554
has comment: http://stackoverflow.com/comment/89318497
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/89318888
has answer: http://stackoverflow.com/a/51167826
favorite count: 0
has body: I have the following logger (Python 2.7): logger = logging.getLogger('solution') logger.setLevel(logging.DEBUG) ch = logging.StreamHandler() ch.setLevel(logging.DEBUG) formatter = .... ch.setFormatter(formatter) logger.addHandler(ch) The logger can be set to Debug / Info etc... Later on my code I do get requests from APIs. I can connect to test API or Production API. #test #url = 'http://...test....com/connect/' #production url = 'http://.......com/connect/' Is there a way that I can use the logger level so that the script would know by itself if it should choose the test url or the production url? As you can see correctly one of them is in comment and I have to change it manualy every time. Something like: If logger.level = 'DEBUG': url = 'http://...test....com/connect/ else url = 'http://.......com/connect/' I know I can set a global variable to solve this but I'm wondering if the logger can be used for that.
has comment: http://stackoverflow.com/comment/89318671
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89318322
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/89318411
has title: How to use logger level status in the code in Python

matplotlib
tags question: http://stackoverflow.com/q/51278660
tags question: http://stackoverflow.com/q/51231943
tags question: http://stackoverflow.com/q/51315526
tags question: http://stackoverflow.com/q/51303380
tags question: http://stackoverflow.com/q/51218711
tags question: http://stackoverflow.com/q/51202959
tags question: http://stackoverflow.com/q/51277936
tags question: http://stackoverflow.com/q/51201364
tags question: http://stackoverflow.com/q/51313451
tags question: http://stackoverflow.com/q/51186663
tags question: http://stackoverflow.com/q/51317288
tags question: http://stackoverflow.com/q/51244309
tags question: http://stackoverflow.com/q/51289348
tags question: http://stackoverflow.com/q/51293585
tags question: http://stackoverflow.com/q/51279345
tags question: http://stackoverflow.com/q/51237022
tags question: http://stackoverflow.com/q/51268165
tags question: http://stackoverflow.com/q/51176306
tags question: http://stackoverflow.com/q/51173761
tags question: http://stackoverflow.com/q/51212011
tags question: http://stackoverflow.com/q/51315923
tags question: http://stackoverflow.com/q/51282144
tags question: http://stackoverflow.com/q/51277066
tags question: http://stackoverflow.com/q/51209797
tags question: http://stackoverflow.com/q/51193342
tags question: http://stackoverflow.com/q/51323519
tags question: http://stackoverflow.com/q/51242748
tags question: http://stackoverflow.com/q/51242352
tags question: http://stackoverflow.com/q/51322274
tags question: http://stackoverflow.com/q/51246740
tags question: http://stackoverflow.com/q/51210955
tags question: http://stackoverflow.com/q/51184189
tags question: http://stackoverflow.com/q/51222421
tags question: http://stackoverflow.com/q/51253664
tags question: http://stackoverflow.com/q/51192250
tags question: http://stackoverflow.com/q/51177849
tags question: http://stackoverflow.com/q/51285630
tags question: http://stackoverflow.com/q/51237359
tags question: http://stackoverflow.com/q/51310784
tags question: http://stackoverflow.com/q/51230423
tags question: http://stackoverflow.com/q/51242154
tags question: http://stackoverflow.com/q/51231689
tags question: http://stackoverflow.com/q/51266291
tag name: matplotlib
tags question: http://stackoverflow.com/q/51256404
tags question: http://stackoverflow.com/q/51169691
tags question: http://stackoverflow.com/q/51187240
tags question: http://stackoverflow.com/q/51262395
tags question: http://stackoverflow.com/q/51202433
tags question: http://stackoverflow.com/q/51188674
tags question: http://stackoverflow.com/q/51239301
tags question: http://stackoverflow.com/q/51303724
tags question: http://stackoverflow.com/q/51320868
tags question: http://stackoverflow.com/q/51272304
tags question: http://stackoverflow.com/q/51231320
tags question: http://stackoverflow.com/q/51276435
tags question: http://stackoverflow.com/q/51323595
tags question: http://stackoverflow.com/q/51297547
tags question: http://stackoverflow.com/q/51256360
tags question: http://stackoverflow.com/q/51204559
tags question: http://stackoverflow.com/q/51174947
tags question: http://stackoverflow.com/q/51203043
tags question: http://stackoverflow.com/q/51219068
tags question: http://stackoverflow.com/q/51314554
tags question: http://stackoverflow.com/q/51174691
tags question: http://stackoverflow.com/q/51213863
tags question: http://stackoverflow.com/q/51290182
tags question: http://stackoverflow.com/q/51296949
tags question: http://stackoverflow.com/q/51315721
tags question: http://stackoverflow.com/q/51318950
tags question: http://stackoverflow.com/q/51286455
tags question: http://stackoverflow.com/q/51254308
tags question: http://stackoverflow.com/q/51220918
tags question: http://stackoverflow.com/q/51300658
tags question: http://stackoverflow.com/q/51178853
tags question: http://stackoverflow.com/q/51181436
tags question: http://stackoverflow.com/q/51203591
tags question: http://stackoverflow.com/q/51258494
tags question: http://stackoverflow.com/q/51253661
tags question: http://stackoverflow.com/q/51288628

http://stackoverflow.com/q/51223418
answer count: 1
has body: Created Virtual environment (Python 3.7.0) and tried installing pyarrow: pip3.7 install --no-cache pyarrow and getting error: Collecting pyarrow Downloading https://files.pythonhosted.org/packages/be/2d/11751c477e4e7f4bb07ac7584aafabe0d0608c170e4bff67246d695ebdbe/pyarrow-0.9.0.tar.gz (8.5MB) 100% |████████████████████████████████| 8.5MB 383kB/s 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 "/private/var/folders/xy/b__x_l9n1kl9_llyngq1cvddqsd9bn/T/pip-install-3p7vvogb/pyarrow/setup.py", line 29, in &lt;module&gt; from Cython.Distutils import build_ext as _build_ext ModuleNotFoundError: No module named 'Cython' ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in /private/var/folders/xy/b__x_l9n1kl9_llyngq1cvddqsd9bn/T/pip-install-3p7vvogb/pyarrow/ Tried installing Cython and running again pip3.7 install --no-cache pyarrow, this time got different error at the end: Command "/Users/myuser/python/venv/p3/bin/python3 -u -c "import setuptools, tokenize;__file__= '/private/var/folders/xy/b__x_l9n1kl9_llyngq1cvddqsd9bn/T/pip-install-3a5y_ug4/pyarrow/setup.py'; f=getattr(tokenize, 'open', open)(__file__); code=f.read().replace('\r\n', '\n');f.close(); exec(compile(code, __file__, 'exec'))" install --record /private/var/folders/xy/b__x_l9n1kl9_llyngq1cvddqsd9bn/T/pip-record-tw4inr9f/install-record.txt --single-version-externally-managed --compile --install-headers /Users/myuser/python/venv/p3/include/site/python3.7/pyarrow" failed with error code 1 in /private/var/folders/xy/b__x_l9n1kl9_llyngq1cvddqsd9bn/T/pip-install-3a5y_ug4/pyarrow/
tagged with: python-module
has answer: http://stackoverflow.com/a/51250493
favorite count: 0
tagged with: python-3.x
downvote count: 0
type: UnansweredQuestion
tagged with: python
score: 2
has title: How to install pyarrow on mac
type: Question
upvote count: 2

http://stackoverflow.com/a/51169314
has comment: http://stackoverflow.com/comment/89372606
type: Answer
has comment: http://stackoverflow.com/comment/89348008
has comment: http://stackoverflow.com/comment/89324326
answers question: http://stackoverflow.com/q/51168896
upvote count: 1
has comment: http://stackoverflow.com/comment/89321479
score: 1
downvote count: 0
has body: It looks like you are creating clusters and histograms for each image. But in order to make it work you have to aggregate the sift features for all images and then clusters theses and use these common clusters to create the histogram. Check out also https://github.com/shackenberg/Minimal-Bag-of-Visual-Words-Image-Classifier

http://stackoverflow.com/comment/89366126
score: 0
has text: @MartijnPieters How do I cancel them using sets
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51192126

http://stackoverflow.com/q/51286018
has comment: http://stackoverflow.com/comment/89550345
has comment: http://stackoverflow.com/comment/92135565
has comment: http://stackoverflow.com/comment/89550838
type: Question
has comment: http://stackoverflow.com/comment/89550951
has comment: http://stackoverflow.com/comment/89550768
score: 0
has title: Python requests authentication after redirect result 401
tagged with: python
linked to: http://stackoverflow.com/q/37945057
has comment: http://stackoverflow.com/comment/89550732
tagged with: python-3.x
answer count: 0
type: UnansweredQuestion
has body: I have question regarding HTTP Basic Authentication after a redirect. I am trying to login to a website which redirects me to a login site (HTTP 302 response). import requests response = requests.get('my_url') if response.history: print("Request was redirected") for resp in response.history: print(resp.status_code, resp.url) print("Final destination:") print(response.status_code, response.url) else: print("Request was not redirected") The output: Request was redirected 302 my_url Final destination: 401 new_url The new_url is url where I should put username and password. I tried solution from here: stackowerflow but it didn't work for me - I always get response: Out[152]: &lt;Response [401]&gt; Any suggestions what I'm doing wrong?
tagged with: python-requests
tagged with: http

http://stackoverflow.com/comment/89465496
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51241661
has text: Yes it does, I believe there is a timestamp integrated into the encryption process which gives a different encryption output each time. This gives you the option to add a `ttl` parameter when creating the encrypted string.
score: 0

http://stackoverflow.com/comment/89509533
type: Comment
type: QuestionComment
score: 2
has text: That is logical: `counter1` does not *return* anything, hence in that case it returns `None`.
comment on: http://stackoverflow.com/q/51265816

http://stackoverflow.com/q/51253953
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/51254920
downvote count: 1
upvote count: 0
tagged with: python
type: AnsweredQuestion
score: -1
has body: I want to get the prediction probabilities for each class along with the class labels for a decision tree classifier. probs = clf.predict_proba(test). This give me the probabilities and I want to sort to get the top 3 so the code below would give me that: best_n = np.argsort(probs, axis=1)[-n:] But I am unaware how to incorporate the clf.classes_ along with this to get it all together?
has title: Is there a way to get both the prediction probabilities for each class along with the labels for each class in a decision tree classifier?
type: Question
accepted answer: http://stackoverflow.com/a/51254920

http://stackoverflow.com/q/51175840
favorite count: 0
has title: Can't locate a library when script is run from a different directory
tagged with: python
tagged with: shared-libraries
type: UnansweredQuestion
downvote count: 1
tagged with: putty
has answer: http://stackoverflow.com/a/51176019
score: -1
type: Question
linked to: http://stackoverflow.com/q/4383571
upvote count: 0
answer count: 1
has body: Running a script on Putty, under directory user/Projects/Python/example.py. Under the Python directory, there is a subfolder called crypto, and under that, a library called cryptolib.so. If I run example.py from the Python folder, it works perfectly. But if I run it from my user folder, it says: OSError: ./crypto/cryptolib.so: cannot open shared object file: No such file or directory. This is a C++ library I'm calling, using Python How do I change the library path?

http://stackoverflow.com/q/51249564
type: Question
upvote count: 1
has body: The Notebook demo of NYC Citibike Demand with Weather (Large) can't be run locally due to errors accessing the Citibike datasets. When the following cell is run: big_test = [mylocate("bigdata/laptop/citibike-nyc/2013-07.csv"), mylocate("bigdata/laptop/citibike-nyc/2013-08.csv"), mylocate("bigdata/laptop/citibike-nyc/2013-09.csv"), mylocate("bigdata/laptop/citibike-nyc/2013-10.csv"), mylocate("bigdata/laptop/citibike-nyc/2013-11.csv"), mylocate("bigdata/laptop/citibike-nyc/2013-12.csv"), mylocate("bigdata/laptop/citibike-nyc/2014-01.csv"), mylocate("bigdata/laptop/citibike-nyc/2014-02.csv"), mylocate("bigdata/laptop/citibike-nyc/2014-03.csv"), mylocate("bigdata/laptop/citibike-nyc/2014-04.csv"), mylocate("bigdata/laptop/citibike-nyc/2014-05.csv"), mylocate("bigdata/laptop/citibike-nyc/2014-06.csv"), mylocate("bigdata/laptop/citibike-nyc/2014-07.csv"), mylocate("bigdata/laptop/citibike-nyc/2014-08.csv")] # ---------- # 1- Load data - 1 row per bicycle trip. Has columns showing the start and end # station, trip duration and trip start time and day. The larger dataset # totals about 10 million rows print("Import and Parse bike data") data = h2o.import_file(path=big_test) The following error is output if data_source_is_s3 is set to true: H2OResponseError: Server error java.lang.IllegalArgumentException: Error: AWS Access Key ID and Secret Access Key must be specified as the username or password (respectively) of a s3n URL, or by setting the fs.s3n.awsAccessKeyId or fs.s3n.awsSecretAccessKey properties (respectively). Request: GET /3/ImportFiles params: {'path': 's3n://h2o-public-test-data/bigdata/laptop/citibike-nyc/2013-07.csv'} and the following if data_source_is_s3 is set to False: ValueError: File not found: bigdata/laptop/citibike-nyc/2013-10.csv
has comment: http://stackoverflow.com/comment/89511930
favorite count: 0
tagged with: h2o
tagged with: python
answer count: 0
downvote count: 0
type: UnansweredQuestion
has title: NYC Citibike Demand demo data access error
score: 1

http://stackoverflow.com/a/51236240
type: Answer
has body: try this: keras.backend.clear_session()
score: 0
answers question: http://stackoverflow.com/q/51236215

http://stackoverflow.com/q/51240875
duplicate of: http://stackoverflow.com/q/24072790
tagged with: qt
has comment: http://stackoverflow.com/comment/89460644
score: 0
tagged with: pyside2
tagged with: pyside
tagged with: pyqt5
answer count: 0
type: UnansweredQuestion
has title: Using Pyside2/Pyqt5 to detect keyboard input when QT application is minimised and out of focus
has body: I'm writing a Windows Python application using the Pyside2 Qt5 binding. I want the user to be able to press a combination of hot keys(e.g "j" + "k") regardless of whether or not the Qt application is in focus or not in focus/minimized. I ideally want to take advantage of signals and slots, so when the specific key combination is emitted I can intercept it via a slot to perform a specific function. I looked into QShortcut, but I can't seem to get the functionality I want when the Qt application is minimized in the backround/out of focus. One workaround I've had some success with is using Pynput, however, I was hoping for a Qt specific solution.
linked to: http://stackoverflow.com/q/24072790
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/89460671

http://stackoverflow.com/a/51223838
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/89430184
has comment: http://stackoverflow.com/comment/89430080
downvote count: 0
answers question: http://stackoverflow.com/q/51218957
has body: See ImageVisual.set_data method # Create the image img_data = np.random.random((800,800, 3)) image = scene.visuals.Image(img_data, parent=view.scene) view.camera.set_range() # Generate new data : img_data_new = np.zeros((800,800, 3)) img_data_new[400:, 400:, 0] = 1. # red square image.set_data(img_data_new)
type: Answer

http://stackoverflow.com/comment/89571668
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51296898
has text: Whats the problem, Why do you ask? Is it because you are having issues installing? If so can you give more details?

http://stackoverflow.com/comment/89580388
type: QuestionComment
comment on: http://stackoverflow.com/q/51301688
has text: @jezrael explain please how can I use that answer in my case? I have already seen it but did not get how to use it in my case - in that case columns are named, my columns are unnamed.
score: 0
type: Comment

http://stackoverflow.com/comment/89715197
type: QuestionComment
score: 0
has text: Please close this thread then, for example by answering your own question.
comment on: http://stackoverflow.com/q/51235033
type: Comment

http://stackoverflow.com/a/51286901
has comment: http://stackoverflow.com/comment/89551575
has comment: http://stackoverflow.com/comment/89552528
score: 1
has comment: http://stackoverflow.com/comment/89553028
upvote count: 1
answers question: http://stackoverflow.com/q/51286525
has body: There are a lot of services. For instance, making a Google search: PAID EOD Historical Xignite FREE IEX Developer Platform Tiingo Check out also this list
has comment: http://stackoverflow.com/comment/89552451
has comment: http://stackoverflow.com/comment/89552648
has comment: http://stackoverflow.com/comment/89551920
downvote count: 0
type: Answer

loops
tags question: http://stackoverflow.com/q/51289972
tags question: http://stackoverflow.com/q/51184617
tags question: http://stackoverflow.com/q/51176690
tags question: http://stackoverflow.com/q/51222834
tags question: http://stackoverflow.com/q/51320956
tags question: http://stackoverflow.com/q/51203302
tags question: http://stackoverflow.com/q/51225292
tags question: http://stackoverflow.com/q/51309762
tags question: http://stackoverflow.com/q/51199226
tags question: http://stackoverflow.com/q/51207828
tags question: http://stackoverflow.com/q/51196487
tags question: http://stackoverflow.com/q/51217524
tags question: http://stackoverflow.com/q/51172081
tags question: http://stackoverflow.com/q/51275357
tags question: http://stackoverflow.com/q/51202437
tags question: http://stackoverflow.com/q/51248306
tags question: http://stackoverflow.com/q/51174715
type: Tag
tags question: http://stackoverflow.com/q/51241670
tags question: http://stackoverflow.com/q/51270368
tags question: http://stackoverflow.com/q/51322864
tags question: http://stackoverflow.com/q/51208399
tags question: http://stackoverflow.com/q/51172585
tags question: http://stackoverflow.com/q/51172403
tags question: http://stackoverflow.com/q/51202238
tags question: http://stackoverflow.com/q/51281477
tag name: loops
tags question: http://stackoverflow.com/q/51206289
tags question: http://stackoverflow.com/q/51209823
tags question: http://stackoverflow.com/q/51218054
tags question: http://stackoverflow.com/q/51316220
tags question: http://stackoverflow.com/q/51313895
tags question: http://stackoverflow.com/q/51208552
tags question: http://stackoverflow.com/q/51302203
tags question: http://stackoverflow.com/q/51317953
tags question: http://stackoverflow.com/q/51263016
tags question: http://stackoverflow.com/q/51223640
tags question: http://stackoverflow.com/q/51315185
tags question: http://stackoverflow.com/q/51248067
tags question: http://stackoverflow.com/q/51266698
tags question: http://stackoverflow.com/q/51170893

http://stackoverflow.com/q/51192905
answer count: 1
has title: Merging one minute ahead time frame values from csv using Pandas Python 3
tagged with: pandas
tagged with: http://stackoverflow.com/tag/csv
has body: I am trying to compare the test file with model file and then verifying it with the result. Here is what I have tried till now: import pandas as pd data = pd.read_csv("data.csv",encoding = "utf-16", header = 0,sep="\t") data.head(20) createmodel = data.drop(labels=['param1','param3','param5','param7','param9','param13','param15','colorsame'], axis=1) createmodel.drop_duplicates().to_csv("model.csv",index=False,header =True,sep="\t",encoding="utf-16") createmodel.head(10) createmodel.drop_duplicates().to_csv("test.csv",index=False,header =True,sep="\t",encoding="utf-16") createmodel.head(10) verifyresult = pd.read_csv("verify.csv",encoding = "utf-16", header = 0,sep="\t") verifyresult.head(20) result = pd.merge(testmodel,createmodel, on = ["param2","param4","param6","param8","param10","param11","param12","param14","param16"]) result = result.drop_duplicates() Here are the files model,test, and verify I have achieved the comparison, using the merge statement and got output in the result variable. The only part that is troubling me is that, I need to find one minute later time of the value in the result.Time from the verify.csv and then merge the values with result in another column. And save it as csv. The final result must be like the following: If following is the dataframe in result variable: 2018.5.1 0:5 0-1 0-1 0-1 0-1 0--1 0 1 -43--42 78-79 Red And verify.csv has: 2018.5.1 0:6 Green which is the values associated with the one minute later time frame of the value of result variable. Then the new frame should be: Time param2 param4 param6 param8 param10 param11 param12 param14 param16 color Actual 2018.5.1 0:5 0-1 0-1 0-1 0-1 0--1 0 1 -43--42 78-79 Red Green which is the final result. Kindly, suggest me the way to do and achieve what I want.
tagged with: python
type: AnsweredQuestion
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51193565
type: Question
accepted answer: http://stackoverflow.com/a/51193565
score: 0

http://stackoverflow.com/q/51293554
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89566046
tagged with: python
has body: Is there a way to resize two axes by appending new data?. I was able to append new data to one axis using resize and maxshape following Docs in h5py Docs. But what I am trying now is append data to two axes at once by using the same logic as appending to one axis. But what I am getting is a TypeError: Can't broadcast (10000, 500, 2) -&gt; (10000, 1000, 2). This might be due to the chunks sizes but can't figure it out. Any suggestion This is what I tried so far: def create_hdf5_file(name, path, shape, chunks = None): """create a hdf5 file given a path, shape and chunks. If chunks is not given file will be created without any chunk. Default chunks is equal to False. The file will be compressed as gzip with a level of compression equals to 4. This function will append data to the hdf5 file""" with h5py.File(str(path+'/'+name+'.hdf5'), 'w') as f: dset = f.create_dataset(str(name), compression = 'gzip', shape= (shape), chunks= (chunks), \ maxshape = (None, None, shape[2])) n = 10**5 # size for axis 0 #m = 5*10**3 size for axis 1 while dset.shape[0] &lt; n: # and dset.shape[1] &lt; m: dset.resize(dset.shape[0]+10**4, axis=0) #dset.resize(dset.shape[1]+5*10**2, axis = 1) dset[-10**4:] = np.random.randint(2, size=(10**4, shape[1], shape[2])) #dset[-5*10**2:] = np.random.randint(2, size =(shape[0], 5*10**2, shape[2])) print(dset.shape) print('Final dataset size: {}'.format(dset.shape)) print('Chunks size: {}'.format(dset.chunks)) print('HDF5 file created as: {}'.format(str(name)+'.hdf5')) if __name__ == "__main__": create_hdf5_file(name='test',path='/home/neither/Desktop', \ shape = (10000, 500,2), chunks= (1000,5000,2)) I commented what I was trying while appending data into a new axis. But I get the previous error. Appending data into axis 0 works as expected but when trying to do the same with both axes fails.
type: Question
tagged with: numpy
answer count: 1
score: 0
tagged with: h5py
has title: Resize two axes at once h5py
has answer: http://stackoverflow.com/a/51294965

http://stackoverflow.com/comment/89434384
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51227101
score: 0
has text: It's not *that* cryptic an error message; you defined a method but didn't call it.

http://stackoverflow.com/a/51788863
has comment: http://stackoverflow.com/comment/90629737
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90585950
has comment: http://stackoverflow.com/comment/90635493
upvote count: 1
has comment: http://stackoverflow.com/comment/90657143
type: Answer
has body: It's because scrapy-heroku does not support python-3 instead use python-2 as a environment.
has comment: http://stackoverflow.com/comment/90628398
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/51202121
accepted answer of: http://stackoverflow.com/q/51202121

http://stackoverflow.com/q/51193931
favorite count: 0
has answer: http://stackoverflow.com/a/51194088
upvote count: 2
has answer: http://stackoverflow.com/a/51194082
type: UnansweredQuestion
downvote count: 2
has answer: http://stackoverflow.com/a/51194149
type: Question
has body: I know how to concatenate two columns of strings. df['a'] + ' ' + df['b'] but if I have a long list of column names I can't write all that out. This is obviously incorrect but I was thinking something along the lines of... ' '.join([df[col] for col in columns])
has answer: http://stackoverflow.com/a/51194220
has title: Concatenate columns of strings, where the column names are in a list
score: 0
tagged with: pandas
tagged with: python
answer count: 4

http://stackoverflow.com/a/51223950
has body: Why can't I decompose this matrix? Because it is not separable. The DoG, and many other kernels, are not separable. What class of matrices are separable (into two vectors)? The kernels where all rows are scaled versions of the other rows are separable. That is, each row i must be of the form r[i][j] = a[i] * b[j] where b is the “model row”, and a[i] is the scaling for each row. This looks kind of obvious, since the multiplication above is what you get when you convolve the column kernel a with the row kernel b (and is the outer product that the code in the question uses). To know if a 2D kernel is separable, compute its rank: the rank must be 1. This indicates that all rows are scaled versions of each other. For reference, here are two different MATLAB solutions to the kernel decomposition in an arbitrary number of dimensions: my solution, using SVD DJ Kroon’s solution, using least squares
type: AcceptedAnswer
downvote count: 0
score: 2
accepted answer of: http://stackoverflow.com/q/51223006
upvote count: 2
answers question: http://stackoverflow.com/q/51223006
type: Answer

http://stackoverflow.com/comment/89491176
type: QuestionComment
comment on: http://stackoverflow.com/q/51253538
has text: the middleware was not installed correctly as it says scrapy cannot find it. How did you install it?
score: 0
type: Comment

http://stackoverflow.com/q/51187962
type: Question
answer count: 2
downvote count: 0
tagged with: pandas
favorite count: 0
has body: I have two data frame as follows: DF1: Name Value buying fish hook 240 arrange lunch 75 repair equipment 800 purchase air condition 1400 buying fish 66 DF 2: Name fish lunch equipemt air condition hair condition fish hook I want to match the name in name columns from both dataframe with fuzzy logic and add name column from second dataframe to first as: Name Value item buying fish hook 240 fish hook arrange lunch 75 lunch repair equipment 800 equipment purchase air condition 1400 air condition not all names have exact match. Df 2 has several names and some have matching words ex: air condition and hair condition. Splitting values from DF 1 causes miss match where fish hook is matched only with fish
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51188054
tagged with: python
has answer: http://stackoverflow.com/a/51211165
score: 3
upvote count: 3
has title: How to match and extract text from dataframe in pandas using fuzzy logic?

http://stackoverflow.com/q/51259562
answer count: 1
has body: I'm try to use asciimatics for a TUI, which will be the front end for a test frame work. The TUI should have some parameters that are constant and are common for all tests, and another section where there are parameters based on the selected test. I'm pretty sure I can get this to work if I create a main frame for the common parameters, and frames for each individual test, then, based on the selected test open the specific test frame when the user clicks a button to edit test parameters. However, I would much rather have the test parameters shown along side the common ones. I was thinking about putting the second frame inside a layout, and swapping it on the fly when the selected test is changed. Is this possible to do with asciimatics? Thanks, o
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/52021379
type: Question
has title: How to show 2 scene side by side in asciimatics
score: 0
tagged with: user-interface

http://stackoverflow.com/comment/89552648
score: 0
comment on: http://stackoverflow.com/a/51286901
type: AnswerComment
has text: That is where I'm looking, but it does not tell me if I should import anything, only commands to use in order to get the data.
type: Comment

http://stackoverflow.com/comment/89370643
comment on: http://stackoverflow.com/q/51194517
score: 0
type: Comment
type: QuestionComment
has text: What do you mean "this will throw away any models"? The session just runs the computation graph, your model stays as is.

http://stackoverflow.com/a/51251729
upvote count: 3
score: 3
accepted answer of: http://stackoverflow.com/q/51249178
answers question: http://stackoverflow.com/q/51249178
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/89517041
has comment: http://stackoverflow.com/comment/89609688
type: Answer
has comment: http://stackoverflow.com/comment/89525200
has body: That goes best in the models.py of the specific app that uses it. But during development, this # my_app/models.py import os mymodule = {'a': 1} print('id: {} -- pid: {}'.format(id(mymodule), os.getpid())) will print out two lines with two different pids. That is, because during development, Django uses the first process for the auto-reload feature. To disable that, turn off auto-reload with: ./manage.py runserver --noreload. And now you can do # my_app/views.py import os from django.http import HttpResponse from .models import mymodule def home(request): return HttpResponse('id: {} -- pid: {}'.format(id(mymodule), os.getpid())) and it will print the same pid and the same id for the mymodule object.

http://stackoverflow.com/comment/89457979
score: 1
comment on: http://stackoverflow.com/q/51237022
has text: I know that. The point is that we cannot run your code and reproduce the error. Have you actually followed the link that @ImportanceOfBeingErnest has provided? It explains very well how you can cook down your problem into a minimal runnable example.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89350830
score: 0
type: AnswerComment
has text: It saved my time significantly. For more than 3 hours using my own code, it reduced to only no more than 10 seconds.
type: Comment
comment on: http://stackoverflow.com/a/51174730

http://stackoverflow.com/q/51189055
has title: QcomboBox using "ENTER" event
upvote count: 1
has comment: http://stackoverflow.com/comment/89359979
type: Question
accepted answer: http://stackoverflow.com/a/51189441
has comment: http://stackoverflow.com/comment/89359862
has comment: http://stackoverflow.com/comment/89359850
tagged with: pyqt4
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/89359788
tagged with: pyqt
downvote count: 0
has comment: http://stackoverflow.com/comment/89360064
answer count: 1
linked to: http://stackoverflow.com/q/62594748
score: 1
has comment: http://stackoverflow.com/comment/89359822
has body: in this user selects item from DROP DOWN menu use "SEARCH" button to search. I want to add "ENTER" but as a shortcut for this event. Please refer image.it will be more clear.
favorite count: 0
tagged with: qcombobox
has answer: http://stackoverflow.com/a/51189441
has comment: http://stackoverflow.com/comment/89359940
has comment: http://stackoverflow.com/comment/89360350
has comment: http://stackoverflow.com/comment/89359913
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/89389005
type: Comment
comment on: http://stackoverflow.com/a/51194867
type: AnswerComment
score: 0
has text: @Aacini Of course all Kudos go to you ;-). I didn't now that link, inserted it into my answer.

http://stackoverflow.com/q/51227323
tagged with: decode
answer count: 2
downvote count: 0
score: 1
favorite count: 0
tagged with: python-3.x
has body: There are some packages that returns values as bytes in my project. There is some configuration or environment variable to set so I don't need to decode bytes to string ever again? And if so, what is it?
has answer: http://stackoverflow.com/a/51227998
tagged with: python
type: AnsweredQuestion
upvote count: 1
has title: How to avoid decoding bytes to string all the time?
type: Question
tagged with: encoding
accepted answer: http://stackoverflow.com/a/51227998
possible better answer: http://stackoverflow.com/a/51227332
has comment: http://stackoverflow.com/comment/89434633
has answer: http://stackoverflow.com/a/51227332

http://stackoverflow.com/comment/89477344
score: 0
comment on: http://stackoverflow.com/q/51237725
type: QuestionComment
type: Comment
has text: @HackSaw Added. Sorry bout that.

parallel-processing
tags question: http://stackoverflow.com/q/51274194
tags question: http://stackoverflow.com/q/51211769
tags question: http://stackoverflow.com/q/51271451
tags question: http://stackoverflow.com/q/51256738
tags question: http://stackoverflow.com/q/51185274
tags question: http://stackoverflow.com/q/51219201
type: Tag
tag name: parallel-processing
tags question: http://stackoverflow.com/q/51184001

http://stackoverflow.com/comment/89613765
has text: You cant upload the data, can you?
score: 0
comment on: http://stackoverflow.com/q/51309166
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51280767
upvote count: 1
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51290864
score: 1
has comment: http://stackoverflow.com/comment/89543664
accepted answer: http://stackoverflow.com/a/51290864
type: Question
tagged with: mypy
has comment: http://stackoverflow.com/comment/89538891
downvote count: 0
has title: Static typing for function return value of nested list
answer count: 1
has comment: http://stackoverflow.com/comment/89542479
tagged with: python-typing
favorite count: 0
has body: I have a Python code: from typing import List, Optional class MyClass: pass def generate_list() -> List[List[Optional[MyClass]]]: my_list = [[None for _ in range(10)] for _ in range(10)] # assignments might be extended in the future my_list[0][0] = MyClass() return my_list I want generate list to return a list, that includes a list which might have either None or MyClass objects in it. Simplified list might look like this [[None, None, <my_class_object>], [<my_class_object>, None, <my_class_object>]] Right now mypy is raising error on line my_list[0][0] = MyClass() With message error: Incompatible return value type (got "List[List[None]]", expected "List[List[Optional[MyClass]]]") I guess I'm missing something, or it even might not be possible to do what I want.

http://stackoverflow.com/comment/89361436
has text: @spejsy Only is this specific case though. In real-world cases you may not know which `num` produces a `None` response.
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/51189742

http://stackoverflow.com/comment/89479715
has text: Thank you for your help, but that didn't worked.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51250382

http://stackoverflow.com/comment/89591157
comment on: http://stackoverflow.com/q/51307228
type: Comment
type: QuestionComment
score: 3
has text: Django is a backend. So all things that should change dynamically should be handled through JavaScript. There are some Django libraries that can make that easier, but the workhorse at the frontend is JS.

http://stackoverflow.com/a/51213209
answers question: http://stackoverflow.com/q/51212695
score: 0
has comment: http://stackoverflow.com/comment/89421550
type: Answer
has body: Not sure what you want to do here, but if you want to implement any post save actions for model look at django signals. Particularly at post_save signal. Here is example usage of post_save signal, for model Test1(suppose you want to create new Test2 object): from django.db.models.signals import post_save from django.dispatch import receiver @receiver(post_save, sender=Test1) def create_test2(sender, instance, created, **kwargs): Test2.objects.create(test1id=instance)

http://stackoverflow.com/comment/89590397
type: Comment
has text: Re-reading your question with this information makes it clear that there are multiple issues with your code: Why is partner_id only an Integer, not a Many2One ('res.partner')? How is your method create_contact_tag() called? (It seems some more code is missing) You need to set all values to the vals dict before creating records, including the market_id, application_id. Where should these come from? Why are you naming your loop variable "partner", even though it iterates over sale_order_line_ids? (in your new code). I'm afraid these are too many questions to give you a good answer...
type: AnswerComment
comment on: http://stackoverflow.com/a/51213663
score: 0

http://stackoverflow.com/comment/89451188
type: Comment
has text: @a_guest these are classes in mochgir.py file.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51236061

http://stackoverflow.com/comment/89468502
has text: Thanks. How can i use them just for this script when i am running all my other python scripts currently in anaconda env?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51244960

http://stackoverflow.com/comment/89327770
type: QuestionComment
comment on: http://stackoverflow.com/q/51171256
has text: I see you have 3 different templates to extract the required information. I am assuming that on a particular page, either of the 3 templates would work, and I guess every product has **ASIN**. Is that right?
score: 0
type: Comment

http://stackoverflow.com/a/51215393
downvote count: 0
answers question: http://stackoverflow.com/q/51206648
has body: In order for mypy (and other PEP 484 compliant tools) to understand how to type a given module, it must be able to find stubs for that module somewhere. Mypy (if we simplify slightly) checks essentially two different places for stubs: It checks a local copy of typeshed, which is a repository of type hints for the standard library and popular 3rd party libraries. (A copy of typeshed is automatically installed alongside mypy.) It checks if the package itself is bundling type hints (e.g. if the package is a PEP 561 compliant package). Unfortunately, it seems that tzwhere is doing neither of these things: I can't find it on typeshed; it doesn't appear to be bundling types. As a result, mypy will not be able to accurately type check code using tzwhere. You have three main options: Just suppress the error message by adding a # type: ignore annotation to the import. Note that this will introduce some dynamism into your code: any variable/function you use from tzwhere will be assumed to be of type Any. Create type stubs for the module, store it in a folder somewhere, and point the MYPYPATH environment variable at that folder. Note that this will require a little bit of detective work on your part. More details on how mypy finds imports here. If you want to share your work from step 2 with others, either submit a pull request to typeshed with your stubs or submit a pull request with tzwhere itself to turn it into a PEP 561 compliant package. Make sure you get an ok from the author of the library before doing either of these things.
score: 4
type: Answer
upvote count: 4

pipeline
type: Tag
tags question: http://stackoverflow.com/q/51217367
tag name: pipeline
tags question: http://stackoverflow.com/q/51276877
tags question: http://stackoverflow.com/q/51308362
tags question: http://stackoverflow.com/q/51268803

http://stackoverflow.com/q/51245526
downvote count: 0
has title: PySMB Handler - [WinError 10054] An existing connection was forcibly closed by the remote host
type: Question
has body: I am tring to use PYSMB smb handler to save files to windows shared folder from Linux box. Currently, I am running the code on windows box to test. # -*- coding: utf-8 -*- import urllib.request from smb.SMBHandler import SMBHandler director = urllib.request.build_opener(SMBHandler) fh = director.open('smb://username:password!@Directory/path/upload_file.txt') fh.close() Below is the part of error shown. File "C:\ProgramData\Anaconda3\lib\urllib\request.py", line 526, in open response = self._open(req, data) File "C:\ProgramData\Anaconda3\lib\urllib\request.py", line 544, in _open '_open', req) File "C:\ProgramData\Anaconda3\lib\urllib\request.py", line 504, in _call_chain result = func(*args) File "C:\ProgramData\Anaconda3\lib\site-packages\smb\SMBHandler.py", line 45, in smb_open names = n.queryIPForName(host) File "C:\ProgramData\Anaconda3\lib\site-packages\nmb\NetBIOS.py", line 79, in queryIPForName ret = self._pollForQueryPacket(trn_id, timeout) File "C:\ProgramData\Anaconda3\lib\site-packages\nmb\NetBIOS.py", line 144, in _pollForQueryPacket raise ex File "C:\ProgramData\Anaconda3\lib\site-packages\nmb\NetBIOS.py", line 131, in _pollForQueryPacket data, _ = self.sock.recvfrom(0xFFFF) ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host Though there are many solutions regarding the error, there is nothing specific to smb handler. Can you help me figure out the issue? Thank you.
upvote count: 3
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: smb
tagged with: python
score: 3
answer count: 0

http://stackoverflow.com/comment/89551562
score: 0
type: Comment
type: QuestionComment
has text: [The repository](https://github.com/philippbosch/django-geoposition) has not been updated since 2016, so you can't expect it to work in Django 2.0. You could try one of the [pull requests](https://github.com/philippbosch/django-geoposition/pulls) which add support for Django 2.0, or perhaps look for a different library which is still being maintained.
comment on: http://stackoverflow.com/q/51286678

http://stackoverflow.com/a/51226912
has comment: http://stackoverflow.com/comment/89439351
score: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51225909
type: Answer
accepted answer of: http://stackoverflow.com/q/51225909
has body: clean_pairs is a list of lists. The core Python language does not formally have a concept of multi-dimensional arrays so the syntax you're using clean_pairs[i,0] does not work. It should be clean_pairs[i][0]. You probably got the idea from using Pandas which is using a more sophisticated n-d array data structure that supports that style of indexing. I'm confused by your code though. It looks like you're saving a a dataframe to a TSV file (tab-separated) and then manually parsing the TSV and performing text transformations on it? There are multiple things wrong with this: Just as you used a library to write a TSV file, you should use a library to read one too. A CSV/TSV reader will return your rows of data directly back to you in a pre-parsed data structure. AFAICT you can do all this kind of filtering on the data in memory without writing to an intermediate file in the first place. You've also got some other problems at least in the code you posted. For example your to_pairs function (which again is something you should be leaving up to a library, if at all) doesn't return anything.

http://stackoverflow.com/comment/89634636
has text: The problem with this code is you are not addressing the real problem but using a bad workaround to visualize the updating of the loading bar. The tkinter application is still frozen and not usable during these sleep calls. At no point should your have code in your program that specifically freezes the GUI and this could cause unpredictable issues down the road.
comment on: http://stackoverflow.com/a/51299593
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/89584368
type: QuestionComment
has text: Do you want to copy From Value Column of First Dataframe to the Value Column of Second Data frame ? or what was the question. It seems unclear....
score: 1
comment on: http://stackoverflow.com/q/51302668
type: Comment

http://stackoverflow.com/a/51281538
accepted answer of: http://stackoverflow.com/q/51281236
answers question: http://stackoverflow.com/q/51281236
type: Answer
upvote count: 4
downvote count: 0
has body: Yield in generator expressions is actually a bug, as discussed in this related question. If you want to actually see what's going on with dis, you need to introspect on the code object's co_const[0], so: &gt;&gt;&gt; dis.dis(f1.__code__.co_consts[1]) 2 0 LOAD_FAST 0 (.0) &gt;&gt; 3 FOR_ITER 11 (to 17) 6 STORE_FAST 1 (i) 9 LOAD_FAST 1 (i) 12 YIELD_VALUE 13 POP_TOP 14 JUMP_ABSOLUTE 3 &gt;&gt; 17 LOAD_CONST 0 (None) 20 RETURN_VALUE &gt;&gt;&gt; dis.dis(f2.__code__.co_consts[1]) 2 0 LOAD_FAST 0 (.0) &gt;&gt; 3 FOR_ITER 12 (to 18) 6 STORE_FAST 1 (i) 9 LOAD_FAST 1 (i) 12 YIELD_VALUE 13 YIELD_VALUE 14 POP_TOP 15 JUMP_ABSOLUTE 3 &gt;&gt; 18 LOAD_CONST 0 (None) 21 RETURN_VALUE So, it yields twice.
has comment: http://stackoverflow.com/comment/89541456
has comment: http://stackoverflow.com/comment/89540670
type: AcceptedAnswer
score: 4

http://stackoverflow.com/q/51292438
has title: Python - writeback function not working
answer count: 1
has comment: http://stackoverflow.com/comment/89562633
has comment: http://stackoverflow.com/comment/89563211
tagged with: python
has answer: http://stackoverflow.com/a/51292517
type: UnansweredQuestion
has body: This is my school project code for a number game: I am trying to store the user's name and score in the database, and then print a list of all user names and scores. When I run the code the user's name and score is overwritten every time and the previous user and score is not saved. Shouldn't the writeback=True function prevent the data from being overwritten? name=('n') Fscore=(0) import shelve s = shelve.open('hscore_shelf.db',writeback=True) key1 = [name] try: existing = s['key1'] finally: s.close() print (existing) import shelve n = shelve.open('score_shelf.db',writeback=True) key1 = [Fscore] try: existing = n['key1'] finally: s.close() print(existing) print("WELCOME TO THE NUMBER QUIZ") input("HIT ENTER TO START") name=(input("ENTER YOUR NAME")) q = (1) score=(0) while q &lt;=1 and q &gt;0: import random num1 =(random.randint(1,9)) num2 =(random.randint(1,9)) num3 =(random.randint(1,9)) index1=num1 index2=num2 index3=num3 e=(" eleven") teens= ("ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen") units=(" ","one","two","three","four","five","six","seven","eight","nine") tens=(""," ","twenty ","thirty ","fourty ","fifty ","sixty ","seventy ","eighty ","ninety ") hun=("","one hundred and ", "two hundred and ", "three hundred and ", "four hundred and ", "five hundred and ", "six hundred and ", "seven hundred and ", "eight hundred and ", "nine hundred and ") print("Type in the following number using digits") if num1==0 and num2==0 and num3==0: print("zero") elif num1==0 and num2==0 and num3&gt;0: print(units[index3]) elif num1==0 and num2==1: print(teens[index3]) elif num1&gt;0 and num2==1 and num3==1: print(hun[index1]+e) else: print(hun[index1]+tens[index2]+units[index3]) num11=(int(input("Enter first digit:"))) num22=(int(input("Enter second digit:"))) num33=(int(input("Enter third digit:"))) q = (q-1) if num1==num11 and num2==num22 and num3==num33: print("Correct") score=(score+1) else: print("Incorrect") Fscore=(s…
has comment: http://stackoverflow.com/comment/89562584
tagged with: shelve
has comment: http://stackoverflow.com/comment/89562979
type: Question
has comment: http://stackoverflow.com/comment/89562681
score: 0

http://stackoverflow.com/q/51296034
answer count: 2
has title: ImportError: cannot import name _aligners [biopython]
tagged with: python
tagged with: biopython
score: 4
has comment: http://stackoverflow.com/comment/89606509
tagged with: import
has comment: http://stackoverflow.com/comment/89633853
upvote count: 4
has body: I am doing bioinformatics that has biopython dependency. Biopython always give me the following error: I hope someone could help me with this issue. Thank you!
type: UnansweredQuestion
tagged with: importerror
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/51376616
has answer: http://stackoverflow.com/a/60535873
type: Question
tagged with: bioinformatics
has comment: http://stackoverflow.com/comment/89569618

http://stackoverflow.com/comment/89523111
comment on: http://stackoverflow.com/q/51271368
type: Comment
type: QuestionComment
has text: @tobsecret, because the OP's request for "just a push in the right direction" is very different from "you are asking SO to write code for you", I do not understand your comment. would you please clarify that part of your comment?
score: 1

rfid
tag name: rfid
tags question: http://stackoverflow.com/q/51269275
type: Tag

http://stackoverflow.com/q/51233280
has answer: http://stackoverflow.com/a/51233556
has comment: http://stackoverflow.com/comment/89499202
type: AnsweredQuestion
favorite count: 0
type: Question
tagged with: python
accepted answer: http://stackoverflow.com/a/51233556
upvote count: 2
score: 0
downvote count: 2
tagged with: openpyxl
answer count: 1
linked to: http://stackoverflow.com/q/28929310
has comment: http://stackoverflow.com/comment/89446016
duplicate of: http://stackoverflow.com/q/28929310
has body: Hi I am iterating through lines, from few answers in the forum and using row_offset=1 but it is not skipping the header, please check and help. Code > import openpyxl > > Owb= openpyxl.load_workbook("E:\\First.xlsx") Ows = Owb.worksheets[0] > > row_counter=1 > > for row in Ows.iter_rows(row_offset=1): > > policy_number=Ows.cell(row=row_counter,column=1).value > print policy_number > Ows.cell(row=row_counter, column=2).value = "test value" > > row_counter = row_counter + 1 > Owb.save("E:\\First.xlsx")
has title: python openpyxl skip header of excel

http://stackoverflow.com/a/51248355
type: Answer
answers question: http://stackoverflow.com/q/51248218
upvote count: 1
has body: Verbose version: def check_pos_tag(document): nn = document['NN'] if 'NN' in document else 0 ne = document['NE'] if 'NE' in document else 0 return nn + ne
downvote count: 0
score: 1

http://stackoverflow.com/q/51317549
has answer: http://stackoverflow.com/a/51317652
downvote count: 0
has comment: http://stackoverflow.com/comment/89611095
favorite count: 0
tagged with: python
accepted answer: http://stackoverflow.com/a/51317585
type: AnsweredQuestion
upvote count: 2
possible better answer: http://stackoverflow.com/a/51317587
has answer: http://stackoverflow.com/a/51317587
has comment: http://stackoverflow.com/comment/89611118
type: Question
has body: I am a newbie to python. I am trying to put my 22k images into matrix before i process them using CNN. However, I encounter this situation which I don't know where I did wrong. path1 = 'C:/Users/Z/Documents/Python Scripts/Data' path2 = 'C:/Users/Z/Documents/Python Scripts/Data1' listing = os.listdir(path1) num_samples=size(listing) for file in listing: im = Image.open(path1 + '\\' + file) img_rows, img_cols = 224, 224 img = im.resize((img_rows,img_cols),3) img.save(path2 +'\\' + file, "JPEG") imlist = os.listdir(path2) img_data_list=[] a = Image.open('Data1' + '\\'+ imlist[0]) # open one image to get size im1 = array(a) m,n = im1.shape[0:3] # get the size of the images imnbr = len(imlist) # get the number of images num_samples = len(imlist) I got this error
has comment: http://stackoverflow.com/comment/89611076
has comment: http://stackoverflow.com/comment/89611121
has answer: http://stackoverflow.com/a/51317585
answer count: 3
score: 2
has title: FileNotFoundError: [Errno 2] No such file or directory ,even I have the image in that particular folder

http://stackoverflow.com/q/51223025
possible better answer: http://stackoverflow.com/a/51224566
answer count: 2
downvote count: 0
favorite count: 0
upvote count: 1
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89437253
has answer: http://stackoverflow.com/a/51223365
score: 1
tagged with: selenium
tagged with: web-scraping
tagged with: calendar
type: Question
has body: I'm currently attempting to scrape judgments from this website (https://www.sci.gov.in/judgments) using Selenium, Python and Jupyter Notebook. I'm currently stuck choosing the date in the jQuery calendar. The following code allows me to change the month: driver.get("https://www.sci.gov.in/judgments") driver.find_element_by_xpath('//*[@id="tabbed-nav"]/ul[2]/li[3]/a').click(); driver.find_element_by_xpath('//*[@id="JBJfrom_date"]').click(); selectByVisibleText = Select(driver.find_element_by_class_name('ui-datepicker-month')); selectByVisibleText.select_by_visible_text("Jan"); Adding the following code should allow me to change the year: selectByVisibleText2 = Select(driver.find_element_by_class_name('ui-datepicker-year')); selectByVisibleText2.select_by_visible_text("1950"); However, the above code doesn't work. I'm only above to either change the dropdown of either the year or the month, but not both of them. I'm also unable to get Selenium to move to any other part of the screen. Like for example to click the submit button. driver.find_element_by_xpath('//*[@id="getJBJ"]').click(); Why is selenium not able to identify the other dropdown and how do I get it to select both date and month? Thank you so much for your time!
has answer: http://stackoverflow.com/a/51224566
tagged with: jquery
accepted answer: http://stackoverflow.com/a/51223365
has title: Selenium (Python) does not switch between two select dropdown menus
has comment: http://stackoverflow.com/comment/89426581

http://stackoverflow.com/q/51219761
has title: Option to replace the matrix key return error in dictionary using python
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/89420644
favorite count: 0
tagged with: matrix
tagged with: python
accepted answer: http://stackoverflow.com/a/51219803
tagged with: dictionary
linked to: http://stackoverflow.com/q/8813226
upvote count: 1
type: AnsweredQuestion
score: 1
has body: I have a list of matrix and I would like to print the value for that key. This is the code: list1=np.matrix([[ 0.],[ 1.]]),np.matrix([[ 1.],[ 0.]]),np.matrix([[ 1.],[ 0.]]) print (list1) dictionary = { np.matrix([[ 0.],[ 1.]]): '1' , np.matrix([[ 1.],[ 0.]]):'0'} output=[dictionary[i] for i in list1] The output shows like this: (matrix([[ 0.], [ 1.]]), matrix([[ 1.], [ 0.]]), matrix([[ 1.], [ 0.]])) dictionary = { np.matrix([[ 0.],[ 1.]]): '1' , np.matrix([[ 1.],[ 0.]]):'0'} TypeError: unhashable type: 'matrix' Supposedly, the output shows like this: 1, 0, 0 Since the matrix can not be used as the key in dictionary, is there any way to assign the value for the list of matrix? Thank you.
has comment: http://stackoverflow.com/comment/89420532
has answer: http://stackoverflow.com/a/51219803
type: Question

http://stackoverflow.com/comment/89555652
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51288911
score: 1
has text: For scalar need `and` like `if(a=='cust' and b=='id')`

http://stackoverflow.com/comment/89461959
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51205949
type: Comment
has text: and where is scan part in your code can you post that one so i can work around that.

http://stackoverflow.com/q/51242063
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89463064
score: 2
has answer: http://stackoverflow.com/a/51242168
has title: Create a single element tuple of tuple
favorite count: 0
tagged with: python-3.x
tagged with: tuples
accepted answer: http://stackoverflow.com/a/51242168
tagged with: python
answer count: 4
possible better answer: http://stackoverflow.com/a/51242402
upvote count: 3
has answer: http://stackoverflow.com/a/51242205
has answer: http://stackoverflow.com/a/51242402
has answer: http://stackoverflow.com/a/51242194
downvote count: 1
has body: I just noticed that if you want to create a tuple with single element, being a tuple itself, you cannot do it with constructor tuple only with (,) syntax. Why is that? Example: &gt;&gt;&gt; tuple(list('abc')) ('a', 'b', 'c') &gt;&gt;&gt; tuple(tuple(list('abc'))) ('a', 'b', 'c') &gt;&gt;&gt; (tuple(list('abc')),) (('a', 'b', 'c'),) But then it holds for a list &gt;&gt;&gt; tuple([1],) (1,) &gt;&gt;&gt; tuple([1]) (1,)
type: Question

http://stackoverflow.com/q/51272159
downvote count: 1
type: Question
score: -1
tagged with: printf
has comment: http://stackoverflow.com/comment/89522419
tagged with: operating-system
upvote count: 0
answer count: 1
tagged with: shell
has body: I'm not entirely sure how to express what I need, but in essence, I need for something like dirname = raw_inpur("what is your dirname") os.mkdir(os.getcwd(), %s) %dirname os.chdir(os.getcwd()/ %s), %dirname I'm not entirely sure what the proper syntax for something like this is. Edit: Just overthinking ofc thanks
has comment: http://stackoverflow.com/comment/89522547
tagged with: command
favorite count: 0
has comment: http://stackoverflow.com/comment/89522481
type: UnansweredQuestion
tagged with: python
has title: Getting printf like variable changes in os commands in Python
has answer: http://stackoverflow.com/a/51272201

http://stackoverflow.com/q/51301596
has comment: http://stackoverflow.com/comment/89580091
has answer: http://stackoverflow.com/a/51756692
type: Question
tagged with: multiprocessing
score: 0
answer count: 1
has body: I use Python 3.6 and start a process in my script (VTK Visualization). Until I close the visualization window the command line is blocked which I want to change. I read something about multiprocessing and threading, but I'm not sure which is the right approach. This is what I want to achieve and my ideas: start two processes (visualization window and a loop for inputs) with exec(input) the inputs are written into my script after that the visualization window is updated I am thankful for any advice on which method could be suitable for my intend! Edit: I tried threading and started both threads, but still the command line was blocked until I closed the window and just opened up again after typing in an input.. Is there anyone who achieved something similar before?
has comment: http://stackoverflow.com/comment/89580126
tagged with: pythoninterpreter
tagged with: vtk
type: UnansweredQuestion
tagged with: python-multithreading
has title: How to use the python interpreter while another python process is running?
tagged with: python

http://stackoverflow.com/q/51286833
answer count: 2
has body: I am trying to extract numeric string from text using python - example : "大田区大森北3−24−27ルミエールN103 " I only want '3-24-27' from a column in df. I tried this but the error says invalid syntax. I am now working with Japanese script but I need this for other languages as well. I am new to python and request some help - Thanks.
has title: extracting numeric string from text in python
has answer: http://stackoverflow.com/a/51287056
has answer: http://stackoverflow.com/a/51290076
score: 0
tagged with: pandas
tagged with: python
tagged with: regex
tagged with: text-extraction
linked to: http://stackoverflow.com/q/10365225
has comment: http://stackoverflow.com/comment/89551741
has comment: http://stackoverflow.com/comment/89551265
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89551210
has comment: http://stackoverflow.com/comment/89551377
type: Question

http://stackoverflow.com/comment/89474676
has text: It is not clear what are you trying to achieve? Can you tell in words what the math operation does? Also, can you post the expected output?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51247928

http://stackoverflow.com/q/51199765
has body: I'm trying to insert a child element into a parent element but for some reason I cannot manage to update the tree in order to write a file containing the child element I just created. Can anyone please let me know what I'm missing? This is what I have And this is what I need tree = et.parse('/Users/missogra/Desktop/test/s_tagging/1.txt') root = tree.getroot() for element in root: if element.tag == 'p': p = et.Element("p") child = et.SubElement(p, "s" ) # How to update the new root from here?
has comment: http://stackoverflow.com/comment/89387974
accepted answer: http://stackoverflow.com/a/51205584
answer count: 1
tagged with: elementtree
tagged with: http://stackoverflow.com/tag/xml
tagged with: python-3.x
tagged with: python
has comment: http://stackoverflow.com/comment/89387479
has title: Changes in XML tree using Elementtree do not get updated
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51205584
score: 0
type: Question

http://stackoverflow.com/comment/89358134
has text: I think I am not clear enough. The data is coming from one_shot_iterator. I might be wrong, but I think data is coming as the tensor, not numpy array. So what is the use of using feed_dict here and placeholders when you can pass data directly to graph?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51188174
type: AnswerComment

http://stackoverflow.com/a/51316081
upvote count: 1
has comment: http://stackoverflow.com/comment/89609179
answers question: http://stackoverflow.com/q/51316065
has comment: http://stackoverflow.com/comment/89608818
type: Answer
has comment: http://stackoverflow.com/comment/89608666
has comment: http://stackoverflow.com/comment/89608958
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/89608985
has comment: http://stackoverflow.com/comment/89609112
has body: You can check the length of the set of resulting values: class Item(object): def __init__(self, val): self.val = val def __repr__(self): return f'Item({self.val})' def compute(x): return x%10 items = [ Item(0), Item(11), Item(25), Item(16), Item(31)] c = list(map(lambda x:compute(x.val), items)) if len(set(c)) == len(c): #no two or more equal values exist in the list raise Exception("All elements have unique computational results") To find values with similar computational results, a dictionary can be used: from collections import Counter new_d = {i:compute(i.val) for i in items} d = Counter(new_d.values()) multiple = [a for a, b in new_d.items() if d[b] &gt; 1] Output: [Item(11), Item(31)] A slightly more efficient way to find if multiple objects of the same computational value exist is to use any, requiring a single pass over the Counter object, whereas using a set with len requires several iterations: if all(b == 1 for b in d.values()): raise Exception("All elements have unique computational results")

http://stackoverflow.com/comment/89448702
comment on: http://stackoverflow.com/q/51234889
score: 3
has text: Which version of HTMltestrunner do you have?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89344625
has text: Awesome. So do it untill you find out what the hell is in that cell :) (i.e. until something returns `True`)
type: AnswerComment
comment on: http://stackoverflow.com/a/51180953
score: 0
type: Comment

http://stackoverflow.com/q/51200369
has title: Shift rows of a numpy array independently
favorite count: 0
has answer: http://stackoverflow.com/a/51255018
type: Question
accepted answer: http://stackoverflow.com/a/51614167
tagged with: python
has comment: http://stackoverflow.com/comment/89382616
answer count: 3
upvote count: 7
has comment: http://stackoverflow.com/comment/89382809
linked to: http://stackoverflow.com/q/20360675
tagged with: numpy
has comment: http://stackoverflow.com/comment/89382976
tagged with: arrays
has answer: http://stackoverflow.com/a/51614167
has answer: http://stackoverflow.com/a/65682885
has body: This is an extension of the question posed here (quoted below) I have a matrix (2d numpy ndarray, to be precise): A = np.array([[4, 0, 0], [1, 2, 3], [0, 0, 5]]) And I want to roll each row of A independently, according to roll values in another array: r = np.array([2, 0, -1]) That is, I want to do this: print np.array([np.roll(row, x) for row,x in zip(A, r)]) [[0 0 4] [1 2 3] [0 5 0]] Is there a way to do this efficiently? Perhaps using fancy indexing tricks? The accepted solution was: rows, column_indices = np.ogrid[:A.shape[0], :A.shape[1]] # Use always a negative shift, so that column_indices are valid. # (could also use module operation) r[r &lt; 0] += A.shape[1] column_indices = column_indices - r[:,np.newaxis] result = A[rows, column_indices] I would basically like to do the same thing, except when an index gets rolled "past" the end of the row, I would like the other side of the row to be padded with a NaN, rather than the value move to the "front" of the row in a periodic fashion. Maybe using np.pad somehow? But I can't figure out how to get that to pad different rows by different amounts.
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89383149
downvote count: 0
score: 7
possible better answer: http://stackoverflow.com/a/51255018

http://stackoverflow.com/q/51247772
has answer: http://stackoverflow.com/a/51248390
has comment: http://stackoverflow.com/comment/89478028
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/89474449
has body: I got error message when upload file into media folder. I already have set everything to 777 permisson and change owner to apache. Loading media and static files are fine. I m using centos7 with httpd service. Please, help me to figure it out. For addition information, wirte file through hardcode is working fine. The error looks like Here's the error message: Traceback: File "/opt/ezadmin/env/lib/python2.7/site-packages/django/core/handlers/exception.py" in inner 41. response = get_response(request) File "/opt/ezadmin/env/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/opt/ezadmin/env/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/opt/ezadmin/env/lib/python2.7/site-packages/django/contrib/admin/options.py" in wrapper 552. return self.admin_site.admin_view(view)(*args, **kwargs) File "/opt/ezadmin/env/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapped_view 149. response = view_func(request, *args, **kwargs) File "/opt/ezadmin/env/lib/python2.7/site-packages/django/views/decorators/cache.py" in _wrapped_view_func 57. response = view_func(request, *args, **kwargs) File "/opt/ezadmin/env/lib/python2.7/site-packages/django/contrib/admin/sites.py" in inner 224. return view(request, *args, **kwargs) File "/opt/ezadmin/env/lib/python2.7/site-packages/django/contrib/admin/options.py" in change_view 1512. return self.changeform_view(request, object_id, form_url, extra_context) File "/opt/ezadmin/env/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapper 67. return bound_func(*args, **kwargs) File "/opt/ezadmin/env/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapped_view 149. response = view_func(request, *args, **kwargs) File "/opt/ezadmin/env/lib/python2.7/site-packages/django/utils/decorators.py" in bound_func 63. return …
has comment: http://stackoverflow.com/comment/89477389
tagged with: apache
has title: Django unable to upload into 777 permission folder
score: -1
tagged with: centos
tagged with: linux
answer count: 2
upvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/89474282
has answer: http://stackoverflow.com/a/51249896
has comment: http://stackoverflow.com/comment/89475310
type: UnansweredQuestion
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/89474319

http://stackoverflow.com/comment/89593823
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51296263
has text: @SachinPatel Users should extremely rarely upload their full code. A question should contain a [mcve]. If users paste in their full code it'll make the question too specific to be valuable for others, and it'll usually contain too much code, which makes it harder to read and reason about.
score: 1

http://stackoverflow.com/a/51236902
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51233683
type: Answer
score: 1
upvote count: 1
has body: initializePage() method is called a moment before displaying the page so you should not call that logic in that part, a possible solution is to use a QTimer. class ProcessData(QWizardPage): """ Sensor Code Entry """ def __init__(self, parent=None): super(ProcessData, self).__init__(parent) self.altThing = True # num of logs combo box self.num_logs_combo = QComboBox(self) self.alt = QComboBox(self) # ~buttons self.btn = QPushButton('OK') self.onloadbtn = QPushButton('OK') layout = QVBoxLayout(self) layout.addWidget(self.num_logs_combo) layout.addWidget(self.alt) layout.addWidget(self.btn) layout.addWidget(self.onloadbtn) self.onloadbtn.hide() self.alt.hide() self.btn.clicked.connect(self._EnterToken) def foo(self): if self.altThing: # .. do Something QMessageBox.about(self, 'Hello', 'Hello') #Pops up before the page is rendered # do other stuff.."" def initializePage(self): QTimer.singleShot(0, self.foo) def _EnterToken(self): """ Method for processing user input after the button is pressed""" pass
accepted answer of: http://stackoverflow.com/q/51233683

http://stackoverflow.com/comment/89371158
type: AnswerComment
has text: Handle missing value too.
type: Comment
comment on: http://stackoverflow.com/a/51194370
score: 0

http://stackoverflow.com/comment/89342000
type: QuestionComment
type: Comment
has text: can you post the full traceback here please?
score: 0
comment on: http://stackoverflow.com/q/51178485

http://stackoverflow.com/q/51295666
upvote count: 1
has answer: http://stackoverflow.com/a/51295705
accepted answer: http://stackoverflow.com/a/51295705
favorite count: 0
tagged with: python
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/51295683
downvote count: 0
has answer: http://stackoverflow.com/a/51295683
score: 1
tagged with: backquote
tagged with: racket
has body: I can't understand what I'm doing wrong here. Maybe a misplaced backquote. The racket code: (require math/array) (define mask_cube (let ([leng 5]) `(make-array #(,leng ,leng) 0))) What I want it to do, written in python: np.zeros((5,5)) Why isn't the comma working like I think it should? If there's a more elegant way to solve the problem, please let me know. Mostly I just want my pretty, short np.zeros() function Moreover, if there's something fundamental I'm misunderstanding about backquote, commas, or racket (or even Lisp in general), please let me know.
linked to: http://stackoverflow.com/q/34984552
has title: racket: equivalent to np.zeros((n, m))
type: Question
tagged with: numpy
answer count: 2
tagged with: lisp

http://stackoverflow.com/comment/89414388
comment on: http://stackoverflow.com/q/51216523
score: 0
type: Comment
has text: sorry its rule_b_obj. corrected thanks @PatrickHaugh
type: QuestionComment

http://stackoverflow.com/a/51220251
has comment: http://stackoverflow.com/comment/89421468
answers question: http://stackoverflow.com/q/51219752
has comment: http://stackoverflow.com/comment/89421462
score: 0
has comment: http://stackoverflow.com/comment/89421541
has body: Let suppose you've your line of text in a file named sentence.txt. sentence.txt As a manager, he told FIFA TV he communicates his messages in a measured way. "I'm not one of the lads," Southgate explained. Now, you can try the below code to read the above line and extract the sub string enclosed within " (double quotes). # -*- coding: utf-8 -*- with open('sentence.txt', encoding='utf-8') as f: sentence = f.read().strip(); words = sentence.split('\"'); if len(words) == 3: string_in_double_quote = words[1]; print string_in_double_quote # I'm not one of the lads, else: print 'WARNING: String in text file does not have 2 double quotes, make sure to have it'
has comment: http://stackoverflow.com/comment/89421498
has comment: http://stackoverflow.com/comment/89421492
type: Answer

http://stackoverflow.com/q/51178115
accepted answer: http://stackoverflow.com/a/51178179
tagged with: sys
score: -3
tagged with: python
type: AnsweredQuestion
downvote count: 3
possible better answer: http://stackoverflow.com/a/57043596
type: Question
has title: how to run exe file and type arguments from python
has comment: http://stackoverflow.com/comment/89338877
answer count: 2
tagged with: operating-system
tagged with: cmd
has answer: http://stackoverflow.com/a/57043596
tagged with: exe
favorite count: 0
upvote count: 0
has answer: http://stackoverflow.com/a/51178179
has body: I have an executable external program that ask the name of the arguments file. I am trying to program this action through python coding. How can it be done?

http://stackoverflow.com/comment/89378574
comment on: http://stackoverflow.com/a/51173274
score: 1
type: AnswerComment
has text: @user3138864, the gzip module gives you a generic file-like object; you can use `shutil.copyfileobj()` with it to copy from that to any other file object on Python (without requiring enough memory to store the whole content in RAM, as the answer currently does).
type: Comment

http://stackoverflow.com/q/51220934
has title: Kernel died restarting spyder and PyQt5
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89429641
tagged with: python
tagged with: pyqt5
type: Question
has body: I am experiencing a strange issue on my PyQt5 running on Python for Windows 10 64 bit. I am using Spyder as editor. Below is my code #read in a table from db dbpath = r"c:\mypath\TransactionToday.db" dbpath.replace('\\','/') import sqlite3 as sql conn = sql.connect(dbpath) c = conn.cursor() c.execute("SELECT * FROM Bord_1_2127") data = c.fetchall() conn.close() from PyQt5.QtWidgets import(QTableWidget, QTableWidgetItem) tw = QTableWidget() tw.setRowCount(len(data)) tw.setColumnCount(4) r = -1 c = -1 When I debug my code I see that the kernel died at tw = QTableWidget() I am not sure the reason why, as if I fresh restart my PC I can get it to work. However if I run this code multiple times, all of sudden I keep getting into the Kernel died restart issue. When I search on this issue I see multiple report on that this problem is related to Windows 10 and others mention that it is due to start up of too many instances of PyQt5. I am not sure if this is my case, since I guess my code is not starting up any instances related to QApplication?
has comment: http://stackoverflow.com/comment/89422805
has comment: http://stackoverflow.com/comment/89422833
score: 0
tagged with: spyder

http://stackoverflow.com/q/51273670
upvote count: 2
tagged with: python
type: AnsweredQuestion
has body: I have been trying to set up a very simple python program to connect to Google Drive API, I have tried dozens of different approaches I found online but none seem to be working, documentation is all over the place and I cant get it to work. I am in need of an approach that does not prompt the user to grant access seeing that I am going to be accessing my own personal drive, I would like it to do it automatically without me having to accept every time. Could anyone send me a complete (very simplistic) working code template that I can use to connect to googles drive API using python? This is my latest attempt, you might modify this one or create a new one, I just need it to work :( import google.oauth2.credentials import google_auth_oauthlib.flow from oauth2client.client import OAuth2WebServerFlow, FlowExchangeError # Use the client_secret.json file to identify the application requesting # authorization. The client ID (from that file) and access scopes are required. flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file( 'client_secret.json', scopes=['https://www.googleapis.com/auth/drive.metadata.readonly']) # Indicate where the API server will redirect the user after the user completes # the authorization flow. The redirect URI is required. flow.redirect_uri = 'http://localhost:8888/' # Generate URL for request to Google's OAuth 2.0 server. # Use kwargs to set optional request parameters. authorization_url, state = flow.authorization_url( # Enable offline access so that you can refresh an access token without # re-prompting the user for permission. Recommended for web server apps. access_type='offline', # Enable incremental authorization. Recommended as a best practice. include_granted_scopes='true') print(state) # code = input('Enter verification code: ').strip() try: credentials = flow.step2_exchange(state) print(json.dumps(json.loads(credentials._to_json([])), sort_keys=True, indent=4)) except FlowExchangeError: print("Your verification code is incorrect …
score: 1
has answer: http://stackoverflow.com/a/51278513
downvote count: 1
has comment: http://stackoverflow.com/comment/89540999
type: Question
accepted answer: http://stackoverflow.com/a/51278513
answer count: 1
has title: Setting up Google Drive API in Python
favorite count: 0
tagged with: google-drive-api

http://stackoverflow.com/q/51277457
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89533349
has title: How to add a typing declaration for a dict with different types as values in python
has comment: http://stackoverflow.com/comment/89532459
has comment: http://stackoverflow.com/comment/89532423
type: Question
upvote count: 4
possible better answer: http://stackoverflow.com/a/51277703
downvote count: 0
accepted answer: http://stackoverflow.com/a/51277762
has comment: http://stackoverflow.com/comment/89532756
has answer: http://stackoverflow.com/a/51277703
score: 4
has comment: http://stackoverflow.com/comment/89532618
has comment: http://stackoverflow.com/comment/89532444
has body: I have a dictionary as follows my_dict = { "key_1": "value_1", "key_2": { "key_1": True, "key_2": 1200 } "key_3": True, } and in my class @dataclass class TestClass: my_dict: typing.Dict[{str, str}, {str, typing.Dict[{str, bool}, {str, int}]}] The above declaration is incorrect. If I want to add typing for my_dict what it should be and how to write the structure since I am having different types as values?
answer count: 3
tagged with: python
tagged with: python-typing
favorite count: 0
has answer: http://stackoverflow.com/a/78292615
has answer: http://stackoverflow.com/a/51277762

http://stackoverflow.com/a/51199045
upvote count: 0
has body: One nasty solution would be to just use tail -n 13 updated_quotes.csv &gt; last_quotes.csv. You could invoke it via subprocess.check_output("tail -n 13 updated_quotes.csv &gt; last_quotes.csv", shell=True)
answers question: http://stackoverflow.com/q/51198871
type: Answer
downvote count: 1
score: -1

http://stackoverflow.com/comment/89359143
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51170784
has text: Correct. When a request comes, I am returning a generator function as a event-stream response. I am trying to access the session inside that generator function.

selenium
tags question: http://stackoverflow.com/q/51202867
tags question: http://stackoverflow.com/q/51277484
tags question: http://stackoverflow.com/q/51273995
tags question: http://stackoverflow.com/q/51239512
tags question: http://stackoverflow.com/q/51246962
tags question: http://stackoverflow.com/q/51234889
tags question: http://stackoverflow.com/q/51192198
tags question: http://stackoverflow.com/q/51306375
tags question: http://stackoverflow.com/q/51279368
tags question: http://stackoverflow.com/q/51243809
tags question: http://stackoverflow.com/q/51214853
tags question: http://stackoverflow.com/q/51320135
tags question: http://stackoverflow.com/q/51313226
tags question: http://stackoverflow.com/q/51213150
tags question: http://stackoverflow.com/q/51240720
tags question: http://stackoverflow.com/q/51259785
tags question: http://stackoverflow.com/q/51237273
tags question: http://stackoverflow.com/q/51187933
tags question: http://stackoverflow.com/q/51323354
tags question: http://stackoverflow.com/q/51276893
tags question: http://stackoverflow.com/q/51230824
tags question: http://stackoverflow.com/q/51281805
tags question: http://stackoverflow.com/q/51252236
tags question: http://stackoverflow.com/q/51276635
tags question: http://stackoverflow.com/q/51199026
tags question: http://stackoverflow.com/q/51175323
tags question: http://stackoverflow.com/q/51320294
tags question: http://stackoverflow.com/q/51222157
tags question: http://stackoverflow.com/q/51310774
tags question: http://stackoverflow.com/q/51240272
tags question: http://stackoverflow.com/q/51203260
tags question: http://stackoverflow.com/q/51207625
tags question: http://stackoverflow.com/q/51183229
tags question: http://stackoverflow.com/q/51173220
tags question: http://stackoverflow.com/q/51236252
tags question: http://stackoverflow.com/q/51188180
tags question: http://stackoverflow.com/q/51227511
tags question: http://stackoverflow.com/q/51252083
tags question: http://stackoverflow.com/q/51179601
tags question: http://stackoverflow.com/q/51195502
tags question: http://stackoverflow.com/q/51188330
tags question: http://stackoverflow.com/q/51175638
tags question: http://stackoverflow.com/q/51227799
tag name: selenium
tags question: http://stackoverflow.com/q/51279921
tags question: http://stackoverflow.com/q/51248986
tags question: http://stackoverflow.com/q/51208401
tags question: http://stackoverflow.com/q/51253916
tags question: http://stackoverflow.com/q/51266235
tags question: http://stackoverflow.com/q/51246874
tags question: http://stackoverflow.com/q/51199515
tags question: http://stackoverflow.com/q/51176193
tags question: http://stackoverflow.com/q/51217618
tags question: http://stackoverflow.com/q/51224314
tags question: http://stackoverflow.com/q/51255274
tags question: http://stackoverflow.com/q/51223025
tags question: http://stackoverflow.com/q/51303649
tags question: http://stackoverflow.com/q/51185284
tags question: http://stackoverflow.com/q/51208207
tags question: http://stackoverflow.com/q/51250542
tags question: http://stackoverflow.com/q/51181949
tags question: http://stackoverflow.com/q/51264652
tags question: http://stackoverflow.com/q/51250668
tags question: http://stackoverflow.com/q/51262274
tags question: http://stackoverflow.com/q/51280539
tags question: http://stackoverflow.com/q/51261038
tags question: http://stackoverflow.com/q/51290499
tags question: http://stackoverflow.com/q/51280078
tags question: http://stackoverflow.com/q/51273285
tags question: http://stackoverflow.com/q/51263444
tags question: http://stackoverflow.com/q/51314737
tags question: http://stackoverflow.com/q/51310495
tags question: http://stackoverflow.com/q/51180363
tags question: http://stackoverflow.com/q/51323686
tags question: http://stackoverflow.com/q/51285004
tags question: http://stackoverflow.com/q/51233901
tags question: http://stackoverflow.com/q/51286846
tags question: http://stackoverflow.com/q/51199226
tags question: http://stackoverflow.com/q/51207243
tags question: http://stackoverflow.com/q/51310047

http://stackoverflow.com/q/51175894
favorite count: 0
tagged with: pyinstaller
has comment: http://stackoverflow.com/comment/89336993
tagged with: python
has comment: http://stackoverflow.com/comment/89337293
has body: I have a python package that involves several python modules. The project has been created in pycharm. I have used pyinstaller to create a single executable file of my python package. When I run the executable using a batch file I get an import error, specifically pandas has failed to be imported. Is there a reason why pyinstaller has not also collected the package dependencies in my virtual environment? Thanks in advance for any help! I have the following 2 errors: (1) ModuleNotFoundError: No module named 'pandas._libs.tslibs.np_datetime' (2) File "site-packages\pandas__init__.py", line 35, in ImportError: C extension: No module named 'pandas._libs.tslibs.np_datetime' 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.
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51177430
downvote count: 1
has title: Import error when using pyinstaller to create a single exe file
tagged with: executable
has comment: http://stackoverflow.com/comment/89336764
type: Question
score: 0
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/89336212
linked to: http://stackoverflow.com/q/49893124

http://stackoverflow.com/comment/89438149
comment on: http://stackoverflow.com/a/51203512
score: 0
has text: Yeah, it breaks the string into list of sub-strings and check each sub-string in list. If it's a digit `sub.isdigit()` returns `True` - the sub-string is added to new list. If there are more than one digit in a string and you want to get all of them in a list - simply remove element index as `digits = [sub for sub in browser.find_element_by_xpath('//span[@gogo-test="backers"]').text.split() if sub.isdigit()]`
type: Comment
type: AnswerComment

http://stackoverflow.com/q/51178166
tagged with: python
score: 2
upvote count: 2
has answer: http://stackoverflow.com/a/51178793
has body: I am trying to iterate through a folder of .png files and OCR them. The iteration works but as soon as I try to open Images with PIL it gives errors. import pytesseract from PIL import Image import os for filename in os.listdir('C:/Users/Artur/Desktop/Sequenz_1'): if filename.endswith('.png'): print(filename) This works just fine. It prints every .png filename in the folder. But when I try to OCR: import pytesseract from PIL import Image import os for filename in os.listdir('C:/Users/Artur/Desktop/Sequenz_1'): if filename.endswith('.png'): print(pytesseract.image_to_string(Image.open(filename))) Output: Traceback (most recent call last): File "C:\Users\Artur\Desktop\Pytesseract_test.py", line 8, in &lt;module&gt; print(pytesseract.image_to_string(Image.open(filename))) File "C:\Users\Artur\AppData\Local\Programs\Python\Python36\lib\site-packages\PIL\Image.py", line 2580, in open fp = builtins.open(filename, "rb") FileNotFoundError: [Errno 2] No such file or directory: 'frame_0000.png' Edit: Thanks to Benehiko it works fine now. Code: import pytesseract from PIL import Image import glob images = glob.glob('C:/Users/Artur/Desktop/Sequenz_1/*.png') for image in images: with open(image, 'rb') as file: img = Image.open(file) print(pytesseract.image_to_string(img))
type: Question
type: AnsweredQuestion
tagged with: python-imaging-library
has title: Iterate through folder with Pillow Image.open
accepted answer: http://stackoverflow.com/a/51178793
answer count: 1
downvote count: 0
favorite count: 0
tagged with: iteration
linked to: http://stackoverflow.com/q/18262293

http://stackoverflow.com/a/51236363
answers question: http://stackoverflow.com/q/51236287
score: 1
upvote count: 1
has body: My take uses zip to walk through the list by pairs, and is fairly terse. Like the others, it uses Counter, which I agree is the right tool for the job. from collections import Counter testlist = ['red','red','blue','red','red','black','yellow','black','yellow','blue'] def count_changes(data): c = Counter() c['key'] = 40006 for item1, item2 in zip(data, data[1:]): if item1 != item2: c[item2] += 1 return c print(count_changes(testlist)) Output: Counter({'key': 40006, 'blue': 2, 'black': 2, 'yellow': 2, 'red': 1}) It's unclear what the correct behavior should be if "key" appears in the testlist, but it would be straightforward to modify this code to handle that.
type: Answer
downvote count: 0

http://stackoverflow.com/q/51295904
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/89569305
has answer: http://stackoverflow.com/a/51296850
has answer: http://stackoverflow.com/a/51295978
type: UnansweredQuestion
has title: concat and append elements of array with several condition
tagged with: python
has comment: http://stackoverflow.com/comment/89569400
has comment: http://stackoverflow.com/comment/89569622
type: Question
has comment: http://stackoverflow.com/comment/89569350
score: 0
answer count: 2
upvote count: 1
has body: Moring guys. I have a question about how to append array elements with several condition. assume i've array like this: A=[[100,Z],[102,A],...,[9901,A]] and another array like this: B=[[100,-0.22,0.99],[102,-0.442,0.99],...,[9901,-1.22,4.99]] The length of array A and B are different. I want to append both the array elements with condition like this: if(A[0][0]==B[0][0]): temp = [B[0][1],B[0][2],A[0][1]] array_new.append(temp) I've try to append , and works , but the length of the new array is shorter than the A array. Is something wrong with my code? this is my code how I concat it: for g in range(len(A)): for h in range(len(B)): if(B[h][0]==A[g][0]): temp = [B[h][1],B[h][2],A[g][1]] array.append(temp) Thank you and have a nice day.

http://stackoverflow.com/comment/89424664
has text: @user1767754: python is not an interpreter. If you write `python` as command line, the interpreter is probably `CPython`.
comment on: http://stackoverflow.com/q/51221986
type: Comment
score: 1
type: QuestionComment

http://stackoverflow.com/comment/89630606
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51323574
has text: No sorry. The run was too fast to be executed in CPU so I debugged the code. The except catch the error but the dataset.repeat() doesn't do anything and basically, it doesn't work...

http://stackoverflow.com/a/51318354
type: Answer
downvote count: 0
score: 12
has body: There are four standard typ parameters: rt: (for round-trip) in this case the document is loaded in special types that preserve comments, etc., used for dumping. This is what ruamel.yaml was created for and this is the default (i.e. what you get if you don't specify typ). This is a subclass of the safe loader/dumper. safe: this only loads/dumps tagged objects, when these are explicitly registered with the loader/dumper unsafe: try to load/dump everything. Classes are automatically resolved to a tag of the form !!python/object:&lt;module&gt;/&lt;class&gt; base: the loader/dumper from which everything is derived. All scalars are loaded as strings (even the types like integer, float, Boolean that are handled specially as mentioned in the YAML specification or the type description For safe, unsafe, base there is the faster C Loader available. If you install from the .tar.gz file these will only get compiled during installation when the appropriate compiler is available. If they are not available, because they could not be compiled, then they cannot be used. There is no C version of the rt code. So it is not possible to use C libraries. The word pure is for when you use Python only modules. The opposite would be "tainted": Python tainted with C extension modules. There is no tainted=True parameter. This is implicit (when possible/available, see previous paragraph) when pure=true is not specified, as the default for pure is False In order to further confuse you: the above are the four basic (built-in) values for type. If you use plug-ins you can e.g. do yaml = YAML(typ='jinja2') as shown in this answer Some of the above information is available from the YAML() docstring, little of that however made it into the package documentation, primarily as a result of lazyness of ruamel.yaml's author.
has comment: http://stackoverflow.com/comment/89629081
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89633376
upvote count: 12
accepted answer of: http://stackoverflow.com/q/51316491
answers question: http://stackoverflow.com/q/51316491

http://stackoverflow.com/q/51256927
answer count: 2
has comment: http://stackoverflow.com/comment/89516816
tagged with: pandas
has title: One hot encoding in Python
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: machine-learning
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/52307049
has answer: http://stackoverflow.com/a/51257133
score: 1
has comment: http://stackoverflow.com/comment/89492837
has body: I'm trying to learn machine learning. I had a doubt about one hot encoding: I have a data set split into 2 excel sheets of data. One sheet has train and other has test data. I first trained my model by importing the train data sheet with pandas. There are categorical features in the data set that have to be encoded. I one hot encoded them. After importing the test dataset , if I one hot encode it, will the encoding be the same as of the train data set or will it be different. If so, how can I solve this issue?
type: Question

http://stackoverflow.com/comment/89493605
type: AnswerComment
has text: your right, I am wrong @ clockwatcher, it returned the Ventura line. THank you!!
comment on: http://stackoverflow.com/a/51257412
type: Comment
score: 0

http://stackoverflow.com/q/51225689
tagged with: python
tagged with: object-detection
answer count: 0
downvote count: 0
type: UnansweredQuestion
score: 1
tagged with: tensorflow
type: Question
has body: I'm currently trying to use the Object Detection framework from Google Tensorflow. I have a trained model for something similar to MNIST. What is the easiest way to use this as the classification checkpoint? As I currently understand it I can use a classification or an object detection checkpoint. Just don't know how to use my classification checkpoint as I think the structure of the network is specified by the type in feature_extractor { type: "ssd_mobilenet_v2" ... Do I have to provide my own model type using this? All of the pretrained models have a lot of layers and my MNIST like dataset has only 3 which was quite easy to train. The goal in general is to detect math symbols on a white background with bounding boxes. The classification part was easy but trying to extend it by object detection seems to hard. Using pretrained models for object detection which were trained on real world images seem to be better than scratch but pretty bad in general. Any ideas appreciated!
has title: Use classification model for object detection framework
upvote count: 1
favorite count: 0

http://stackoverflow.com/comment/89531238
type: QuestionComment
has text: One thing to look into is [pipenv](https://docs.pipenv.org/). It solves some of the issues with requirements.txt files and (like many other package managers) allows you to specify a dependency as a "dev dependency," which will only be installed in development.
type: Comment
score: 1
comment on: http://stackoverflow.com/q/51276429

http://stackoverflow.com/a/51192462
has comment: http://stackoverflow.com/comment/89369813
has comment: http://stackoverflow.com/comment/89366881
type: Answer
has comment: http://stackoverflow.com/comment/89369740
has body: Use: s = df.isnull().all(axis=1).sum(level=0) print (s) user user1 1.0 user2 1.0 user3 2.0 dtype: float64 If need DataFrame: df1 = df.isnull().all(axis=1).sum(level=0).astype(int).reset_index(name='count') print (df1) user count 0 user1 1 1 user2 1 2 user3 2 Explanation: First check NaNs values in all columns: print (df.isnull()) val1 val2 val3 user cat user1 cat1 False True True cat2 True True True cat3 True True False user2 cat1 True True True cat2 True False True cat3 True True False user3 cat1 False True True cat2 True True True cat3 True True True Then check all rows for all Trues by DataFrame.all: print (df.isnull().all(axis=1)) user cat user1 cat1 False cat2 True cat3 False user2 cat1 True cat2 False cat3 False user3 cat1 False cat2 True cat3 True dtype: bool And then sum boolean Trues like 1s by sum: print (df.isnull().all(axis=1).sum(level=0)) user user1 1.0 user2 1.0 user3 2.0 dtype: float64
score: 1
answers question: http://stackoverflow.com/q/51192398
upvote count: 1
has comment: http://stackoverflow.com/comment/89366925
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51192398

http://stackoverflow.com/comment/89610050
type: Comment
type: QuestionComment
has text: Please do not post error messages and code and data as images
score: 1
comment on: http://stackoverflow.com/q/51316973

http://stackoverflow.com/a/51275167
downvote count: 0
has comment: http://stackoverflow.com/comment/89528448
has comment: http://stackoverflow.com/comment/89528411
upvote count: 3
has comment: http://stackoverflow.com/comment/89528527
type: Answer
answers question: http://stackoverflow.com/q/51275134
has comment: http://stackoverflow.com/comment/89528513
score: 3
has body: Well, for one, in the Chrome console you can see that it's a POST request, and it appears you're performing a GET request in your Python code.
has comment: http://stackoverflow.com/comment/89528780
has comment: http://stackoverflow.com/comment/89528792
has comment: http://stackoverflow.com/comment/89528888
has comment: http://stackoverflow.com/comment/89528798
has comment: http://stackoverflow.com/comment/89528869

http://stackoverflow.com/q/51193354
has body: I have string, contains address str_addr = '300114 г Тула, Тульская область, Ленинский р-он, п РАССВЕТ, 75, к.34, тульская обл, Краснодарский край, гагарина 38, республика Хакасия' I need to extract Тульская, тульская, Краснодарский, Хакасия I try to use re.findall(r"\b[А-Я]\w*\s+(?:[кК]рай|[оО](бласть|бл))|\b[рР](еспублика|есп)\s+[А-Я]\w*", str_addr) but I get an empty list. How can I fix that?
score: 0
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/89368211
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51193464
upvote count: 1
downvote count: 1
type: Question
has title: Regex: extract all substrings with condition from string
has comment: http://stackoverflow.com/comment/89368230
has comment: http://stackoverflow.com/comment/89368205
answer count: 1
has answer: http://stackoverflow.com/a/51193464
favorite count: 0

http://stackoverflow.com/comment/89489497
has text: Also, please post the exact, complete error message the MCVE produces, including stack trace.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51255202
score: 0

http://stackoverflow.com/q/51208208
has body: summaries = [] texts = [] with open("C:\\Users\\apandey\\Documents\\Reviews.csv","r",encoding="utf8") as csvfile: reader = csv.reader(csvfile) for row in reader: clean_text = clean(row['Text']) clean_summary = clean(row['Summary']) summaries.append(word_tokenize(clean_summary)) texts.append(word_tokenize(clean_text)) I just want to tokenize row from csv file and I am getting this error: "list indices must be integers or slices, not str"
has comment: http://stackoverflow.com/comment/89397303
has comment: http://stackoverflow.com/comment/89397846
score: -1
has title: Python tokenizing words
has answer: http://stackoverflow.com/a/51209148
accepted answer: http://stackoverflow.com/a/51209148
tagged with: http://stackoverflow.com/tag/csv
answer count: 1
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/89398076
has comment: http://stackoverflow.com/comment/89397978
tagged with: python
has comment: http://stackoverflow.com/comment/89397254
has comment: http://stackoverflow.com/comment/89398242
type: AnsweredQuestion
upvote count: 0
has comment: http://stackoverflow.com/comment/89397387
tagged with: list
has comment: http://stackoverflow.com/comment/89397480
tagged with: tokenize
has comment: http://stackoverflow.com/comment/89397242
type: Question
has comment: http://stackoverflow.com/comment/89397962
tagged with: nltk

http://stackoverflow.com/comment/89377245
comment on: http://stackoverflow.com/q/51197607
score: 0
type: QuestionComment
type: Comment
has text: Also, if that was the case, why does it work locally but not on azure.

http://stackoverflow.com/q/51310638
tagged with: tensorflow
type: Question
has comment: http://stackoverflow.com/comment/89753794
score: 0
has body: I have created a Tensorflow model which uses the Dataset API in order to feed the data into the network. After the training phase, I would like to restore this model and to perform inference on it once in a while. Currently I am re initializing the dataset iterator each time, but I'm wondering if there is an alternative way. Moreover at training time, my dataset contains x and y data, while at prediction time I only have x. As a temporary solution, I am providing a fake y, but again, this does not seem the best solution. Here is a pseudocode of what i'm doing: #### NETWORK input_x = tf.placeholder(tf.int32, [None, None], name="input_x") input_y = tf.placeholder(tf.int32, [None, 2], name="input_y") dataset = tf.data.Dataset.from_tensor_slices((input_x, input_y)) iterator = tf.data.Iterator.from_structure(dataset.output_types, dataset.output_shapes) dataset_init_op = iterator.make_initializer(dataset, name='dataset_init') x_data, y_data = iterator.get_next() output = tf.variable(x_data, name='output') ..... ### INFERENCE while (true): x = new_input x_operation = session.graph.get_operation_by_name("input_x").outputs[0] y_operation = session.graph.get_operation_by_name("input_y").outputs[0] dataset_operation = session.graph.get_operation_by_name("dataset_init") output_operation = session.graph.get_operation_by_name("output").outputs[0] fake_y = np.array([[0, 0]]) dic = {input_x: x, input_y: y} session.run(dataset_operation, feed_dict=dic) prediction = session.run(output_operation) Thank you for your help
has title: Tensorflow interactive prediciton using dataset API
tagged with: tensorflow-datasets
answer count: 0
has comment: http://stackoverflow.com/comment/89771727
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/a/51297764
has comment: http://stackoverflow.com/comment/90268262
has comment: http://stackoverflow.com/comment/89572634
has comment: http://stackoverflow.com/comment/89572668
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89579053
accepted answer of: http://stackoverflow.com/q/51297320
has comment: http://stackoverflow.com/comment/89574987
answers question: http://stackoverflow.com/q/51297320
type: Answer
has body: If I understand your intent, F_ID is a string representation of a list? If so, lets convert it to actual lists: import numpy as np import pandas as pd df = pd.DataFrame({"ID": [2,3,4,5,6,7,8,9,10], "type" :["A", "B", "B", "A", "A", "B", "A", "A", "A"], "F_ID" :["0", "[7 8 9]", "[10]", "0", "[2]", "0", "0", "0", "0"]}) # convert the string representations of list structures to actual lists F_ID_as_series_of_lists = df["F_ID"].str.replace("[","").str.replace("]","").str.split(" ") #type(F_ID_as_series_of_lists) is pd.Series, make it a list for pd.DataFrame.from_records F_ID_as_records = list(F_ID_as_series_of_lists) f_id_df = pd.DataFrame.from_records(list(F_ID_as_records)).fillna(np.nan) f_id_df Now let's join the split F_IDs to the original DataFrame combined_df = df.merge(f_id_df, left_index = True, right_index = True, how = "inner") combined_df = combined_df.drop("F_ID", axis = 1).sort_values(["type", "ID"]) combined_df However we need to omit the F_IDs that appear as in ID within the same type, i.e. As 7 is an ID in type == "B" we want to exclude it where ID == 3 and type == "B", even though it is in the list of F_IDs. To achieve this let's create mapping of ID/type to F_ID. mapping_df = pd.DataFrame(combined_df.set_index(["ID", "type"]).stack()).reset_index().drop("level_2", axis = 1) mapping_df.columns = ["ID", "type", "F_ID"] mapping_df Now to do the filtering, we could probably do some impressive joining, but a query for this example is easier to read should we have to come back to this: def is_fid_of_same_type(row, df): query = "ID == {row_fid} &amp; type == '{row_type}'".format( row_fid = row["F_ID"], row_type = row["type"] ) matches_df = df.query(query) row["fid_in_type_id"] = len(matches_df) &gt; 0 return row Now apply this function to each row, and drop the rows that do appear as a F_ID as an ID within the same type. df = mapping_df.apply(lambda row: is_fid_of_same_type(row, mapping_df), axis = 1) df = df[df["fid_in_type_id"] == False].drop("fid_in_type_…
has comment: http://stackoverflow.com/comment/89572733
has comment: http://stackoverflow.com/comment/89573787
has comment: http://stackoverflow.com/comment/89573424

http://stackoverflow.com/q/51217663
tagged with: plot
score: 1
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/89416560
has title: Color specification for points when feeding a set of points to plot in matplotlib of python
type: Question
tagged with: colors
upvote count: 1
has comment: http://stackoverflow.com/comment/89416912
has body: The commented line does not give an error, but this is not what I want. The color needs to change for different points. def pplot(pdict,pembs,name='np'): fig=plt.figure(figsize=(24,24)) ax=plt.gca() ax.cla() ax.set_xlim((-1.1,1.1)) ax.set_ylim((-1.1,1.1)) ax.add_artist(plt.Circle((0,0),1.,color='black',fill=False)) c0=[itm[0] for itm in pembs] c1=[itm[1] for itm in pembs] ax.plot(c0,c1,'o',color=[idcolor.get(i,(0,0,0)) for i in getseg(pdict)],markersize=5) #ax.plot(c0,c1,'o',color=(0.0,0.0,0.0),markersize=5) txt_height = 0.04/10*(plt.ylim()[1] - plt.ylim()[0]) txt_width = 0.02/10*(plt.xlim()[1] - plt.xlim()[0]) text_positions = get_text_positions(c0, c1, txt_width, txt_height) text_plotter(getnps(pdict), c0,c1, text_positions, ax, txt_width, txt_height) c0 and c1 are vectors. Would I need to plot a point at a time? Really, there's no way to set color at one go? The error I get is. ValueError: to_rgba: Invalid rgba arg "[(0.6484375, 0.76953125, 0.421875), (0.64453125, 0.14453125, 0.69140625), (0.6484375, 0.76953125, 0.421875), (0.98828125, 0.14453125, 0.97265625), (0.29296875, 0.89453125, 0.94921875), (0.97265625, 0.64453125, 0.05078125), (0.32421875, 0.89453125, 0.79296875), (0.6484375, 0.76953125, 0.421875), (0.6484375, 0.76953125, 0.421875), (0.97265625, 0.64453125, 0.05078125), (0.6171875, 0.76953125, 0.578125), (0.9609375, 0.76953125, 0.859375), (0.64453125, 0.14453125, 0.69140625), (0.98828125, 0.14453125, 0.97265625), (0.96484375, 0.39453125, 0.58984375), (0.29296875, 0.89453125, 0.94921875), (0.98828125, 0.14453125, 0.97265625), (0.984375, 0.51953125, 0.2421875), (0.97265625, 0.64453125, 0.05078125), (0.30078125, 0.14453125, 0.41015625), (0.98828125, 0.14453125, 0.97265625), (0.6484375, 0.76953125, 0.421875), (0.6484375, 0.76953125, 0.421875), (0.3203125, 0.26953125, 0.0625), (0.97265625, 0.64453125, 0.05078125), (0.3203125, 0.26953125, 0.0625), (0.6484375, 0.76953125, 0.421875), (0.296875, 0.51953125, 0.6796875), (0.3203125, 0.26953125, 0.0625), (0.98828125,…
favorite count: 0
answer count: 0
downvote count: 0
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/89415595
comment on: http://stackoverflow.com/a/51217143
type: Comment
has text: the alternative (testing `port` as well) is tedious. I'd code that only if necessary. Doesn't seem to be the case.
type: AnswerComment
score: 0

http://stackoverflow.com/q/51274560
tagged with: python
type: AnsweredQuestion
type: Question
has body: I am trying to find Lasso.py on GitHub, I believe I should be able to find it at https://github.com/scikit-learn/scikit-learn/tree/main/sklearn/linear_model; but it is not there. Does anyone have an idea?
tagged with: lasso-regression
has answer: http://stackoverflow.com/a/51274617
tagged with: scikit-learn
score: 0
answer count: 1
has title: Lasso.py is not included in github.com/scikit-learn
accepted answer: http://stackoverflow.com/a/51274617

http://stackoverflow.com/comment/89581685
type: QuestionComment
has text: performance? You have may noticed many of the "everything is an object" languages are not actually efficient, CPU and memory wise. The only reason they appear okay is that many of the functions are hidden, implemented in other languages such as C - while Java does everything by itself, e.g. math, encoding conversion, string and collection operations, etc. However, it's actually possible with the bytecode form to support "everything is an object", by examining the use of certain variables/fields and transforming/JIT the code accordingly (primitive or object).
comment on: http://stackoverflow.com/q/51293294
score: 0
type: Comment

http://stackoverflow.com/q/51320227
possible better answer: http://stackoverflow.com/a/51320889
linked to: http://stackoverflow.com/q/37842165
has answer: http://stackoverflow.com/a/67802232
has answer: http://stackoverflow.com/a/51320889
has comment: http://stackoverflow.com/comment/112951882
type: AnsweredQuestion
type: Question
upvote count: 4
has comment: http://stackoverflow.com/comment/89616637
accepted answer: http://stackoverflow.com/a/51323796
tagged with: k-means
downvote count: 0
tagged with: scikit-learn
score: 4
favorite count: 0
has comment: http://stackoverflow.com/comment/126995567
answer count: 3
tagged with: python
has body: I want to classify Iris flower dataset (I removed labels though, so its an unlabeled data now) using sklearns k-means clustering function. I have made the prediction model and the output seems to be classifying the data correctly for the most part, however it is choosing the labels randomly (0, 1 and 2) and I cannot compare it to my own labels to determine the accuracy (I have marked setosa as 0, versicolor as 1, virginica as 2). Is there any way to correctly label the flowers? Heres the code: from sklearn.cluster import KMeans cluster = KMeans(n_clusters = 3) cluster.fit(features) pred = cluster.labels_ score = round(accuracy_score(pred, name_val), 4) print('Accuracy scored using k-means clustering: ', score) features, as expected contains the features, name_val is matrix containing flower values, 0 for setosa, 1 for versicolor, 2 for virginica Edit: one solution I came up with was setting random_state to any number so that the labeling is constant, is there any other solution?
has title: Determining accuracy for k-means clustering
has answer: http://stackoverflow.com/a/51323796

http://stackoverflow.com/q/51321575
tagged with: matplotlib
has answer: http://stackoverflow.com/a/51321715
downvote count: 1
type: Question
linked to: http://stackoverflow.com/q/27083051
has comment: http://stackoverflow.com/comment/89618849
score: 0
answer count: 2
has title: Simplest histogram with dates as x-axis in matplotlib
accepted answer: http://stackoverflow.com/a/51321715
favorite count: 0
possible better answer: http://stackoverflow.com/a/51321707
has body: I have been trying to properly display a simple histogram with dates as x-axis and integers as y-axis. The example below happens to be a subplot (2 y-axis, 1 shared x-axis) but the problem is not there, it's rather the hist itself. import datetime import matplotlib matplotlib.use('agg') # server no need to display graphics import matplotlib.pyplot as plt # x-axis is 3 consecutive dates (days) now = datetime.datetime.now().date() x = [now, now + datetime.timedelta(days=1), now + datetime.timedelta(days=2)] # y1-axis is 3 numbers y1 = [10, 0, 3] y2 = [8, 0, 3] fig, axarr = plt.subplots(2, sharex=True) bins = range(1, len(x) + 1) axarr[1].hist(y1, bins=len(x), edgecolor="k") axarr[1].set_xticks(bins) axarr[1].set_xticklabels(x) axarr[1].set_yticks(range(0, max(y1) + 1)) # axarr[0] ommitted for simplicity plt.savefig('a.png', bbox_inches='tight') However the image I get is ...
has answer: http://stackoverflow.com/a/51321707
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/89619213
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/29672375

http://stackoverflow.com/comment/89452813
type: AnswerComment
type: Comment
has text: @Mr.T You may use `s = ax.scatter(order, np.empty(len(order))*np.nan)` and then not remove anything. I don't think they hurt, but of course you have an extra artist in `ax.collections` and need to remember it being there for no reason, once this is relevant.
comment on: http://stackoverflow.com/a/51236684
score: 0

http://stackoverflow.com/q/51289763
score: 2
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/51311314
tagged with: python
has title: How to calculate the balancing of a matrix in python?
tagged with: stochastic-process
type: AnsweredQuestion
tagged with: mathematical-optimization
has body: I would like to perform a matrix balancing in python. I thought to use linalg.matrix_balance in order to make the input matrix a doubly stochastic matrix: from scipy import linalg import numpy as np x = np.array([[1,2,7], [9,1,1], [1,2,10*np.pi]]) y, permscale = linalg.matrix_balance(x) np.abs(x).sum(axis=0) / np.abs(x).sum(axis=1) np.abs(y).sum(axis=0) / np.abs(y).sum(axis=1) permscale array([[ 1., 0., 0.], [ 0., 2., 0.], [ 0., 0., 1.]]) It doesn't look that it actually balancing the rows and cols of the matrix. Any idea what should I do? If I do: y, permscale = linalg.matrix_balance(x, scale=False) The result isn't normalized either: array([[ 1. , 2. , 7. ], [ 9. , 1. , 1. ], [ 1. , 2. , 31.41592654]])
upvote count: 3
downvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/51311314
tagged with: math
tagged with: linear-algebra
has comment: http://stackoverflow.com/comment/89680433

http://stackoverflow.com/q/51313895
answer count: 2
possible better answer: http://stackoverflow.com/a/51314050
tagged with: while-loop
favorite count: 0
has comment: http://stackoverflow.com/comment/89604598
has comment: http://stackoverflow.com/comment/89635327
has body: I have a while loop that goes over a two-dimensional list, to see if it can find a similar submission for it to be removed. i=0 while i &lt;= len(my_list): if my_list[i] == userinput: del my_list[i] print("Entry Removed!") else: print("This publication does not exist") i+=1 What I wanted was for the code to print the message "This publication does not exist" if no matches were found. However, what happens right now is that everytime it compares an item, the code prints the sentence. I understand why this happens but I have no idea how to fix it. What is the best way of addressing this issue? EDIT: Changed list name from "list" to "my_list". My bad, I didn't actually call it that in the code, I just changed the name when uploading the question for ease of understanding.
tagged with: python-3.x
tagged with: python
has answer: http://stackoverflow.com/a/51313953
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89604528
has comment: http://stackoverflow.com/comment/89604562
has comment: http://stackoverflow.com/comment/89627436
tagged with: loops
downvote count: 1
type: Question
linked to: http://stackoverflow.com/q/3295938
tagged with: if-statement
has answer: http://stackoverflow.com/a/51314050
has title: Is it possible to make my else statement appear after the code is done checking every option?
upvote count: 5
score: 4
accepted answer: http://stackoverflow.com/a/51313953

http://stackoverflow.com/a/51240835
answers question: http://stackoverflow.com/q/51240796
type: Answer
has body: Problem is with duplicated data, need unique rows, so solution is remove dupes: student_vle = student_vle.drop_duplicates('id_student')
upvote count: 1
has comment: http://stackoverflow.com/comment/89460863
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51240796
score: 1

http://stackoverflow.com/comment/89601024
has text: What is dream_hand1?
type: Comment
comment on: http://stackoverflow.com/q/51312142
type: QuestionComment
score: 0

http://stackoverflow.com/comment/89321773
score: 0
has text: Thanks but I think we need to see the code that defines `entry` in the first place before passing it to this function. It seems that it is a newly-instantiated object, rather than one loaded from the db. Can you show the full flow?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51168175

http://stackoverflow.com/comment/89469804
has text: Give a simple and clear example, it's pretty confusing. Give us an example of inputs and the corresponding output
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51244013

http://stackoverflow.com/q/51245938
has comment: http://stackoverflow.com/comment/89470966
tagged with: python-datetime
tagged with: gregorian-calendar
has comment: http://stackoverflow.com/comment/89470544
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/89471403
favorite count: 0
has body: I have a vector of time in Gregorian type. I want to convert it in the common format of dates with year, month, day, hour, minute and seconds. I tried this: from datetime import datetime datetime.fromordinal(736364.94) It returns always something only with the information of year, month and day. Like this: datetime.datetime(2017, 2, 4, 0, 0) I was expecting a date with hours, minutes and seconds information
has answer: http://stackoverflow.com/a/59548872
tagged with: time
tagged with: datetime
tagged with: python
has title: How can I convert a gregorian time vector into datetime in Python?
has comment: http://stackoverflow.com/comment/89470689
type: UnansweredQuestion
score: 1
upvote count: 1
type: Question

python-requests
tags question: http://stackoverflow.com/q/51266928
tags question: http://stackoverflow.com/q/51268405
tags question: http://stackoverflow.com/q/51295586
tags question: http://stackoverflow.com/q/51181637
tags question: http://stackoverflow.com/q/51191625
tags question: http://stackoverflow.com/q/51176429
tags question: http://stackoverflow.com/q/51263978
type: Tag
tags question: http://stackoverflow.com/q/51201287
tags question: http://stackoverflow.com/q/51189327
tags question: http://stackoverflow.com/q/51183608
tags question: http://stackoverflow.com/q/51313195
tags question: http://stackoverflow.com/q/51273612
tags question: http://stackoverflow.com/q/51275134
tags question: http://stackoverflow.com/q/51191428
tags question: http://stackoverflow.com/q/51308375
tags question: http://stackoverflow.com/q/51264436
tags question: http://stackoverflow.com/q/51214794
tags question: http://stackoverflow.com/q/51213408
tags question: http://stackoverflow.com/q/51199996
tags question: http://stackoverflow.com/q/51214191
tags question: http://stackoverflow.com/q/51244373
tags question: http://stackoverflow.com/q/51190354
tags question: http://stackoverflow.com/q/51225763
tags question: http://stackoverflow.com/q/51210220
tags question: http://stackoverflow.com/q/51236461
tags question: http://stackoverflow.com/q/51245038
tags question: http://stackoverflow.com/q/51179961
tags question: http://stackoverflow.com/q/51205893
tags question: http://stackoverflow.com/q/51286018
tags question: http://stackoverflow.com/q/51289415
tags question: http://stackoverflow.com/q/51278403
tags question: http://stackoverflow.com/q/51185110
tags question: http://stackoverflow.com/q/51192165
tags question: http://stackoverflow.com/q/51315550
tags question: http://stackoverflow.com/q/51235402
tags question: http://stackoverflow.com/q/51322889
tags question: http://stackoverflow.com/q/51238014
tags question: http://stackoverflow.com/q/51302368
tags question: http://stackoverflow.com/q/51259693
tags question: http://stackoverflow.com/q/51194153
tags question: http://stackoverflow.com/q/51170871
tags question: http://stackoverflow.com/q/51256851
tags question: http://stackoverflow.com/q/51287953
tags question: http://stackoverflow.com/q/51230307
tags question: http://stackoverflow.com/q/51285853
tag name: python-requests
tags question: http://stackoverflow.com/q/51170000
tags question: http://stackoverflow.com/q/51190701
tags question: http://stackoverflow.com/q/51244689
tags question: http://stackoverflow.com/q/51179320
tags question: http://stackoverflow.com/q/51248455
tags question: http://stackoverflow.com/q/51245651
tags question: http://stackoverflow.com/q/51188661
tags question: http://stackoverflow.com/q/51192866
tags question: http://stackoverflow.com/q/51276426
tags question: http://stackoverflow.com/q/51176474
tags question: http://stackoverflow.com/q/51266656
tags question: http://stackoverflow.com/q/51238905
tags question: http://stackoverflow.com/q/51219664
tags question: http://stackoverflow.com/q/51257735
tags question: http://stackoverflow.com/q/51209475

http://stackoverflow.com/q/51309901
has comment: http://stackoverflow.com/comment/89597228
has answer: http://stackoverflow.com/a/51310533
type: Question
type: AnsweredQuestion
has body: So I have a directory of .txt files ~~~ c:\users\Admin\Documents\Exm ~~~ Each .txt file is extensive and I need to find certain sub-strings contained in each file ('Apple', 'Pear', 'Orange', etc). My understanding is that I need a [for loop] to iterate through the directory AND another [for loop] to iterate through each .txt file. ~~~ OBJECTIVE: a list of the first sub-string found in each .txt file. So if 'apple' is found first in 1.txt and 'pear' is found first in 2.txt the list would like like the following: ['apple', 'pear',...,'n-th fruit'] ~~~ This is what I have so far: ~~~ import glob import os names = os.listdir('c:\\users\Admin\Documents\Exm') lst = [] lst_2 =[] #Appends lst with all newly converted .txt Files (from .SIF files) for name in names: if name.endswith(".txt"): lst.append(name) #PROBLEM STARTS HERE - Intended to open each .txt file in directory for file in names: #Quick file verification (not each file is a .txt if file.endswith('.txt.'): #Opens a single .txt file in directory with open(os.path.join('c:\\users\Admin\Documents\Exm', file)) as f: #Iterates through each line in .txt file for line in f: #Temporary String placeheader for further checking content = f.readlines() if content = 'Apple' : lst_2.append('Apple') elif content = 'Pear' : lst_2.append('Pear') elif content = 'Orange' : lst_2.append('Orange') else: lst_2.append('Fruit not Found') print(lst_2) ~~~ Thank you for your assistance
has title: Python - Folder of long .txt files, search through each .txt file for various substrings, append to list
tagged with: for-loop
has comment: http://stackoverflow.com/comment/89596372
answer count: 1
accepted answer: http://stackoverflow.com/a/51310533
tagged with: directory
score: 0
tagged with: python
has comment: http://stackoverflow.com/comment/89597030
has comment: http://stackoverflow.com/comment/89596970
tagged with: list

http://stackoverflow.com/comment/89542871
type: Comment
comment on: http://stackoverflow.com/a/51267059
score: 1
has text: https://shinesolutions.com/2017/03/23/triggering-dataflow-pipelines-with-cloud-functions/
type: AnswerComment

http://stackoverflow.com/comment/89462190
has text: no images please. SO is about code, your document is useless here.
comment on: http://stackoverflow.com/q/51240720
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/89366489
type: AnswerComment
comment on: http://stackoverflow.com/a/51192344
has text: Or just `np.dstack((a, b))`, though it's only a wrapper around concatenate
type: Comment
score: 1

http://stackoverflow.com/comment/89605594
type: QuestionComment
score: 1
has text: here's [a steam community link](https://steamcommunity.com/app/585410/discussions/0/1484356232250432696/). Post #4 has something to try: "I had the same problem. I fixed it by going to file -> preferences -> runtime feeds and updating my runtime and deleting the old runtime. I hope this helped. "
type: Comment
comment on: http://stackoverflow.com/q/51313850

http://stackoverflow.com/q/51178100
tagged with: apache-kafka
answer count: 0
tagged with: multiprocessing
type: Question
score: 2
downvote count: 0
tagged with: amazon-ec2
has body: I have developed a Kafka consumer in python using python-kafka library in my local machine.My requirement is to read from 100+ topics. I have used multiprocessing module to create pool of workers for reading topics and writing to database. I have a EC2 instance and I need to know best way to scale my application ?? Like read topics in parallel...
has title: Scaling Kafka Consumer in AWS
favorite count: 0
has comment: http://stackoverflow.com/comment/89359415
upvote count: 2
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/a/51264789
answers question: http://stackoverflow.com/q/51264748
type: AcceptedAnswer
has body: Use map by Series but first remove column item_id by drop or pop: s = df_bill['item_id'].map(df_item.set_index('item_id')['item_name']) df = df_bill.drop('item_id', 1).assign(item_name = s) Or: s = df_bill.pop('item_id').map(df_item.set_index('item_id')['item_name']) df = df_bill.assign(item_name = s) print (df) bill_no item_name 0 201 Vegetables 1 202 Noodles 2 203 Dairy Products 3 204 Vegetables 4 205 Ice Cream
upvote count: 5
type: Answer
downvote count: 0
score: 5
accepted answer of: http://stackoverflow.com/q/51264748

http://stackoverflow.com/q/51239214
score: 2
downvote count: 0
tagged with: hook
has answer: http://stackoverflow.com/a/51240825
has body: I have a python service which may be ended by exception - I'm ok with it. But the problem is that it spawned an child process which continues to run even it's parent got a fail. import multiprocessing as mp from time import sleep import os import atexit import psutil @atexit.register # Doesn't fired at exception def goodbye(): current_process = psutil.Process() children = current_process.children(recursive=True) for child in children: print('Kill child with pid {}'.format(child.pid)) try: child.terminate() except: pass print("You are now leaving the Python sector.") def func(): # Child process while True: ppid = os.getppid() print("Parent process id:", ppid) if ppid == 1: print("Parent process has terminated") break sleep(1) t = mp.Process(target=func, args=()) t.start() print(9 + "0") # Exception here print("I'm ok") And service continues to work (formally) until it got a kick from outside: Parent process id: 29118 Traceback (most recent call last): File "stestcp.py", line 32, in &lt;module&gt; print(9 + "0") # Exception here TypeError: unsupported operand type(s) for +: 'int' and 'str' Parent process id: 29118 Parent process id: 29118 Parent process id: 29118 Parent process id: 29118 Parent process id: 29118 ^CError in atexit._run_exitfuncs: Traceback (most recent call last): File "/usr/lib/python3.6/multiprocessing/popen_fork.py", line 28, in poll Process Process-1: pid, sts = os.waitpid(self.pid, flag) KeyboardInterrupt Traceback (most recent call last): File "/usr/lib/python3.6/multiprocessing/process.py", line 258, in _bootstrap self.run() File "/usr/lib/python3.6/multiprocessing/process.py", line 93, in run self._target(*self._args, **self._kwargs) File "stestcp.py", line 27, in func sleep(1) KeyboardInterrupt Kill child with pid 29119 You are now leaving the Python sector. The question is - is there any way to call some global fallback function (like atexit) when program failed with exception?
tagged with: multiprocessing
type: Question
upvote count: 2
answer count: 1
favorite count: 0
tagged with: exception
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/9741351
tagged with: python
has title: Exit child process when main process ended by unhandled exception
has comment: http://stackoverflow.com/comment/89457458

http://stackoverflow.com/comment/89559971
type: Comment
score: 2
comment on: http://stackoverflow.com/a/51291063
has text: Post-mortem debugging is going to enter the (usually dead) stack frame where the exception was raised, rather than the stack frame where the `post_mortem` call occurs, though. In this case, those happen to be the same frame, but they usually won't be the same.
type: AnswerComment

http://stackoverflow.com/comment/89495491
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51257776
has text: Then you should indicate it in your question, if you do not indicate it, we will assume that you have not done it, on the other hand you should indicate how you installed kivy, the version of kivy and cython that you have installed.
score: 0

http://stackoverflow.com/comment/89339522
has text: The last two lines of your code.... is that valid syntax? This may lead to why you're not finding any matches in your search.
type: QuestionComment
comment on: http://stackoverflow.com/q/51178459
type: Comment
score: 1

http://stackoverflow.com/comment/89321839
comment on: http://stackoverflow.com/q/51167814
score: 0
type: Comment
type: QuestionComment
has text: sorry i got confused. it was `visvis.clim(0,500)`

http://stackoverflow.com/a/51202323
score: 0
type: Answer
has body: I think you are looking for some sort of stack method rather than iteration (generally, when working with dataframes, iteration is a last resort, as there are usually vectorized methods to achieve most data reorganization tasks). Take the example dataframe: &gt;&gt;&gt; df 0 1 2 \ 0 Consumer Products Consumer Products Financial Services 1 Collaboration Future of Supply Chains Financial Services 2 Financial Services Consumer Products Collaboration 3 Collaboration Financial Services Future of Supply Chains 4 Consumer Products Future of Supply Chains Financial Services Pageviews 0 1210 1 1528 2 1716 3 1403 4 1090 You can do the following: new_df = (df.set_index('Pageviews') .stack() .reset_index(0)) &gt;&gt;&gt; new_df Pageviews 0 0 1210 Consumer Products 1 1210 Consumer Products 2 1210 Financial Services 3 1528 Collaboration 4 1528 Future of Supply Chains 5 1528 Financial Services 6 1716 Financial Services 7 1716 Consumer Products 8 1716 Collaboration 9 1403 Collaboration 10 1403 Financial Services 11 1403 Future of Supply Chains 12 1090 Consumer Products 13 1090 Future of Supply Chains 14 1090 Financial Services
has comment: http://stackoverflow.com/comment/89385937
answers question: http://stackoverflow.com/q/51202238
has comment: http://stackoverflow.com/comment/89385917

http://stackoverflow.com/q/51219958
has title: Dataframe becomes Nonetype after first loop
score: 0
has comment: http://stackoverflow.com/comment/89421546
tagged with: pandas
has body: After the first for loop runs once contDF is set to a Nonetype object. Thus it runs into a problem since contDF[col] does not exist the second loop. At the end of the first loop contDF is correct. Some how it becomes none when the second loop starts. def Lable_Controls_and_Exper(colum_name, list_values_to_determine_control, list_values_to_determine_exper): contDF = copy.deepcopy(masterDF) for col in colum_name: index = 0 print(col+':') print(contDF) print(contDF[col]) for element in contDF[col]: #print(index) #if list values match a row in a column then the row is excluded for value in list_values_to_determine_control: if(element == value and contDF.loc[index,'control_or_experiment'] != 'exper'): contDF.loc[index,'control_or_experiment'] = 'control' for value in list_values_to_determine_exper: if(element == value): contDF.loc[ index, 'control_or_experiment' ] = 'exper' index = index + 1 print(contDF) print(contDF[col]) Here is the output. depression_bipolar_schizophrenia: #SampleID age_years antibiotic_history \ 0 10317.000049761 52 I have not taken antibiotics in the past year. 1 10317.000040165 32 I have not taken antibiotics in the past year. 2 10317.000030322 43.0 I have not taken antibiotics in the past year. 3 10317.000028857 56.0 I have not taken antibiotics in the past year. 4 10317.000038189 39.0 I have not taken antibiotics in the past year. 5 10317.000001281 61.0 I have not taken antibiotics in the past year. 6 10317.000036487 46.0 I have not taken antibiotics in the past year. bmi_cat depression_bipolar_schizophrenia \ 0 Overweight Unspecified 1 Unspecified Unspecified 2 Normal I do not have this condition 3 Overweight I do not have this condition 4 Overweight Unspecified 5 Unspecified Unspecified 6 Obese I do not have this condition mental_illness_type_depression smoking_frequency control_or_experiment 0 Unspecified Never none 1 Unspecified Never none 2 Unspecified Never none 3 Unspecified Never none 4 Unspecified Never none 5 Unspecified Never none 6 U…
answer count: 1
has answer: http://stackoverflow.com/a/51221109
type: UnansweredQuestion
tagged with: python
type: Question

http://stackoverflow.com/q/51201364
tagged with: matplotlib
tagged with: gradient
has title: Plot gradient arrows over heatmap with plt
has answer: http://stackoverflow.com/a/51202012
type: Question
tagged with: imshow
has body: I am trying to plot arrows to visualize the gradient over a heatmap. This is the code I have until now: import matplotlib.pyplot as plt import numpy as np function_to_plot = lambda x, y: x + y ** 2 horizontal_min, horizontal_max, horizontal_stepsize = 0, 3, 0.3 vertical_min, vertical_max, vertical_stepsize = 0, 3, 0.6 xv, yv = np.meshgrid(np.arange(horizontal_min, horizontal_max, horizontal_stepsize), np.arange(vertical_min, vertical_max, vertical_stepsize)) result_matrix = function_to_plot(xv, yv) xd, yd = np.gradient(result_matrix) def func_to_vectorize(x, y, dx, dy, scaling=1): plt.arrow(x + horizontal_stepsize/2, y + vertical_stepsize/2, dx*scaling, dy*scaling, fc="k", ec="k", head_width=0.1, head_length=0.1) vectorized_arrow_drawing = np.vectorize(func_to_vectorize) plt.imshow(result_matrix, extent=[horizontal_min, horizontal_max, vertical_min, vertical_max]) vectorized_arrow_drawing(xv, yv, xd, yd, 1) plt.colorbar() plt.show() This is the resulting plot: I was expecting the arrows to point toward the rectangles with greatest values, but they aren't. What am I missing?
downvote count: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/51202012
favorite count: 0
tagged with: python
type: AnsweredQuestion
score: 3
upvote count: 3

http://stackoverflow.com/a/51269893
has body: python label_image.py --image cat3.jpg --graph retrained_graph.pb --labels retrained_labels.txt --input_layer=Placeholder This command, the problem was solved.
answers question: http://stackoverflow.com/q/51269683
score: 0
type: Answer

getattr
tags question: http://stackoverflow.com/q/51270662
tag name: getattr
type: Tag

http://stackoverflow.com/comment/89346291
score: 0
type: Comment
has text: hey thanks a lot! i'll try it now. what if the wordlist and testlist is the same, because they are in my case? i don't have a separate testlist.
type: AnswerComment
comment on: http://stackoverflow.com/a/51181841

http://stackoverflow.com/q/51203839
answer count: 3
tagged with: python
tagged with: jupyter
linked to: http://stackoverflow.com/q/9012487
tagged with: jupyter-notebook
has answer: http://stackoverflow.com/a/51203872
tagged with: plot
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/51203872
upvote count: 5
tagged with: matplotlib
type: Question
has title: Python saving empty plot
has answer: http://stackoverflow.com/a/51203861
has body: EDIT: This question is a duplicate. Original question's link is posted above. I am using Python to plot a set of values which are showing good on the Python terminal (using Jupyter NoteBook) but when I save it, the saved file when opened shows an empty (completely white) photo. Here's my code: import matplotlib.pyplot as plt plt.plot([1,3,4]) plt.show() plt.savefig('E:/1.png')
score: 5
duplicate of: http://stackoverflow.com/q/9012487
has answer: http://stackoverflow.com/a/51203929
downvote count: 0
accepted answer: http://stackoverflow.com/a/51203861
favorite count: 0

http://stackoverflow.com/comment/89475706
type: Comment
type: QuestionComment
score: 1
has text: Yes working great, the problem was the path. Solved.
comment on: http://stackoverflow.com/q/51245502

http://stackoverflow.com/a/51428746
downvote count: 0
has body: You need to parse the message you received and attach it to the dom! ws.onmessage = function (event) { try { var obj = JSON.parse(event.data); document.getElementById("message-1").innerHTML = obj.first_name; document.getElementById("message-2").innerHTML = obj.second_name; document.getElementById("message-3").innerHTML = obj.titles.join(" "); } catch { console.log("Object is not received, Message is:: ", event.data); } } If this is not working, then check the json format your are sending! Remember JSON Needs to be valid json, Replace ' (single-quote) with " (double-quote): d = { "first_name": "Guido", "second_name": "Rossum", "titles": ["BDFL", "Developer"] }
answers question: http://stackoverflow.com/q/51323651
accepted answer of: http://stackoverflow.com/q/51323651
upvote count: 2
type: AcceptedAnswer
type: Answer
score: 2

http://stackoverflow.com/comment/89343512
score: 0
type: AnswerComment
has text: Have you used my last code ?, I get the following https://imgur.com/a/4OYMkvs I have added a print, copy again my code I have indicated to me that you get in the print
type: Comment
comment on: http://stackoverflow.com/a/51180058

http://stackoverflow.com/a/51205076
type: Answer
answers question: http://stackoverflow.com/q/51204227
has body: Created two dicts: old_new_dict to traverse from old to new name and old_new_dict_rev to traverse from new to old name : old_new_dict = {k:v for k,v in zip(df.old_name,df.new_name)} old_new_dict_rev = {v:k for k,v in zip(df.old_name,df.new_name)} Function find_tree, traverses in both direction and joins them to create the full path of names. def find_tree(name): left_list = [] right_list = [] name_l, name_r = name, name while(name_l in old_new_dict_rev): left_list.append(old_new_dict_rev[name_l]) name_l = old_new_dict_rev[name_l] left_list.reverse() while(name_r in old_new_dict): right_list.append(old_new_dict[name_r]) name_r = old_new_dict[name_r] return "-".join(left_list + [name] + right_list) Add the full path as name column in dataframe df: df['name'] = df['old_name'].apply(lambda x: find_tree(x)) end_df = df.drop(['old_name','new_name'], axis = 1) end_df # dt name #0 01/01/2001 AAA-BBB-CCC-DDD #1 02/02/2002 AAA-BBB-CCC-DDD #2 03/03/2003 AAA-BBB-CCC-DDD #3 02/01/2001 XXX-YYY-ZZZ #4 03/02/2002 XXX-YYY-ZZZ
score: 0

http://stackoverflow.com/q/51181824
has answer: http://stackoverflow.com/a/51181830
score: 1
upvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/51181830
has body: I am trying to find out if a number is a palindrome. My code is: max = 10 ** n length = 0 total = 0 for i in range (max): if i == i[::-1]: total += 1 if len(i) == n: length += 1 The line if i == i[::-1]: gives the error TypeError: 'int' object is not subscriptable. n is an integer.
tagged with: int
possible better answer: http://stackoverflow.com/a/51181838
answer count: 2
has answer: http://stackoverflow.com/a/51181838
downvote count: 0
favorite count: 0
tagged with: python-3.x
tagged with: python
has title: TypeError: 'int' object is not subscriptable when reversing a number
has comment: http://stackoverflow.com/comment/89345985
type: AnsweredQuestion

http://stackoverflow.com/q/51179109
has body: I write a module for Salt. By the documentation it adds __salt__ object into builtins. So, pyflake warn me that __salt__ is undefined when I run prospector and mypy says the same, that __salt__ is undefined! I can ignore either for pyflake with # noqa: F821 or for mypy with # type: ignore on that line. The question is! How to ignore for both of them?
has title: Set pyflake AND mypy ignore same line
has comment: http://stackoverflow.com/comment/89355214
has answer: http://stackoverflow.com/a/51200080
downvote count: 0
answer count: 1
upvote count: 55
favorite count: 0
accepted answer: http://stackoverflow.com/a/51200080
tagged with: python
has comment: http://stackoverflow.com/comment/89340689
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89341050
type: Question
tagged with: mypy
tagged with: pyflakes
score: 55

http://stackoverflow.com/comment/89450456
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51235503
has text: Thanks for your time and efforts @PRMoureu. Surely will not multiple questions in one.
score: 0

http://stackoverflow.com/q/51306399
has answer: http://stackoverflow.com/a/57080255
has body: Currently I'm trying to have the speech_recognition module listen in the background when the user pushes a button made with py qt. I have the initialization and callback methods in a class, however when I try and listen to the microphone it doesn't seem to be registering anything, not even outputting errors. class VoiceRecognitionWidget(ScriptedLoadableModuleWidget): def callback(self, recognizer, audio): try: print(recognizer.recognize_google(audio)) # handles any api/voice errors errors except sr.RequestError: print( "There was an issue in handling the request, please try again") except sr.UnknownValueError: print("Unable to Recognize speech") def onApplyButton(self): #self.displayLabel.setText("Listening for speech....") self.recognizer = sr.Recognizer() try: self.microphone = sr.Microphone() except(IOError): print("ERROR: No default microphone. Check if microphone is plugged in or if you have a default microphone set in your sound settings.") self.errors.setText("ERROR: No default microphone. Check if your microphone is plugged in or if you have a default microphone set in your sound settings.") with self.microphone as source: self.recognizer.adjust_for_ambient_noise(source) # audio = self.recognizer.listen(source) stop_listening = self.recognizer.listen_in_background(self.microphone, self.callback) The microphone works when I just listen to it normally when I press the button, it's just that when I try to have it continuously listen it doesn't seem to do anything. I also tried creating the recognizer and microphone in a function in the same class that initializes the whole GUI (not shown) but that didn't work either. Any help would be appreciated.
favorite count: 0
type: UnansweredQuestion
tagged with: python
score: 2
downvote count: 0
tagged with: google-speech-api
type: Question
has title: Python Speech Recognition listen_in_background on button press?
upvote count: 2
answer count: 1

http://stackoverflow.com/q/51216719
upvote count: 2
answer count: 1
has comment: http://stackoverflow.com/comment/89415937
has comment: http://stackoverflow.com/comment/89415470
favorite count: 0
downvote count: 5
score: -3
tagged with: python
has comment: http://stackoverflow.com/comment/89414800
has body: The Logic I'm attempting to implement: if the user doesn't upload a file to a Filefield thus leaving it empty, then don't upload the file to the S3 bucket or create a link to it. Line 8/9 doesn't do what I expected cause it still uploads empty files to the bucket & creates a link to it on my ticket. uploads = [['frontview', 'upload', 'Frontview: '],['backview', 'upload2', 'Backview: '], ['electricalsupply', 'upload3', 'Electrical Supply: '], ['fullstructure', 'upload4', 'Full Structure: '], ['controlroom', 'upload5', 'Control Room: '], ['otherdoc', 'upload6', 'Other Documentation: '], ['customersignoff', 'upload7', 'Customer Sign-Off: ']] file_upload_urls = [] folder = str(datetime.datetime.now()).replace(' ', '') + '/' # sets folder to the current date & time while getting rid of spaces & adding forward slash for linking purposes for upload in uploads: #loops through uploads array files = request.files.getlist(upload[1]) section_urls = [] for file in files: #loops through uploads array more specifically each File (upload, upload2, upload3, etc) if file not in request.files: filename = str(upload[0] + '_' + file.filename).replace(' ', '') section_urls.append(current_app.config['NEVCODOCS_BASE_URL'] + folder + filename) path = "ServiceRegistration/" + folder + filename s3.Bucket('nevcodocs').put_object(Key=path, Body=file) file_upload_urls.append([upload[2], section_urls]) ​ # Installation photos are placed in an unordered list & formats links of photos for ticket submission for section in file_upload_urls: ticket_html = ticket_html + section[0] + ' ' for url in section[1]: ticket_html = ticket_html + ' <href=' + url + '">' + url + '</href> ' ticket_html = ticket_html + ' ' The code below is a snippet from above, but I figured I would add the entire function for context. My intended function would be: While looping through each FileField, retrieve the data of each FileField, and run a check to see if a file was uploaded in each field. If there's data, then upload tha…
type: AnsweredQuestion
tagged with: flask-wtforms
has title: How to implement if file in request.files is not empty
type: Question
has answer: http://stackoverflow.com/a/51251749
accepted answer: http://stackoverflow.com/a/51251749
has comment: http://stackoverflow.com/comment/89414704
has comment: http://stackoverflow.com/comment/89415158
has comment: http://stackoverflow.com/comment/89414910
tagged with: flask
has comment: http://stackoverflow.com/comment/89414938

http://stackoverflow.com/a/51221041
accepted answer of: http://stackoverflow.com/q/51218962
score: 7
has comment: http://stackoverflow.com/comment/89443574
downvote count: 0
upvote count: 7
type: AcceptedAnswer
has body: Using subplots_adjust goes in the right direction. Don't use tight_layout afterwards as this would overwrite any settings done via subplots_adjust. You may decide to opt for something like fig.subplots_adjust(left=0.2, bottom=0.2) to make some space for the inset in the lower left corner of the figure. Then you need to position the inset. Since here you're working in the lower left corner, this is relatively easy. The loc parameter needs to be set to the lower left corner and you may stick to the bbox_to_anchor=(0,0) position. Then just add some padding via borderpad=3 (in units of font size), such that the inset axes' labels are still visible, zoomed_inset_axes(ax, 2, loc='lower left', bbox_to_anchor=(0,0), borderpad=3) Complete code: import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1.inset_locator import zoomed_inset_axes, mark_inset X = np.random.normal(.5,10,1000) Y = np.random.normal(.5,10,1000) fig, ax = plt.subplots(1, figsize=(10,6)) fig.subplots_adjust(left=0.2, bottom=0.2) ax.scatter(X,Y) # # Setup zoom window axins = zoomed_inset_axes(ax, 2, loc='lower left', bbox_to_anchor=(0,0), borderpad=3) mark_inset(ax, axins, loc1=2, loc2=4, fc="none", ec="0.5") axins.set_xlim([-15,0]) axins.set_ylim([-12,-3]) # # Plot zoom window axins.scatter(X,Y) #fig.savefig('test.png', dpi=70) plt.show() In general, you have a lot of options to position and size the inset. I recently created a new example on the matplotlib page: Inset Locator Demo, which is currently only available in the devdocs, to show the interplay between the different parameters (in that case for inset_axes - but it totally applies to zoomed_inset_axes as well).
answers question: http://stackoverflow.com/q/51218962
type: Answer

http://stackoverflow.com/comment/89541020
score: 0
type: Comment
has text: @JonClements -I add it to answer, hard question, it depends of data.
comment on: http://stackoverflow.com/a/51281345
type: AnswerComment

exe
tags question: http://stackoverflow.com/q/51192565
tags question: http://stackoverflow.com/q/51228874
type: Tag
tags question: http://stackoverflow.com/q/51312059
tags question: http://stackoverflow.com/q/51178115
tag name: exe
tags question: http://stackoverflow.com/q/51289247
tags question: http://stackoverflow.com/q/51281482
tags question: http://stackoverflow.com/q/51197350
tags question: http://stackoverflow.com/q/51301401
tags question: http://stackoverflow.com/q/51323958
tags question: http://stackoverflow.com/q/51273113

http://stackoverflow.com/comment/89479761
type: AnswerComment
has text: You will either need to include a blank icon and link to that icon, or embed a blank icon into the code, as indicated in the numerous answers given in the link above.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51250382

http://stackoverflow.com/a/51208677
has comment: http://stackoverflow.com/comment/89398212
upvote count: 8
has body: Unfortunately timedelta doesn't support a vectorized form so I would go for an apply df["First_day_of_the_week"] = df.apply(lambda x: x['Date'] - timedelta(days=x['Day_of_Week']), axis=1) EDIT timedelta doesn't support vectorized arguments but can be multiplied by a vector :) df["First_day_of_the_week"] = df.Date - df.Day_of_Week * timedelta(days=1)
has comment: http://stackoverflow.com/comment/89398451
type: Answer
accepted answer of: http://stackoverflow.com/q/51208570
score: 8
has comment: http://stackoverflow.com/comment/89398849
has comment: http://stackoverflow.com/comment/89398649
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51208570

http://stackoverflow.com/comment/89350478
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51183477
has text: Hi, have you had a look at the examples at https://github.com/IBMDecisionOptimization/Decision-Optimization-with-CPO-samples ?
type: Comment

http://stackoverflow.com/q/51284059
has comment: http://stackoverflow.com/comment/89545370
has title: Problems with printing variables with successive names
has body: I am new to Python so apologies in advance. Here is the code that I have problems with: x = 1 v1 = "First" v2 = "Second" v3 = "Third" v4 = "Forth" v5 = "Fifth" v6 = "Sixth" v7 = "Seventh" v8 ="Eighth" v9 = "Ninth" v10 = "Tenth" for x in range (1,11): print("v"+str(x)) This is the returned result: v1 v2 v3 v4 v5 v6 v7 v8 v9 v10 And this is what I want the returned result to be: First Second Third Fourth Fifth Sixth Seventh Eighth Ninth Tenth How could I print the content of increasingly named variables?
has answer: http://stackoverflow.com/a/51284121
favorite count: 0
answer count: 9
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/1373164
tagged with: python
has answer: http://stackoverflow.com/a/51284105
score: 2
has comment: http://stackoverflow.com/comment/89545366
has answer: http://stackoverflow.com/a/51284378
downvote count: 2
has answer: http://stackoverflow.com/a/51284178
has answer: http://stackoverflow.com/a/51284189
has answer: http://stackoverflow.com/a/51284257
has answer: http://stackoverflow.com/a/51284087
type: Question
has answer: http://stackoverflow.com/a/51284271
duplicate of: http://stackoverflow.com/q/1373164
has answer: http://stackoverflow.com/a/51284127
upvote count: 4

http://stackoverflow.com/q/51173298
has answer: http://stackoverflow.com/a/51173978
tagged with: linux
answer count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/89329676
favorite count: 0
has title: Parse Linux Command with Python
has comment: http://stackoverflow.com/comment/89329953
upvote count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/51173714
type: AnsweredQuestion
score: 1
has body: Here's a quick snippet of my code using pexpect: child.expect('tc@') child.sendline('ps -o args | grep lp_ | grep -v grep | sort -n') child.expect('tc@') print(child.before) child.sendline('exit') and then the output: user@myhost:~/Python$ python tctest.py tc-hostname:~$ ps -o args | grep lp_ | grep -v grep | sort -n /usr/local/bin/lp_server -n 5964 -d /dev/usb/lp1 /usr/local/bin/lp_server -n 5965 -d /dev/usb/lp0 {lp_supervisor} /bin/sh /usr/local/lp/lp_supervisor /dev/usb/lp0 SERIAL#1 /var/run/lp/lp_pid/usb_lp0 {lp_supervisor} /bin/sh /usr/local/lp/lp_supervisor /dev/usb/lp1 SERIAL#2 /var/run/lp/lp_pid/usb_lp1 user@myhost:~$ There's 4 lines of output. The first two lines show with printer port the usb device is assigned to (EX: first line shows port 5964 is assigned to lp1) The 3rd and 4th lines show which device serial number is assigned to which usb port. (EX: SERIAL#1 is assigned to lp0) I need to somehow parse that output so I can do the following: If SERIAL#1 is not assigned to 5964: run some command else: do something else If SERIAL#2 is not assigned to 5965: run some command else: do something else I'm not sure how to manipulate that output so I can get the desired variables. Any help is appreciated.
type: Question
has comment: http://stackoverflow.com/comment/89329893
possible better answer: http://stackoverflow.com/a/51173978
has answer: http://stackoverflow.com/a/51173714

http://stackoverflow.com/comment/89569166
type: QuestionComment
score: 2
has text: If you just don't understand what a particular function does, like `enumerate` (I'm just guessing at what you're question is here, so apologies if I'm wrong), [look it up in the docs](https://docs.python.org/3/library/functions.html#enumerate). If you _still_ don't understand it after reading the docs, or if you understand it in general but not how it applies in some line of code, then you can ask a specific question that can be easily answered.
comment on: http://stackoverflow.com/q/51295832
type: Comment

http://stackoverflow.com/a/51217643
type: Answer
has body: You just need to check whatever value you get back for 999999_999. It's simpler if you use the get method to "pretend" that a missing URL is a string that will match. # This assumes that you want the top-level imageURL in preference to # the product imageURL... def get_url(d): for item in d['threads'], d['threads']['product']: url = item.get('imageUrl', '999999_999') if not re.match('999999_999', url): return url As you can see, it's also simpler to just pretend that the second try could match 999999_999, even if you know it won't.
upvote count: 1
score: 1
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51217534
answers question: http://stackoverflow.com/q/51217534

http://stackoverflow.com/q/51306328
has title: Can't create sidebars in Python Sphinx html output?
tagged with: python
has comment: http://stackoverflow.com/comment/89663782
favorite count: 0
answer count: 0
tagged with: python-sphinx
type: UnansweredQuestion
has body: I'm documenting my Python project using Sphinx tool and my HTML output currently looks like this: As you can see the tool bar has "Navigation" heading with nothing under it. When I add the following code to my conf.py file, the HTML toolbar remains the same (with nothing under Navigation): html_sidebars = { '**': [ 'about.html', 'navigation.html', 'searchbox.html' ]} Do I have to create some file on my own or am I doing something wrong? My goal is for the HTML to look like this: I assume it's the same issue as adding a logo to the HTML which I also couldn't create. These are the contents of the index.rst file in my Sphinx project: .. Sample documentation master file, created by sphinx-quickstart on Thu Jul 5 09:19:15 2018. You can adapt this file completely to your liking, but it should at least contain the root `toctree` directive. Welcome to Sample's documentation! ==================================== .. toctree:: :maxdepth: 2 :caption: Contents: Indices and tables ================== * :ref:`genindex` * :ref:`modindex` * :ref:`search`
type: Question
tagged with: toctree
has comment: http://stackoverflow.com/comment/89605517
tagged with: navigationbar
tagged with: sidebar
has comment: http://stackoverflow.com/comment/89666947
upvote count: 4
downvote count: 0
has comment: http://stackoverflow.com/comment/89663656
score: 4

http://stackoverflow.com/comment/89420058
has text: etc. PDF viewer applications like Adobe PDF viewer are Acitive X controls in IE. IE's ActiveX filtering settings will prevent display of ActiveX content in websites that map to the Internet or Restricted sites zones.
comment on: http://stackoverflow.com/q/51205411
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/q/51257776
has comment: http://stackoverflow.com/comment/89495444
type: Question
has comment: http://stackoverflow.com/comment/89495721
linked to: http://stackoverflow.com/q/36190757
tagged with: ubuntu
tagged with: python-3.6
score: 0
has body: Error: ImportError: /usr/lib/python3/dist-packages/kivy/event.cpython-36m-x86_64-linux-gnu.so: undefined symbol: PyFPE_jbuf I have use this method to install the Kivy: sudo add-apt-repository ppa:kivy-team/kivy sudo apt-get update sudo apt-get install python3-kivy sudo apt-get install kivy-examples I have also go through from this question: numpy undefined symbol: PyFPE_jbuf and this also did not solve my error. I have built the App using kivy in python3 and It is working fine. Today I have switched to ubuntu. Even when I import the kivy It is not working and shows me same error in ubuntu! Is there any solution for it? I have looked everywhere but I didn't find the issue. Thanks in Advance.
has comment: http://stackoverflow.com/comment/89495491
has title: I have building app in python3 with kivy it is working fine but in linux I got the error below
has comment: http://stackoverflow.com/comment/89495294
tagged with: kivy
favorite count: 0
has comment: http://stackoverflow.com/comment/89495239
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89495572
tagged with: python
has comment: http://stackoverflow.com/comment/89494988
answer count: 0
has comment: http://stackoverflow.com/comment/89544747
has comment: http://stackoverflow.com/comment/89510601
upvote count: 1
downvote count: 1

http://stackoverflow.com/q/51299834
accepted answer: http://stackoverflow.com/a/51300391
linked to: http://stackoverflow.com/q/10670217
answer count: 1
tagged with: paramiko
type: AnsweredQuestion
has body: I intend to create a use passwordless connection using SSH Keys between a client and a server. Using paramiko, I end up in a AuthenticationException. Using standard SSH via Popen, I can connect without problems For Paramiko I use the following code: client = paramiko.SSHClient() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) client.load_system_host_keys() client.connect(ssh_server, username=ssh_user) For the same situation, I am able to use SSH: cmd = 'ssh -o GSSAPIAuthentication=no -o ForwardX11=no {}@{} echo 0 &gt; /dev/null'.format(ssh_user, ssh_server) process = subprocess.Popen(md, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) process.communicate() I am using Python 3.4.6 and Paramiko 2.4.1. Some more details: I am able to establish a connection with Paramiko on a different client On this specific client, the user for ssh impersonation is not the same as the user who starts the call. Paramiko Debug Output 2018-07-11 20:55:54,025 20730 DEBUG: putting paramiko output to console 2018-07-11 20:55:54,112 20730 DEBUG: starting thread (client mode): 0x4ca07320 2018-07-11 20:55:54,112 20730 DEBUG: Local version/idstring: SSH-2.0-paramiko_2.4.1 2018-07-11 20:55:54,112 20730 DEBUG: Remote version/idstring: SSH-2.0-OpenSSH_7.2 2018-07-11 20:55:54,112 20730 INFO: Connected (version 2.0, client OpenSSH_7.2) 2018-07-11 20:55:54,115 20730 DEBUG: kex algos:['curve25519-sha256@libssh.org', 'ecdh-sha2-nistp256', 'ecdh-sha2-nistp384', 'ecdh-sha2-nistp521', 'diffie-hellman-group-exchange-sha256', 'diffie-hellman-group14-sha1'] server key:['ssh-rsa', 'rsa-sha2-512', 'rsa-sha2-256', 'ssh-dss', 'ecdsa-sha2-nistp256', 'ssh-ed25519'] client encrypt:['chacha20-poly1305@openssh.com', 'aes128-ctr', 'aes192-ctr', 'aes256-ctr', 'aes128-gcm@openssh.com', 'aes256-gcm@openssh.com'] server encrypt:['chacha20-poly1305@openssh.com', 'aes128-ctr', 'aes192-ctr', 'aes256-ctr', 'aes128-gcm@openssh.com', 'aes256-gcm@openssh.com'] client mac:['umac-64-etm@openssh.com', 'um…
downvote count: 0
linked to: http://stackoverflow.com/q/52632693
has answer: http://stackoverflow.com/a/51300391
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/8382847
score: 3
has title: Passwordless SSH connection with Paramiko fails where as with SSH works
tagged with: ssh
tagged with: python
upvote count: 3

http://stackoverflow.com/comment/89382574
comment on: http://stackoverflow.com/a/51198978
score: 1
type: AnswerComment
has text: Yes, I tried your solution with unaligned __m128 and it works!
type: Comment

http://stackoverflow.com/q/51311365
has comment: http://stackoverflow.com/comment/89599394
has comment: http://stackoverflow.com/comment/89599710
answer count: 1
accepted answer: http://stackoverflow.com/a/51311577
tagged with: flask
favorite count: 0
has body: For some reason, I keep getting 404 not found errors when I launch my code in flask for animsition, even though I'm pretty sure that I'm linking to it correctly in the static file. The line in particular that is messed up is this one, I believe: &lt;script src="{{url_for('static', filename ='vendor/animsition/animsition.min.js')}}'"&gt;&lt;/script&gt; I checked and this is the proper location of the animsition file. Does this seem like proper syntax, or is the problem something else? Thanks!
tagged with: http://stackoverflow.com/tag/html
tagged with: python
has comment: http://stackoverflow.com/comment/89599551
upvote count: 1
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/51311577
has comment: http://stackoverflow.com/comment/89599852
type: AnsweredQuestion
has title: Animsition not working when in flask?
tagged with: javascript
has comment: http://stackoverflow.com/comment/89599678
tagged with: script-tag
score: 0

http://stackoverflow.com/comment/89555210
has text: I will post a new question because I think this problem is a bit different. I will try to explain better in that question.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/51270843
score: 0

http://stackoverflow.com/comment/89468588
has text: You can use `OrderedDict` to preserve attribute order with lxml. See https://stackoverflow.com/a/22596064/407651
score: 1
comment on: http://stackoverflow.com/q/51234136
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51350346
has body: elemnts=[2,2,0,0,5,6] h1=9 h2=6 def func(elemts,a,b): list1=[] for i in range(0,len(elemts)): for j in range(i+1,len(elemts)): for k in range(0,len(elemts)): if(k not in [i,j]): temp=elemts[i]+elemts[j]+elemts[k] if(temp in [h1,h2]): list1.extend([elemts[i],elemts[j],elemts[k]]) return list1 list2=func(elemnts,h1,h2) @arthur_currry...just chnged one line in last if case.Its working fine
type: Answer
accepted answer of: http://stackoverflow.com/q/51291648
answers question: http://stackoverflow.com/q/51291648
type: AcceptedAnswer
score: 0

http://stackoverflow.com/a/51192651
upvote count: 1
has body: Man, it works, your problem is that there is no 31 of september
type: Answer
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/51192165

http://stackoverflow.com/comment/89372987
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51195343
has text: My first comment was a bit off. `x` is a local variable in both cases. When I said 'making it local' I was thinking of a case where `y` is used inside the function (but not passed as an argument). In either case the distinction between reassigning a variable and modifing an object is important.

http://stackoverflow.com/comment/89892349
type: QuestionComment
comment on: http://stackoverflow.com/q/51234994
score: 0
has text: I'm not using multiprocessing. The weirdest thing here is that when I run the class from the interactive shell it works perfectly. When I run the same commands from the terminal it hangs. Very odd.
type: Comment

http://stackoverflow.com/q/51243341
downvote count: 1
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51245365
tagged with: python-unicode
has comment: http://stackoverflow.com/comment/89468212
has comment: http://stackoverflow.com/comment/89468157
answer count: 1
has body: I am having a tough time in running the following code. import urllib.request, urllib.parse, urllib.error from bs4 import BeautifulSoup import ssl import re import csv file = open("Test.CSV", "r") reader = csv.reader(file) for line in reader: text = line[5] lst = re.findall('(http.?://[^\s]+)', text) if not lst: print('Empty List') else: try: for url in lst: html = urllib.request.urlopen(url, context=ctx).read() soup = BeautifulSoup(html, 'html.parser') title = soup.title.string str_title = str (title) if 'Twitter' in str_title: if len(lst) &gt; 1: break else: continue else: print (str_title, ',', url) except urllib.error.HTTPError as err: if err.code == 404: print ('Invalid Twitter Link') The above mentioned code reads a csv file, selects a column, then parses that using regex to get all the hyperlinks in a single row, I then use BeautifulSoup to parse through the Hyperlink to get the 'Title String' of the page. Now, whenever i run this code, it stops working for a particular row, and throws an error "UnicodeEncodeError: 'ascii' codec can't encode characters in position 15-17: ordinal not in range(128)" How do I work my way with the Unicode String here ? Any help would be much appreciated.
favorite count: 0
tagged with: beautifulsoup
accepted answer: http://stackoverflow.com/a/51245365
score: 0
tagged with: python
has comment: http://stackoverflow.com/comment/89468488
has comment: http://stackoverflow.com/comment/89467675
tagged with: python-3.x
has title: UnicodeEncodeError: 'ascii' codec can't encode characters in position 15-17: ord inal not in range(128)
upvote count: 1

http://stackoverflow.com/q/51235770
score: 2
upvote count: 2
has answer: http://stackoverflow.com/a/51240320
tagged with: django
has comment: http://stackoverflow.com/comment/89450464
type: Question
linked to: http://stackoverflow.com/q/38703016
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51240320
has comment: http://stackoverflow.com/comment/89450735
linked to: http://stackoverflow.com/q/6158859
has title: How to perform an F() query with datetime field?
has body: I want to do a query based on two fields of a model, a date, offset by an int, used as a timedelta model.objects.filter(last_date__gte=datetime.now()-timedelta(days=F('interval'))) My model goes this way: class Line(models.Model): last_date = models.DateTimeField(auto_now=True) interval = models.IntegerField(default=0) I am using Django 2.0 and db.sqlite3 I found some sources What is the replacement for DateModifierNode in new versions of Django and Making queries using F() and timedelta at django but they were not helpful. some suggested to use duration field, but I want the interval to be entered in days desperately, whenever I use duration field , the admin needs to enter that in [days hh:mm:ss] in admin forms. And some gave a method model.objects.filter(last_date__gte=datetime.now()-timedelta(days=1)*F('interval')) which isn't working in db.sqlite3 and returning errors. Please suggest me some solution,like admin using duration field and entering only days or some solution with integer field of days.
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/89450495
favorite count: 0
tagged with: python

http://stackoverflow.com/q/51237354
has body: I need convert an image from BGR to YCbCr in Python using OpenCV. I have an image with size/resolution 512x512, but when the image is opened, the size is 128x128. I'm doing: image = cv2.imread(imageName, cv2.COLOR_BGR2YCR_CB) Could anyone help me?
has title: OpenCV Python converting color-space image to YCbCr
tagged with: color-space
upvote count: 1
downvote count: 1
type: Question
tagged with: opencv
tagged with: format-conversion
tagged with: image
has answer: http://stackoverflow.com/a/51237521
score: 0
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/89453836
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/51294534
has comment: http://stackoverflow.com/comment/89566729
tagged with: uwsgi
type: Question
has title: Flask / uWSGI / CentOS - updates do not work
tagged with: nginx
tagged with: wsgi
has comment: http://stackoverflow.com/comment/89566670
tagged with: centos
has answer: http://stackoverflow.com/a/51294950
answer count: 2
has comment: http://stackoverflow.com/comment/89568013
downvote count: 0
has comment: http://stackoverflow.com/comment/89595932
favorite count: 0
has answer: http://stackoverflow.com/a/62512031
upvote count: 2
type: UnansweredQuestion
has body: to be honest i am a Noob if it comes to servers &amp; maintenance. I followed exactly the following guide to create my first "Hello There" page which worked out so far. https://www.digitalocean.com/community/tutorials/how-to-serve-flask-applications-with-uwsgi-and-nginx-on-centos-7 But after trying to update my homepage by inserting more code into my Application and saving the script the server output in my Browser still remains the same old "hello there". I am better with functional programming (mathematics) and database handling, but since I have to supply my team colleagues with some tools i thought about a quick homepage. Unfortunatley it is harder than expected to set up a python hp. Thank you in advanced Stefan EDIT: I really followed the link above 1 to 1. Ht here are my codes: TAOWeb.py from flask import Flask, render_template application = Flask(__name__) @application.route("/") def hello(): return "&lt;h style='color:green'&gt; HELLO ASDF! &lt;/h1&gt;" if __name__ == "__main__": application.run(host='0.0.0.0') TAOWeb.ini [uwsgi] module = wsgi master = true processes = 5 socket = TAOWeb.sock chmod-socket = 660 vacuum = true die-on-term = true wsgi.py from TAOWeb import application if __name__ == "__main__": application.run() and the /etc/systemd/system/TAOWeb.service [Unit] Description=uWSGI instance to serve TAOWeb After=network.target [Service] User=tao Group=nginx WorkingDirectory=/home/tao/TAOWeb Environment="PATH=/home/tao/TAOWeb/env/bin" ExecStart=/home/tao/TAOWeb/env/bin/uwsgi --ini TAOWeb.ini [Install] WantedBy=multi-user.target Last but not least the nginx Config: # For more information on configuration, see: # * Official English Documentation: http://nginx.org/en/docs/ # * Official Russian Documentation: http://nginx.org/ru/docs/ user nginx; worker_processes auto; error_log /var/log/nginx/error.log; pid /run/nginx.pid; # Load dynamic modules. See /usr/share/nginx/README.dynamic. include /usr/share/nginx/modules/*.conf; events { worker_connections …
tagged with: python
score: 2

http://stackoverflow.com/comment/89366959
comment on: http://stackoverflow.com/q/51192294
type: Comment
type: QuestionComment
has text: Is get_text() not useful? Check the [documentation](https://www.crummy.com/software/BeautifulSoup/bs4/doc/)
score: 0

http://stackoverflow.com/a/51199562
has comment: http://stackoverflow.com/comment/89561572
has comment: http://stackoverflow.com/comment/89546533
has body: PDFTron PDFNet SDK is available on all platforms, with Python bindings, and you can find/edit fields. https://www.pdftron.com/documentation/samples?platforms=linux#InteractiveForms
has comment: http://stackoverflow.com/comment/89400215
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51195218

http://stackoverflow.com/comment/89437522
type: QuestionComment
has text: I pasted both sections into an editor and when I ran `test_2_test.py` the code printed -10 and 30
score: 0
type: Comment
comment on: http://stackoverflow.com/q/51228843

http://stackoverflow.com/comment/89328350
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51169509
has text: @Chuck - Unfortunately not :( And also problem with `NaN`s, possible solution for numeric `n` columns is `cols = df.filter(like='n').columns df[cols] = df[cols].astype(float)`

http://stackoverflow.com/comment/89440319
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51224826
score: 0
has text: Looks promising. I will try and let you know. Thanks

http://stackoverflow.com/comment/89469347
has text: There is difference between `onlyfiles` and `all_files` ?
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51245394

permutation
tags question: http://stackoverflow.com/q/51310139
tags question: http://stackoverflow.com/q/51223640
tags question: http://stackoverflow.com/q/51225496
tag name: permutation
tags question: http://stackoverflow.com/q/51268745
type: Tag
tags question: http://stackoverflow.com/q/51218151

http://stackoverflow.com/q/51213150
tagged with: selenium
upvote count: 1
type: Question
score: -2
linked to: http://stackoverflow.com/q/26566799
has comment: http://stackoverflow.com/comment/89407210
has comment: http://stackoverflow.com/comment/89407128
has comment: http://stackoverflow.com/comment/89414032
tagged with: firefox
answer count: 1
has comment: http://stackoverflow.com/comment/89407200
favorite count: 0
has title: selenium python wait doesn't work
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89413536
has body: I tried this WebDriverWait(web.driver,1000000000000000000000000000000000000000000000000) and it did nothing literally nothing. The web is also changing dynamically new elements are introduced to it and the code doesn't exist in the page_source of the new elements. please help I have been stuck on this all morning I'm using geckodriver for firefox python 3 test code _browser_profile = webdriver.FirefoxProfile() _browser_profile.set_preference("dom.webnotifications.enabled", False) driver=webdriver.Firefox(firefox_profile= _browser_profile) driver.get("https://www.google.com/") wait= WebDriverWait(driver,10) driver.get("https://www.youtube.com")
has answer: http://stackoverflow.com/a/51213247
downvote count: 3

http://stackoverflow.com/comment/89487540
has text: I don't think your solution of using different lists qualify as a resolution towards a student. The question is about adding/updating values in a dictionary "persistently" using a single List `encounters_to_add `. your "solution" is to use multiple lists.
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/51252345

http://stackoverflow.com/q/51316029
has comment: http://stackoverflow.com/comment/89634312
has comment: http://stackoverflow.com/comment/89609123
upvote count: 4
tagged with: python-sockets
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/89624646
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51316104
has body: While im trying to recv data with a while loop the loop not stopping even when there is no data import socket class Connect: connect = socket.socket(socket.AF_INET, socket.SOCK_STREAM) def __init__(self, server_ip, server_port): self.connect.connect((server_ip, server_port)) def recv(self): data_ls = [] while True: data = self.connect.recv(2048) if not data: # after getting the first data break # Python wont come to this "if" so it wont break! data = data.decode('utf-8') data_ls.append(data) return data_ls
has title: Python socket recv data in while loop not stopping
tagged with: python
type: AnsweredQuestion
downvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/51316104
score: 3

http://stackoverflow.com/comment/89413770
comment on: http://stackoverflow.com/q/51216292
score: 2
type: QuestionComment
type: Comment
has text: Yep that too, pretty much anything to avoid keys `Wooden_Sword1-Wooden_Sword9999` :P

http://stackoverflow.com/a/51292879
downvote count: 2
upvote count: 1
score: -1
has body: You could use list comprehension to build a new list: [ x for x in data if data.count(x)&gt;1 ] Also, the pop() method takes the index of the element as an argument, not the value.
type: Answer
answers question: http://stackoverflow.com/q/51292725

http://stackoverflow.com/q/51260058
has body: I have a container with several ports. I want remote access to the port 9001 outside of the container. My docker IP is: 172.17.0.1 My container IP is: 172.19.0.23 My server IP is: 192.168.1.131 I have searched about this issue and I found the expose and ports attributes for ports forwarding but it did not work. How to expose docker ports to make your containers externally accessible Reference This is my docker-compose file: version: '3' services: nginx: image: nginx:latest container_name: nginx ports: - "8010:8010" volumes: - .:/code - ./nginx/default.conf:/etc/nginx/conf.d/default.conf links: - ivms restart: unless-stopped ivms: build: . container_name: ivms command: bash bashes/createDB.sh volumes: - .:/code expose: - "8010" - "9001" ports: - "9001:9001" Here's the code snippet inside the ivms container: import zmq if __name__ == '__main__': context = zmq.Context() socket = context.socket(zmq.SUB) socket.setsockopt(zmq.SUBSCRIBE, "") socket.bind("tcp://192.168.1.131:9001") # doesn't work with server or docker IP while True: data = socket.recv_json() I run the above docker-compose via docker-compose up -d But when I use the server_IP:9001 which is 192.168.1.131:9001 or docker_IP:9001 which is 172.17.0.1:9001 can not access either the remote or local mode. But when using container_IP:9001 which is 172.19.0.23:9001 this works in local. What should I do so that I can have access the server_IP:9001 --> 192.168.1.131:9001? [NOTE]: In createDB.sh runs several operations such as creating a ZMQ on 9001 port. I have been set the port allowing before, using $ ufw allow 9001 I tried on Ubuntu 16.04 and Ubuntu-Server 16.04 Any help would be appreciated.
favorite count: 0
tagged with: docker
has comment: http://stackoverflow.com/comment/89498614
tagged with: pyzmq
has comment: http://stackoverflow.com/comment/89499952
has comment: http://stackoverflow.com/comment/89499222
has answer: http://stackoverflow.com/a/51390175
accepted answer: http://stackoverflow.com/a/51390175
tagged with: python
upvote count: 9
has comment: http://stackoverflow.com/comment/89499119
has comment: http://stackoverflow.com/comment/89498543
downvote count: 0
has comment: http://stackoverflow.com/comment/89501389
possible better answer: http://stackoverflow.com/a/51261937
has answer: http://stackoverflow.com/a/51261937
has comment: http://stackoverflow.com/comment/89499162
has comment: http://stackoverflow.com/comment/89499096
type: AnsweredQuestion
tagged with: docker-compose
has comment: http://stackoverflow.com/comment/89498852
tagged with: zeromq
has comment: http://stackoverflow.com/comment/89498809
type: Question
score: 9
answer count: 2
has title: How to expose a ZMQ container port outside of docker/container using docker-compose?
has comment: http://stackoverflow.com/comment/89498916
has comment: http://stackoverflow.com/comment/89501330
has comment: http://stackoverflow.com/comment/89499242

http://stackoverflow.com/comment/89560427
comment on: http://stackoverflow.com/q/51291281
score: 0
has text: Are your D, E, F & Y variables also single character strings?
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51221477
tagged with: jupyter
linked to: http://stackoverflow.com/q/38819322
has body: I had a Python version 3.6.5 and I deleted whole Python with my Jupyter installed. Than I installed Python 3.7.0, but it does not support some modules now, so I deleted that and again installed Python 3.6.6 but now I don't have my Jupyter files there. Do you know how can I restore my old files?
has comment: http://stackoverflow.com/comment/89423578
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89425515
tagged with: python
has comment: http://stackoverflow.com/comment/89426284
has comment: http://stackoverflow.com/comment/89425475
has comment: http://stackoverflow.com/comment/89426448
has comment: http://stackoverflow.com/comment/89425541
tagged with: ipython
type: Question
has comment: http://stackoverflow.com/comment/89425390
has comment: http://stackoverflow.com/comment/89425311
has comment: http://stackoverflow.com/comment/89425552
has comment: http://stackoverflow.com/comment/89425481
tagged with: restore
score: 0
has comment: http://stackoverflow.com/comment/89425508
tagged with: backup
has title: How can I restore files in Jupyter?

http://stackoverflow.com/comment/89451611
has text: *The second and third I haven't gotten to work despite hours of trying. Multiple libraries simply didn't work* - well, maybe you should post questions about these issues then instead of asking for a miracle solution.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51229188
score: 1

http://stackoverflow.com/q/51181729
has title: Custom Plotly Markers based on variable value
downvote count: 0
tagged with: plotly
upvote count: 8
type: Question
answer count: 1
has body: I am using the following code to create a simple plotly line chart in Python. I have two variables (at the bottom of the code): ctime amount ctime just using the current time for each element in amount; there are 10 times amount is a contained of amounts ranging from 0-1000; the are ten amounts I want to color my plot markers in the following way: amount is less than 300; that specific marker for that value will be green amount is between 300 and 400; that specific marker for that value will be yellow amount is greater than 400; that specific marker for that value will be red Is there any way I can build in a conditional type handler for this? layout = Layout( title='Current Amount', titlefont=Font( family='"Open sans", verdana, arial, sans-serif', size=17, color='#444' ), font=Font( family='"Open sans", verdana, arial, sans-serif', size=12, color='#444' ), showlegend=True, autosize=True, width=803, height=566, xaxis=XAxis( title='Time', titlefont=Font( family='"Open sans", verdana, arial, sans-serif', size=14, color='#444' ), range=[1418632334984.89, 1418632334986.89], domain=[0, 1], type='date', rangemode='normal', autorange=True, showgrid=False, zeroline=False, showline=True, autotick=True, nticks=0, ticks='inside', showticklabels=True, tick0=0, dtick=1, ticklen=5, tickwidth=1, tickcolor='#444', tickangle='auto', tickfont=Font( family='"Open sans", verdana, arial, sans-serif', size=12, color='#444' ), mirror='allticks', linecolor='rgb(34,34,34)', linewidth=1, anchor='y', side='bottom' ), yaxis=YAxis( title='GHI (W/m2)', titlefont=Font( family='"Open sans", verdana, arial, sans-serif', size=14, color='#444' ), range=[-5.968375815056313, 57.068375815056314], domain=[0, 1], type='linear', rangemode='normal', autorange=True, showgrid=False, zeroline=False, showline=True, autotick=True, nticks=0, ticks='inside', showticklabels=True, tick0=0, dtick=1, ticklen=5, tickwidth=1, tickcolor='#444', tickangle='auto', tickfont=Font( family='"Open sans", verdana, arial, sans-se…
score: 8
favorite count: 0
has answer: http://stackoverflow.com/a/51183434
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/51272055
has title: OpenCV unproject 2D points to 3D with known depth `Z`
has comment: http://stackoverflow.com/comment/89561998
favorite count: 0
has answer: http://stackoverflow.com/a/51292288
type: Question
tagged with: python
accepted answer: http://stackoverflow.com/a/51292288
upvote count: 13
tagged with: 3d-reconstruction
tagged with: c++
answer count: 1
has comment: http://stackoverflow.com/comment/89563966
tagged with: opencv
has body: Problem statement I am trying to reproject 2D points to their original 3D coordinates, assuming I know the distance at which each point is. Following the OpenCV documentation, I managed to get it to work with zero-distortions. However, when there are distortions, the result is not correct. Current approach So, the idea is to reverse the following: into the following: By: Geting rid of any distortions using cv::undistortPoints Use intrinsics to get back to the normalized camera coordinates by reversing the second equation above Multiplying by z to reverse the normalization. Questions Why do I need to subtract f_x and f_y to get back to the normalized camera coordinates (found empirically when testing)? In the code below, in step 2, if I don't subtract -- even the non-distorted result is off This was my mistake -- I messed up the indexes. If I include the distortion, the result is wrong -- what am I doing wrong? Sample code (C++) #include &lt;iostream&gt; #include &lt;opencv2/calib3d/calib3d.hpp&gt; #include &lt;opencv2/core/core.hpp&gt; #include &lt;opencv2/imgproc/imgproc.hpp&gt; #include &lt;vector&gt; std::vector&lt;cv::Point2d&gt; Project(const std::vector&lt;cv::Point3d&gt;&amp; points, const cv::Mat&amp; intrinsic, const cv::Mat&amp; distortion) { std::vector&lt;cv::Point2d&gt; result; if (!points.empty()) { cv::projectPoints(points, cv::Mat(3, 1, CV_64F, cvScalar(0.)), cv::Mat(3, 1, CV_64F, cvScalar(0.)), intrinsic, distortion, result); } return result; } std::vector&lt;cv::Point3d&gt; Unproject(const std::vector&lt;cv::Point2d&gt;&amp; points, const std::vector&lt;double&gt;&amp; Z, const cv::Mat&amp; intrinsic, const cv::Mat&amp; distortion) { double f_x = intrinsic.at&lt;double&gt;(0, 0); double f_y = intrinsic.at&lt;double&gt;(1, 1); double c_x = intrinsic.at&lt;double&gt;(0, 2); double c_y = intrinsic.at&lt;double&gt;(1, 2); // This was an error before: // double c_x = intrinsic.at&lt;double&gt;(0, 3); // double c_y = intrinsic.at&lt;double&gt;(1, 3); // …
score: 13
tagged with: projection
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89541848
downvote count: 0

http://stackoverflow.com/comment/89573576
score: 0
type: AnswerComment
has text: Then make sure path is right and all the extensions are exactly ".txt" (matching the case)as this is very straightforward code.
comment on: http://stackoverflow.com/a/51297961
type: Comment

http://stackoverflow.com/q/51211055
accepted answer: http://stackoverflow.com/a/51214326
upvote count: 5
tagged with: scipy
type: Question
answer count: 2
score: 5
downvote count: 0
favorite count: 0
has title: Can scipy.optimize minimize functions of complex variables at all and how?
tagged with: python
has answer: http://stackoverflow.com/a/51214326
tagged with: mathematical-optimization
possible better answer: http://stackoverflow.com/a/73328286
has answer: http://stackoverflow.com/a/73328286
type: AnsweredQuestion
has body: I am trying to minimize a function of a complex (vector) variable using scipy.optimize. My results so far indicate that it may not be possible. To investigate the problem, I have implemented a simple example - minimize the 2-norm of a complex vector with an offset: import numpy as np from scipy.optimize import fmin def fun(x): return np.linalg.norm(x - 1j * np.ones(2), 2) sol = fmin(fun, x0=np.ones(2) + 0j) The output is Optimization terminated successfully. Current function value: 2.000000 Iterations: 38 Function evaluations: 69 &gt;&gt;&gt; sol array([-2.10235293e-05, 2.54845649e-05]) Clearly, the solution should be array([0.+1.j, 0.+1.j]) Disappointed with this outcome, I have also tried scipy.optimize.minimize: from scipy.optimize import minimize def fun(x): return np.linalg.norm(x - 1j * np.ones(2), 1) sol = minimize(fun, x0=np.ones(2) + 0j) The output is &gt;&gt;&gt; sol fun: 2.0 hess_inv: array([[ 9.99997339e-01, -2.66135332e-06], [-2.66135332e-06, 9.99997339e-01]]) jac: array([0., 0.]) message: 'Optimization terminated successfully.' nfev: 24 nit: 5 njev: 6 status: 0 success: True x: array([6.18479071e-09+0.j, 6.18479071e-09+0.j]) Not good either. I have tried specifying all of the possible methods for minimize (supplying the Jacobian and Hessian as necessary), but none of them reach the correct result. Most of them cause ComplexWarning: Casting complex values to real discards the imaginary part, indicating that they cannot handle complex numbers correctly. Is this possible at all using scipy.optimize? If so, I would very much appreciate if someone can tell me what I am doing wrong. If not, do you perhaps have suggestions for alternative optimization tools (for Python) that allow this?

http://stackoverflow.com/comment/89602334
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51312227
has text: Errr... this is where the `length_P-1` value should be, as the comment explains.
type: AnswerComment

http://stackoverflow.com/q/51170784
has comment: http://stackoverflow.com/comment/89359808
has comment: http://stackoverflow.com/comment/89359143
score: 7
upvote count: 7
type: Question
has title: Setting flask session variable outside request context (inside a generator)
tagged with: flask
has body: I have a flask view which is executed to load some information in a generator (I am using a generator so that I can continuously yield the progress - how much information has loaded). Here is what the view looks like: @app.route("/progress", methods=['GET']) def progress(): gen = get_user_saved_tracks(session['token'], session['spotify_id'], session) return Response(gen, mimetype= 'text/event-stream') def get_user_saved_tracks(token, id, session): #load information and keep yielding session['info'] = info I would like to store the information which is loaded in a session variable inside the generator (This generator function is defined in a different file, outside the request context). But when I try to access the session variable, I get the following error: RuntimeError: Working outside of request context. So, is there a way to write the information to the session in this way? I am using FileSystemSessionInterface right now but willing to use redis sessions if that will solve my issue. Update: As suggested by Sraw, I tried the following changes: from flask import current_app app = current_app._get_current_object() def get_user_saved_tracks(token, id,session): with app.app_context(): session['info'] = info But I still get the same error. Update 2: So, I need to use the actual app instance instead of using current_app (app object is being created in a different file - app.py) from app import app def get_user_saved_tracks(token, id,session): with app.app_context(): session['info'] = info On doing this, I get the same error: RuntimeError: Working outside of request context. Update 3: Following is the code for get_user_saved_tracks: def get_user_saved_tracks(token, id, session, j, service): tracks = [] for i in range(100): a = service.current_user_saved_tracks(limit=50, offset=i*50) if len(a['items']) == 0: break yield "data:" + "lib" + str((float(i+1)/(j))*100) + "\n\n" time.sleep(0.5) tracks.extend(a) session['tracks'] = tracks session.modified = True yield "data:" + …
has comment: http://stackoverflow.com/comment/89358576
has comment: http://stackoverflow.com/comment/89358939
answer count: 2
has answer: http://stackoverflow.com/a/64873634
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/89359096
has answer: http://stackoverflow.com/a/51189708
has comment: http://stackoverflow.com/comment/89360626
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89324285
tagged with: python
tagged with: flask-session
tagged with: generator
linked to: http://stackoverflow.com/q/34122949
has comment: http://stackoverflow.com/comment/89358517

http://stackoverflow.com/q/51265910
has body: I know you can make a circle with drawEllipse but how can I make a half circle? This is my current code that has the circles displayed correctly but the half circle displays nothing. Any ideas? class DrawImage(QtWidgets.QWidget): def __init__(self, parent): QtWidgets.QWidget.__init__(self, parent) self.move(150,50) self.setFixedSize(100,100) self.startA = 5 self.endA = 30 def paintEvent(self, event): #use to draw on the canvas paint = QtGui.QPainter() paint.begin(self) paint.setRenderHint(QtGui.QPainter.Antialiasing) # make a white drawing background paint.setBrush(QtCore.Qt.white) paint.drawRect(event.rect()) paint.setPen(QtCore.Qt.black) paint.setBrush(QtCore.Qt.white) paint.drawEllipse(QtCore.QRect(25, 25, 50, 50)) #outer circle paint.setPen(QtCore.Qt.yellow) paint.setBrush(QtCore.Qt.yellow) paint.drawEllipse(QtCore.QRect(37.5, 37.5, 25, 25)) #middle circle paint.setPen(QtCore.Qt.white) paint.setBrush(QtCore.Qt.white) paint.drawEllipse(QtCore.QRect(43.75, 43.75, 12.5, 12.5)) #innermost circle #where I am trying to implement a half circle r = QtCore.QRect(12.5, 12.5, 20, 20) #&lt;-- create rectangle size = r.size() #&lt;-- get rectangle size r.setSize(size*10) #&lt;-- set size startAngle = self.startA*16 #&lt;-- set start angle to draw arc endAngle = self.endA*16 #&lt;-- set end arc angle paint.setPen(QtCore.Qt.black) #&lt;-- arc color paint.setBrush(QtCore.Qt.yellow) paint.drawArc(r, startAngle, endAngle) paint.end()
tagged with: python
score: 2
upvote count: 2
has answer: http://stackoverflow.com/a/51267772
tagged with: pyqt5
type: AnsweredQuestion
has title: How to make a half circle in PyQt5 with Python
type: Question
accepted answer: http://stackoverflow.com/a/51267772
answer count: 1
downvote count: 0
favorite count: 0

http://stackoverflow.com/comment/89377675
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51197802
has text: You rearranged and expanded since I comment (moved 2 to 1 and 1 to 2, and finished the thought in old #1/new #2). All's well now.

http://stackoverflow.com/comment/89607135
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51315264
has text: What part of the code do you want caught? Just wrap a `try:` `except KeyError:` around that part. Also, you don't need a void `return` and I'm pretty sure your `.format(PID)` doesn't do anything since it's missing a `{}` inside the string.

http://stackoverflow.com/comment/91378400
type: Comment
has text: Thanks Prithvi, it worked properly once notebook is attached to active cluster
type: AnswerComment
comment on: http://stackoverflow.com/a/51405130
score: 0

http://stackoverflow.com/comment/89533231
has text: sir, how many tweets we can get. Is it based on our consumer key?
type: Comment
comment on: http://stackoverflow.com/q/51258962
type: QuestionComment
score: 0

http://stackoverflow.com/a/51248309
type: Answer
has body: As described in the dataclass PEP, there is a __post_init__ method, which will be the last thing called by __init__. from dataclasses import dataclass @dataclass class DataClass: some_field: int def __post_init__(self): print(f"My field is {self.some_field}") Defining this dataclass class, and then running the following: dc = DataClass(1) # Prints "My field is 1" Would initialize some_field to 1, and then run __post_init__, printing My field is 1. This allows you to run code after the initialization method to do any additional setup/checks you might want to perform.
has comment: http://stackoverflow.com/comment/125887461
answers question: http://stackoverflow.com/q/51199031
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/126988246
downvote count: 0
upvote count: 221
accepted answer of: http://stackoverflow.com/q/51199031
score: 221

http://stackoverflow.com/comment/89421122
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51220010
score: 0
has text: Your question is unclear. Please provide input and expected output.

http://stackoverflow.com/comment/89378140
has text: Dictionaries are not ordered, but you expected output seems to make assumptions that there is an order. Can you clarify what ordering you expected?
comment on: http://stackoverflow.com/q/51198179
score: 0
type: Comment
type: QuestionComment

pygobject
type: Tag
tags question: http://stackoverflow.com/q/51177679
tag name: pygobject
tags question: http://stackoverflow.com/q/51199662

http://stackoverflow.com/comment/89507105
type: QuestionComment
has text: Based on your response I can see I need to read more ;)
comment on: http://stackoverflow.com/q/51264436
score: 0
type: Comment

python-2.7
tags question: http://stackoverflow.com/q/51272799
tags question: http://stackoverflow.com/q/51186226
tags question: http://stackoverflow.com/q/51231660
tags question: http://stackoverflow.com/q/51277876
tags question: http://stackoverflow.com/q/51187459
tags question: http://stackoverflow.com/q/51205985
tags question: http://stackoverflow.com/q/51203996
tags question: http://stackoverflow.com/q/51275578
tags question: http://stackoverflow.com/q/51300364
tags question: http://stackoverflow.com/q/51306224
tags question: http://stackoverflow.com/q/51263789
tags question: http://stackoverflow.com/q/51195799
tags question: http://stackoverflow.com/q/51211452
tags question: http://stackoverflow.com/q/51206400
tags question: http://stackoverflow.com/q/51292900
tags question: http://stackoverflow.com/q/51228047
tags question: http://stackoverflow.com/q/51228874
tags question: http://stackoverflow.com/q/51246724
tags question: http://stackoverflow.com/q/51293794
tags question: http://stackoverflow.com/q/51202865
tags question: http://stackoverflow.com/q/51237591
tags question: http://stackoverflow.com/q/51273207
tags question: http://stackoverflow.com/q/51279464
tags question: http://stackoverflow.com/q/51205924
tags question: http://stackoverflow.com/q/51323776
tags question: http://stackoverflow.com/q/51227799
tags question: http://stackoverflow.com/q/51242520
tags question: http://stackoverflow.com/q/51302227
tags question: http://stackoverflow.com/q/51175154
tags question: http://stackoverflow.com/q/51201748
tags question: http://stackoverflow.com/q/51209020
tags question: http://stackoverflow.com/q/51215052
tags question: http://stackoverflow.com/q/51258537
tags question: http://stackoverflow.com/q/51219159
tags question: http://stackoverflow.com/q/51176851
tags question: http://stackoverflow.com/q/51284908
tags question: http://stackoverflow.com/q/51295329
tags question: http://stackoverflow.com/q/51294386
tags question: http://stackoverflow.com/q/51180439
tags question: http://stackoverflow.com/q/51169471
tags question: http://stackoverflow.com/q/51198679
tags question: http://stackoverflow.com/q/51180775
tags question: http://stackoverflow.com/q/51229274
tags question: http://stackoverflow.com/q/51232224
tags question: http://stackoverflow.com/q/51227029
tags question: http://stackoverflow.com/q/51171741
tags question: http://stackoverflow.com/q/51303008
tags question: http://stackoverflow.com/q/51313429
tags question: http://stackoverflow.com/q/51205194
tags question: http://stackoverflow.com/q/51316221
tags question: http://stackoverflow.com/q/51187553
tags question: http://stackoverflow.com/q/51218916
tags question: http://stackoverflow.com/q/51289564
tags question: http://stackoverflow.com/q/51301206
tags question: http://stackoverflow.com/q/51295378
tags question: http://stackoverflow.com/q/51203785
tags question: http://stackoverflow.com/q/51235168
tags question: http://stackoverflow.com/q/51187850
tags question: http://stackoverflow.com/q/51178199
tags question: http://stackoverflow.com/q/51286732
tags question: http://stackoverflow.com/q/51277895
tags question: http://stackoverflow.com/q/51320167
tags question: http://stackoverflow.com/q/51245038
tags question: http://stackoverflow.com/q/51236003
tags question: http://stackoverflow.com/q/51204370
tags question: http://stackoverflow.com/q/51260858
tags question: http://stackoverflow.com/q/51305831
tags question: http://stackoverflow.com/q/51229559
tags question: http://stackoverflow.com/q/51245252
tags question: http://stackoverflow.com/q/51183311
tags question: http://stackoverflow.com/q/51184089
tags question: http://stackoverflow.com/q/51233730
tags question: http://stackoverflow.com/q/51192165
tags question: http://stackoverflow.com/q/51322672
tags question: http://stackoverflow.com/q/51302364
tags question: http://stackoverflow.com/q/51305905
tags question: http://stackoverflow.com/q/51180486
tags question: http://stackoverflow.com/q/51287338
tags question: http://stackoverflow.com/q/51176566
tags question: http://stackoverflow.com/q/51266989

oop
tags question: http://stackoverflow.com/q/51300833
tags question: http://stackoverflow.com/q/51216605
tags question: http://stackoverflow.com/q/51195607
tags question: http://stackoverflow.com/q/51249969
tags question: http://stackoverflow.com/q/51225748
tags question: http://stackoverflow.com/q/51216523
tag name: oop
tags question: http://stackoverflow.com/q/51240865
tags question: http://stackoverflow.com/q/51323622
tags question: http://stackoverflow.com/q/51314305
tags question: http://stackoverflow.com/q/51170644
tags question: http://stackoverflow.com/q/51249310
tags question: http://stackoverflow.com/q/51256150
tags question: http://stackoverflow.com/q/51219340
tags question: http://stackoverflow.com/q/51239045
type: Tag
tags question: http://stackoverflow.com/q/51187318

http://stackoverflow.com/comment/89468836
type: QuestionComment
has text: I am not sure what the question is about. The code **does not** declare a function. It just calls `requests.get()` and stores the returned value in `r`. `status_code` is not in an array - it is part of the returned value `r` (an attribute, in the Python terminology).
score: 0
comment on: http://stackoverflow.com/q/51244689
type: Comment

http://stackoverflow.com/q/51247349
score: 1
has answer: http://stackoverflow.com/a/51247408
accepted answer: http://stackoverflow.com/a/51247408
type: Question
upvote count: 1
answer count: 1
tagged with: string
has title: Remove characters from a string in a dataframe
favorite count: 0
tagged with: character
tagged with: python-3.x
tagged with: python
tagged with: regex
type: AnsweredQuestion
has body: python beginner here. I would like to change some characters in a column in a dataframe under certain conditions. The dataframe looks like this: import pandas as pd import numpy as np raw_data = {'name': ['Willard Morris', 'Al Jennings', 'Omar Mullins', 'Spencer McDaniel'], 'age': [20, 19, 22, 21], 'favorite_color': ['blue (VS)', 'red', 'yellow (AG)', "green"], 'grade': [88, 92, 95, 70]} df = pd.DataFrame(raw_data, index = ['0', '1', '2', '3']) df My goal is to replace in the column last name the space followed by the parenthesis and the two letters. Blue instead of Blue (VS). There is 26 letter variations that I have to remove but only one format: last_name followed by space followed by parenthesis followed by two letters followed by parenthesis. From what I understood it should be that in regexp: ( \(..\) I tried using str.replace but it only works for exact match and it replaces the whole value. I also tried this: df.loc[df['favorite_color'].str.contains(‘VS’), 'favorite_color'] = ‘random’ it also replaces the whole value. I saw that I can only rewrite the value but I also saw that using this: df[0].str.slice(0, -5) I could remove the last 5 characters of a string containing my search. In my mind I should make a list of the 26 occurrences that I want to be removed and parse through the column to remove those while keeping the text before. I searched for post similar to my problem but could not find a solution. Do you have any idea for a direction ?
downvote count: 0

http://stackoverflow.com/comment/89321277
has text: I meant the setter property definition. The function with @property decorator
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51168556

http://stackoverflow.com/a/51271317
has body: If string does not contain any ',' then string.split(',') will return a list with a single element, the entire string. In this case, string.split(',')[1] will obviously raiseIndexError. li[0] == li[-1] in case li is a list with a single element.
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/51271265
downvote count: 0
type: Answer

http://stackoverflow.com/q/51295521
type: Question
tagged with: multithreading
has comment: http://stackoverflow.com/comment/93780791
tagged with: python
has body: Overview We're building a pipeline inside a Docker container using Luigi. This is my first time using Luigi and I'm trying to get it running but I'm stuck on a Python threading/signal error. What we're building We have a container that runs a setup.py script as an entrypoint. This script imports my Luigi tasks but it's main function is to open up a PubSub channel to Google Cloud Services. When it receives a message on that channel, it kicks off a run of tasks. The Error . I am calling Luigi directly from Python, experimenting with variations of this command: luigi.build([GetImageSet()], workers=2, local_scheduler=True, no_lock=True) And recieving this error: ValueError: signal only works in main thread Background on Signal &amp; Luigi From the Python Signal module docs: signal.signal: this function can only be called from the main thread; attempting to call it from other threads will cause a ValueError exception to be raised. From the Luigi worker.py script here Luigi provides the no_install_shutdown_handler flag (defaults to false). 'If true, the SIGUSR1 shutdown handler will NOT be installed on the worker'. This is also where the error is occuring (on line 538). The script checks that a configuration flag for the no_install_shutdown_handler is (the default) false before running signal.signal(). I have failed so far to get Luigi to read my client.cfg file with that flag set to true, and Docker may be to blame. From the Luigi interface.py script here If you don't want to run luigi from the command line. You may use the methods defined in this module to programmatically run luigi. In this script, I could provide a custom worker schedule factory but I haven't been able to wrap my head around that yet. Local vs. global Luigi scheduler Luigi provides two scheduler options for running tasks. The local Dockerfile woes: In my Dockerfile for this container, I am installing Luigi through pip but not doing much else. After reviewing this and this docker/luigi implementations …
answer count: 1
upvote count: 3
has title: Python Luigi with Docker - Threading/Signal issue
tagged with: dockerfile
tagged with: signals
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/54545891
tagged with: luigi
score: 3
downvote count: 0
favorite count: 0

http://stackoverflow.com/comment/89415134
has text: The interface in `pathos.multiprocessing` is deprecated... the preferred interface is `pathos.pools.ProcessPool`. That pool should have a `_clear` and a `restart` method. Note this is the same object as `pathos.multiprocessing.ProcessPool` and `pathos.multiprocessing.ProcessingPool`... both of which I've left hanging around for backward compatibility.
comment on: http://stackoverflow.com/q/51210305
type: QuestionComment
type: Comment
score: 1

http://stackoverflow.com/q/51318880
type: Question
downvote count: 0
favorite count: 0
score: 1
answer count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: python
has title: what is the difference between the constants and variables in tensorflow and in normal python program?
has body: In the below code i have used the varaibles in tensorflow and in normal code, I do not find any change in the logic, could someone please help me in understanding what is the difference between tensorflow attributes and the normal one: import tensorflow as tf a = tf.constant(3) b = tf.Variable(8) c = 9 d = tf.Variable(a+b+c) with tf.Session() as sess: d.initializer.run() print(d.eval()) Output: 20 In short what is the difference between a,b and c in above code?
tagged with: tensorflow

http://stackoverflow.com/comment/89425683
type: AnswerComment
type: Comment
score: 1
has text: "I have used np.roll() but it is not working." I'm not sure what this answer adds.
comment on: http://stackoverflow.com/a/51222620

http://stackoverflow.com/comment/89419255
score: 1
comment on: http://stackoverflow.com/q/51219088
type: Comment
has text: Use python's json module instead of writing, complex, unmaintainable and buggy code…
type: QuestionComment

http://stackoverflow.com/q/51288581
tagged with: python
tagged with: text
upvote count: 0
tagged with: file
has comment: http://stackoverflow.com/comment/89555078
type: Question
has title: How to read off of a specific line in a text file using python
score: -1
has body: Looking to have my code read one text file and store the line number of a user input as num and then use the variable num to read the same line on another file. currently, the code for the first step of reading the first text file is working and has been tested but the second part doesn't display anything after being executed. I have changed multiple things but am still stuck. Help would be much appreciated. here is my code: print("Check Stock") ca = input("Check all barcodes?") if ca == "y": for x in range(0,5): with open ("stockbarcodes.txt") as f: linesa = f.readlines() print(linesa[x]) with open ("stockname.txt") as f: linesb = f.readlines() print(linesb[x]) print(" ") else: bc = input("Scan barcode: ") f1 = open ("stockname.txt") for num, line in enumerate(f1, 1): if bc in line: linesba = f1.readlines() print(linesba[num])
has answer: http://stackoverflow.com/a/51291571
has comment: http://stackoverflow.com/comment/89555073
downvote count: 1
answer count: 1
linked to: http://stackoverflow.com/q/8685809
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89555665

http://stackoverflow.com/comment/89591834
type: AnswerComment
type: Comment
has text: I've updated the answer, try it again. If you get an error take note of the line number
comment on: http://stackoverflow.com/a/51307481
score: 0

dataframe
tags question: http://stackoverflow.com/q/51280861
tags question: http://stackoverflow.com/q/51295454
tags question: http://stackoverflow.com/q/51301149
tags question: http://stackoverflow.com/q/51302045
tags question: http://stackoverflow.com/q/51213201
tags question: http://stackoverflow.com/q/51290658
tags question: http://stackoverflow.com/q/51238369
tags question: http://stackoverflow.com/q/51242510
tags question: http://stackoverflow.com/q/51173659
tags question: http://stackoverflow.com/q/51222166
tags question: http://stackoverflow.com/q/51279973
tags question: http://stackoverflow.com/q/51247535
tags question: http://stackoverflow.com/q/51215246
tags question: http://stackoverflow.com/q/51305370
tags question: http://stackoverflow.com/q/51178256
tags question: http://stackoverflow.com/q/51172234
tags question: http://stackoverflow.com/q/51288869
tags question: http://stackoverflow.com/q/51172027
tags question: http://stackoverflow.com/q/51258736
tags question: http://stackoverflow.com/q/51228818
tags question: http://stackoverflow.com/q/51233714
tags question: http://stackoverflow.com/q/51214020
tags question: http://stackoverflow.com/q/51241834
tags question: http://stackoverflow.com/q/51262904
tags question: http://stackoverflow.com/q/51206956
tags question: http://stackoverflow.com/q/51265888
tags question: http://stackoverflow.com/q/51315083
tags question: http://stackoverflow.com/q/51277310
tags question: http://stackoverflow.com/q/51313369
tags question: http://stackoverflow.com/q/51252460
tags question: http://stackoverflow.com/q/51265953
tags question: http://stackoverflow.com/q/51241508
tags question: http://stackoverflow.com/q/51291382
tags question: http://stackoverflow.com/q/51260811
tags question: http://stackoverflow.com/q/51263141
tags question: http://stackoverflow.com/q/51218119
tags question: http://stackoverflow.com/q/51189289
tags question: http://stackoverflow.com/q/51297334
tags question: http://stackoverflow.com/q/51236970
tags question: http://stackoverflow.com/q/51221824
tags question: http://stackoverflow.com/q/51171892
tags question: http://stackoverflow.com/q/51286487
tags question: http://stackoverflow.com/q/51256916
tags question: http://stackoverflow.com/q/51290134
tags question: http://stackoverflow.com/q/51268571
tags question: http://stackoverflow.com/q/51253315
tags question: http://stackoverflow.com/q/51218488
tags question: http://stackoverflow.com/q/51268729
tags question: http://stackoverflow.com/q/51264748
tags question: http://stackoverflow.com/q/51294657
tags question: http://stackoverflow.com/q/51248923
tags question: http://stackoverflow.com/q/51217780
tags question: http://stackoverflow.com/q/51212473
tags question: http://stackoverflow.com/q/51321769
tags question: http://stackoverflow.com/q/51316723
tags question: http://stackoverflow.com/q/51282465
tags question: http://stackoverflow.com/q/51231692
tags question: http://stackoverflow.com/q/51275357
tags question: http://stackoverflow.com/q/51294721
tags question: http://stackoverflow.com/q/51200743
tags question: http://stackoverflow.com/q/51229303
tags question: http://stackoverflow.com/q/51167828
tags question: http://stackoverflow.com/q/51304723
tags question: http://stackoverflow.com/q/51243444
tags question: http://stackoverflow.com/q/51173492
tags question: http://stackoverflow.com/q/51303571
tags question: http://stackoverflow.com/q/51240431
tags question: http://stackoverflow.com/q/51193459
tags question: http://stackoverflow.com/q/51179796
tags question: http://stackoverflow.com/q/51256280
tags question: http://stackoverflow.com/q/51227784
tags question: http://stackoverflow.com/q/51225278
tags question: http://stackoverflow.com/q/51289592
tags question: http://stackoverflow.com/q/51201943
tags question: http://stackoverflow.com/q/51203831
tags question: http://stackoverflow.com/q/51227723
tags question: http://stackoverflow.com/q/51210090
tags question: http://stackoverflow.com/q/51248072
tags question: http://stackoverflow.com/q/51308391
tags question: http://stackoverflow.com/q/51176922

http://stackoverflow.com/a/51356279
score: 0
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/51233865
answers question: http://stackoverflow.com/q/51233865
has body: Here is what I did: Iterated over all the polygons and found overlapping polygons. Then, I moved the polygon in different directions and found the best moving direction by calculating the minimum resulting overlapping area. Then I simply moved the polygon in that best direction until there is no overlapping area.

http://stackoverflow.com/comment/89330810
has text: 1) The `I` being referenced is `sympy.I`. 2) If you build such an x1, you'll discover that `isinstance(x1, complex)` is actually False, because the sympy object isn't a subclass of the Python class `complex`.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/51173891
score: 0

http://stackoverflow.com/a/51211654
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89407661
downvote count: 0
has comment: http://stackoverflow.com/comment/89406814
has body: The ProgressBar widget doesn't support this. However you could create a small colored Frame and use place to put it on top of the progress bar. Example: for i in range(0,4): prgb = ttk.Progressbar(...) ... x = random.random() ... marker = Frame(prgb, width=4, background="red") position = random.uniform(0,x) marker.place(relx=position, rely=.5, anchor="w", relheight=.5) I don't have access to a windows machine, but this is what it looks like on my mac:
type: Answer
upvote count: 3
score: 3
answers question: http://stackoverflow.com/q/51211452
accepted answer of: http://stackoverflow.com/q/51211452

http://stackoverflow.com/comment/89620527
score: 0
comment on: http://stackoverflow.com/q/51322347
type: Comment
type: QuestionComment
has text: Seems to be working, but am I not missing out on the async part this way?

http://stackoverflow.com/comment/89511020
comment on: http://stackoverflow.com/q/51265578
has text: As far as I know, only layers can be set `trainable=False`
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51271854
accepted answer: http://stackoverflow.com/a/51293159
type: Question
tagged with: google-admin-sdk
has body: I'm really struggling with trying to add a new user with this API. I'm following every step at google Directory docs but I failed. from __future__ import print_function from apiclient.discovery import build from httplib2 import Http from oauth2client import file, client, tools # Setup the Admin SDK Directory API SCOPES = 'https://www.googleapis.com/auth/admin.directory.user' store = file.Storage('credentials.json') creds = store.get() if not creds or creds.invalid: flow = client.flow_from_clientsecrets('client_secret.json', SCOPES) creds = tools.run_flow(flow, store) service = build('admin', 'directory_v1', http=creds.authorize(Http())) # Call the Admin SDK Directory API #Insert User body = { "name": {"familyName": "Test", "givenName": "Mahalo"}, "password": "mahalo@test", "primaryEmail": "test@test.com", } user_add = service.users().insert(body=body).execute() When I try the insert method I got this error googleapiclient.errors.HttpError: https://www.googleapis.com/admin/directory/v1/users?alt=json returned "Domain not found."> If I try to run the list method like in the quickstart guide it runs perfect https://developers.google.com/admin-sdk/directory/v1/quickstart/python
has comment: http://stackoverflow.com/comment/89527170
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51293159
has title: Google Directory API insert user
tagged with: django
tagged with: python
type: AnsweredQuestion
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/89563806

http://stackoverflow.com/comment/89392512
has text: @khelwood - Correct, those hash containers which I generally would call buckets need to perform collision recovery using double hashing or one of the probing techniques. All probing algorithms require the container/bucket capacity. Can you hellp me in know what the initial capacity of a python dict is?
score: 0
comment on: http://stackoverflow.com/q/51205726
type: QuestionComment
type: Comment

http://stackoverflow.com/q/51250946
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/89481087
favorite count: 0
has comment: http://stackoverflow.com/comment/89480955
tagged with: python
tagged with: python-3.x
has title: data["comment"].str.contains taking to much time
has comment: http://stackoverflow.com/comment/89480896
answer count: 0
has comment: http://stackoverflow.com/comment/89481316
type: UnansweredQuestion
upvote count: 1
tagged with: dataframe
has body: I have to do a pattern match for a column in my dataset and find the below matches for almost 400,000 rows. It is taking a lot of time to execute. Is there a way to reduce run time or is there a better code for this which gives similar result in less time? monthnames=data["comment"].str.contains("\\bJan\\b|\\bFeb\\b|\\bMar\\b|\\bApr\\ |\\bMay\\b|\\bJun\\b|\\bJul\\b|\\bAug\\b|\\bSep\\b|\\bOct\\b|\\bNov\\b|\\bDec\\b")
type: Question
has comment: http://stackoverflow.com/comment/89480825
has comment: http://stackoverflow.com/comment/89481026

http://stackoverflow.com/q/51243633
has body: I am trying to package a Python 3.6 project which additionally requires compiling CPP code. My test setup.py file currently looks like this: print("Hello world from setup.py") from distutils.command.build import build from setuptools import setup class TestBuild(build): def run(self): print("Hello world from TestBuild") setup( name="Test", cmdclass={ 'build': TestBuild, }, ) The idea here is to place the CPP-compiling code inside TestBuild. When I run python setup.py build it seems to work well: &gt; python setup.py build Hello world from setup.py running build Hello world from TestBuild However, running python setup.py install does not seem to run the build step at all: &gt; python setup.py install Hello world from setup.py running install running bdist_egg running egg_info writing Test.egg-info/PKG-INFO writing top-level names to Test.egg-info/top_level.txt writing dependency_links to Test.egg-info/dependency_links.txt reading manifest file 'Test.egg-info/SOURCES.txt' writing manifest file 'Test.egg-info/SOURCES.txt' installing library code to build/bdist.linux-x86_64/egg running install_lib warning: install_lib: 'build/lib' does not exist -- no Python modules to install creating build/bdist.linux-x86_64/egg creating build/bdist.linux-x86_64/egg/EGG-INFO copying Test.egg-info/PKG-INFO -&gt; build/bdist.linux-x86_64/egg/EGG-INFO copying Test.egg-info/SOURCES.txt -&gt; build/bdist.linux-x86_64/egg/EGG-INFO copying Test.egg-info/dependency_links.txt -&gt; build/bdist.linux-x86_64/egg/EGG-INFO copying Test.egg-info/top_level.txt -&gt; build/bdist.linux-x86_64/egg/EGG-INFO zip_safe flag not set; analyzing archive contents... creating 'dist/Test-0.0.0-py3.5.egg' and adding 'build/bdist.linux-x86_64/egg' to it removing 'build/bdist.linux-x86_64/egg' (and everything under it) Processing Test-0.0.0-py3.5.egg My questions: Does the install command automatically invokes the build command? If it does, what did I do wrong? If it does not, how can I ensure the build command run…
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51245742
tagged with: python
score: 2
downvote count: 0
tagged with: setuptools
type: Question
upvote count: 2
linked to: http://stackoverflow.com/q/11331175
answer count: 1
has title: Python setuptools' "setup.py install" does not automatically call build?
has comment: http://stackoverflow.com/comment/89484299
favorite count: 0

http://stackoverflow.com/q/51229303
downvote count: 0
has answer: http://stackoverflow.com/a/51229314
favorite count: 0
type: Question
upvote count: 2
tagged with: python
answer count: 1
accepted answer: http://stackoverflow.com/a/51229314
has body: I have two pandas dataframes: df1 2014 2015 2016 2017 NY 90 85 84 80 IL 88 79 72 65 VA 75 76 81 79 MD 60 62 66 70 df2 Empty DataFrame Columns: [] Index: [CA, WA, NY, VA, DE, MD, IL] How can I get the following dataframe using the two above? 2014 2015 2016 2017 CA -1 -1 -1 -1 WA -1 -1 -1 -1 NY 90 85 84 80 VA 75 76 81 79 DE -1 -1 -1 -1 MD 60 62 66 70 IL 88 79 72 65
has title: Merging pandas dataframe with an empty dataframe
tagged with: dataframe
tagged with: pandas
score: 2
type: AnsweredQuestion

qtablewidget
tags question: http://stackoverflow.com/q/51175841
type: Tag
tags question: http://stackoverflow.com/q/51271956
tag name: qtablewidget

http://stackoverflow.com/a/51190375
score: 1
has body: Your problem is in this line if x is "%":, is operator checks whether the both are same object. You need to use if x=='%' (== operator checks whether both are same value or not, it's not necessary to be both the same object to return True).
upvote count: 1
has comment: http://stackoverflow.com/comment/89363095
answers question: http://stackoverflow.com/q/51190277
downvote count: 0
type: Answer

http://stackoverflow.com/a/51257538
has comment: http://stackoverflow.com/comment/89515305
has comment: http://stackoverflow.com/comment/89493856
has comment: http://stackoverflow.com/comment/89517627
has body: Try this. You're currently iterating through the list without changing directories. import os import sys import shutil list1= [1,2,3] path = "C:\ladg\oner" root, dirs, files = os.walk(path).next() for dir in dirs: curr_path = os.path.join(root, dir) for i in list1: new_folder_path = os.path.join(curr_path, dir + str(i)) shutil.copytree(curr_path, new_folder_path) os.chdir(new_folder_path) curr_path = new_folder_path In a follow-up question, if you want to achieve a scenario where you have this resulting directory: A -- b -- b1 -- b2 -- b3 -- c -- c1 -- c2 -- c3 You can use the following code. This is different from the first suggestion as now you're creating a tmp_dir to store your copies before finally replacing the old curr_dir with this new tmp_dir. This is necessary to maintain an intact copy of curr_dir when you do subsequent copies. import os import sys import shutil list1= [1,2,3] path = "~/A" root, dirs, files = os.walk(path).next() for dir in dirs: curr_dir = os.path.join(root, dir) tmp_dir = os.path.join(root, "tmp_" + dir) os.mkdir(tmp_dir) for i in list1: new_folder_path = os.path.join(tmp_dir, dir+ str(i)) shutil.copytree(curr_dir, new_folder_path) shutil.rmtree(curr_dir) shutil.move(tmp_dir, curr_dir)
has comment: http://stackoverflow.com/comment/89494241
accepted answer of: http://stackoverflow.com/q/51257312
score: 2
has comment: http://stackoverflow.com/comment/89495352
answers question: http://stackoverflow.com/q/51257312
has comment: http://stackoverflow.com/comment/89523477
has comment: http://stackoverflow.com/comment/89515487
has comment: http://stackoverflow.com/comment/89516062
has comment: http://stackoverflow.com/comment/89515866
has comment: http://stackoverflow.com/comment/89494078
type: AcceptedAnswer
downvote count: 1
has comment: http://stackoverflow.com/comment/89516597
upvote count: 3
has comment: http://stackoverflow.com/comment/89516961
type: Answer

http://stackoverflow.com/a/51171488
upvote count: 1
type: AcceptedAnswer
type: Answer
has body: The floating-point format you are using has 53 bits in its significand. This means it can represent numbers as a 53-bit integer multiplied or divided by a power of two. When 0.9999999999999999 is converted to this format, the closest representable value is (253−1)/253, which is exactly 0.99999999999999988897769753748434595763683319091796875. Note that the numerator uses exactly 53 bits. When you add 1, the mathematical result would be (254−1)/253. The numerator would have 54 bits. This cannot be represented in the floating-point format, so it has to be rounded to fit. The two nearest representable values are: (254−2)/253 = (253−1)/252, and (254−0)/253 = 2. These are both equally far away from the exact mathematically result. The rule for breaking ties is to use the value with a zero in the low bit of its significand. (Even though I have presented the significand as an integer here, it is a “left-adjusted” fraction in the floating-point format, so a numerator of 1 corresponds to the binary numeral 1.000000…0002.) Thus, when 1 is added to 0.9999999999999999, the computed result must be rounded to 2.
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/51170191
answers question: http://stackoverflow.com/q/51170191

http://stackoverflow.com/q/51277066
has comment: http://stackoverflow.com/comment/89532055
type: AnsweredQuestion
score: 2
has title: Find all points below a line on a map
tagged with: matplotlib
has answer: http://stackoverflow.com/a/51277396
type: Question
linked to: http://stackoverflow.com/q/44061823
has body: In order to draw a path between two points on a map with many points (almost two thousand), I use the following function: def path_between_cities(self, cities_with_coordinates, from_to): from matplotlib.lines import Line2D # coordinates from chosen path x = [int(from_to[0][2]), int(from_to[1][2])] y = [int(from_to[0][1]), int(from_to[1][1])] #create line line = Line2D(x,y,linestyle='-',color='k') # create axis x_ = np.array((0,2000)) y_ = np.array((0,6000)) plt.plot(x_,y_, 'o') for item in cities_with_coordinates: name = item[0] y_coord = int(item[1]) x_coord = int(item[2]) plt.plot([x_coord], [y_coord], marker='o', markersize=1, color='blue') plt.axes().add_line(line) plt.axis('scaled') plt.show() My goal is to extract all points (coordinates) which are found below the drawn line. I know that you can do this using the cross product of vectors Given a large number of vectors, what would be the most efficient way of achieving this in the context above?
tagged with: cross-product
has comment: http://stackoverflow.com/comment/89535314
accepted answer: http://stackoverflow.com/a/51277396
answer count: 1
downvote count: 0
favorite count: 0
upvote count: 2
tagged with: computational-geometry
has comment: http://stackoverflow.com/comment/89532012
tagged with: python
has comment: http://stackoverflow.com/comment/89531943
has comment: http://stackoverflow.com/comment/89531995

http://stackoverflow.com/q/51271569
has answer: http://stackoverflow.com/a/51271861
score: 6
answer count: 3
tagged with: pandas
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/51271901
tagged with: python
upvote count: 6
has answer: http://stackoverflow.com/a/51271658
type: AnsweredQuestion
has body: So I have two different data-frame and I concatenated both. All columns are the same; however, the date column has all sorts of different dates in the M/D/YR format. dataframe dates get shuffled around later in the sequence Is there a way to keep the whole dataframe itself and just sort the rows based on the dates in the date column. I also want to keep the format that date is in. so basically date people 6/8/2015 1 7/10/2018 2 6/5/2015 0 gets converted into: date people 6/5/2015 0 6/8/2015 1 7/10/2018 2 Thank you! PS: I've tried the options in the other post on this but it does not work
linked to: http://stackoverflow.com/q/28161356
accepted answer: http://stackoverflow.com/a/51271901
type: Question
has title: Pandas: How to sort dataframe rows by date of one column
possible better answer: http://stackoverflow.com/a/51271861

http://stackoverflow.com/q/51275976
tagged with: python-3.x
answer count: 0
duplicate of: http://stackoverflow.com/q/46842793
type: UnansweredQuestion
has title: Is it possible to extract a format string (e.g. "YY-mm-DD HH:MM:SS.sss") from a python datetime object?
has body: If I have it infer the format when converting a column in pandas to datetimes, is there a way I can go backwards and retrieve the formatting? E.g. if I have columns full of date times like "02-09-1990 10:32PM" and I convert that with with pandas.to_datatime, is there a way to retrieve the format it used out of there? I dug into the functions that to_datetime uses to infer, namely: from pandas._libs.tslibs.parsing import _guess_datetime_format from pandas.core.tools.datetimes import _guess_datetime_format_for_array but I can't get them to actually work and I can't step into their code to figure out why in PyCharm. Anyone have any ideas on this? Thank you.
has comment: http://stackoverflow.com/comment/89530039
downvote count: 1
score: 3
type: Question
upvote count: 4
favorite count: 0
tagged with: pandas
tagged with: datetime
tagged with: python
has comment: http://stackoverflow.com/comment/89530614
linked to: http://stackoverflow.com/q/46842793
has comment: http://stackoverflow.com/comment/89530161

http://stackoverflow.com/a/51313760
has comment: http://stackoverflow.com/comment/89604301
has comment: http://stackoverflow.com/comment/89604540
score: 8
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51313585
has comment: http://stackoverflow.com/comment/89604606
has body: You can use re.findall to do this. import re s = " Quote text This is a title " re.findall(r'<[^>]*>.*?</[^>]*>(?:<[^>]*/>)?|[^<>]+', s) # [' Quote ', 'text ', ' This is a title '] But avoid parsing html data like directly using regex and consider using something like BeautifulSoup >>> from bs4 import BeautifulSoup >>> soup = BeautifulSoup(s, "html.parser") >>> soup.findAll() [ Quote , , This is a title ] >>> soup.findAll()[0].text 'Quote' >>> [s for s in soup.strings] ['Quote', 'text ', 'This is a title']
answers question: http://stackoverflow.com/q/51313585
type: AcceptedAnswer
upvote count: 8
type: Answer

http://stackoverflow.com/comment/89517505
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/51269062
type: Comment
has text: Thank you very much for the effort! Unfortunately I already tried this. I probably was not clear enough, I'm really sorry, but the red dot shall not represent an area with one specific color. The real images are way more complex and so unfortunately I could not get reasonable results for all image patches by using `cv2.findContour`... I need a method to merge the borders, so you cannot see the exact transition of patch to background anymore

http://stackoverflow.com/comment/139100662
has text: No, you provide the positions and/or lines that should be avoided in the function call, and then those are automatically avoided. If you have larger objects in the plot you can also provide the sizes of these along with the positions, or a scatter-plot object to do it automatically.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/74323556
type: AnswerComment

http://stackoverflow.com/a/51313108
score: 2
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51312546
has comment: http://stackoverflow.com/comment/89606997
answers question: http://stackoverflow.com/q/51312546
has comment: http://stackoverflow.com/comment/89606031
has comment: http://stackoverflow.com/comment/89605436
upvote count: 2
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89605110
type: Answer
has comment: http://stackoverflow.com/comment/89606703
has comment: http://stackoverflow.com/comment/89604856
has body: What you are looking for has been extensively studied before, and is known as the hypergeometric distribution in probability theory and statistics. There is thus no need to re-invent the wheel! We are looking for at least one red user, in a sample of varying size x. This is equivalent to 1 - Pr(0 red users | sample size = x), that is, one minus its complement. Let us illustrate this by considering sample sizes in [1, # red users]. Some Python code to help you along, from scipy.stats import hypergeom import matplotlib.pyplot as plt red = 450 total = 7000 sample_sizes = list(range(1, red + 1)) probabilities = [1 - hypergeom(total, red, sample_size).pmf(0) for sample_size in sample_sizes] fig = plt.figure() ax = fig.add_subplot(111) ax.plot(sample_sizes, probabilities, 'bo') ax.set_xlabel('Users drawn (#)') ax.set_ylabel('Probability of at least one red user') plt.show() Which yields the following graph, Clearly, the probability of drawing at least one red user increases rapidly as we increase the size of the sample - nothing we did not expect, given our knowledge of the hypergeometric distribution!

http://stackoverflow.com/comment/89451399
type: QuestionComment
comment on: http://stackoverflow.com/q/51236149
score: 1
has text: @melpomene probably [`os.path.expandvars()`](https://docs.python.org/3.6/library/os.path.html?highlight=expandvars#os.path.expandvars) is a better fit than just accessing environment variables. And I am sure there is some subtlety but how is this not a DOS (`.bat`) script? (I know recents is a windows things but the script itself?).
type: Comment

http://stackoverflow.com/q/51255191
tagged with: android
has title: Using Tensorflow to detect falls and implementing the model in Android
has comment: http://stackoverflow.com/comment/89509574
has comment: http://stackoverflow.com/comment/89524626
has comment: http://stackoverflow.com/comment/89586103
answer count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: machine-learning
tagged with: python
has comment: http://stackoverflow.com/comment/89756264
score: 2
has body: It's my first post on the forum, so please excuse any major errors or stupidities on my part. I'm currently doing a project on fall detection using machine learning. I've seen many examples online about ADL's (Activites of Daily Live) and Tensorflow and tried to use some of them as a basis to my work. For example, this one: https://medium.com/@curiousily/human-activity-recognition-using-lstms-on-android-tensorflow-for-hackers-part-vi-492da5adef64. What I did was use the known WISDM dataset (this one: http://www.cis.fordham.edu/wisdm/dataset.php) as the "Not Falling" examples and found another dataset with 30 fall examples (this one: http://fenix.univ.rzeszow.pl/~mkepski/ds/uf.html). However, I'm encountering some problems regarding the use of the model on the smartphone. Even tough I see, in some cases, accuracy levels of 80-90% and up, when I test the model on an App, the results are horrible. Is it even possible to do it this way? What could be the problem? I've tried numerous ways to mix the datasets, changing the learn rate, the complexity of the model, etc. but still no luck... import pandas as pd import numpy as np import pickle import matplotlib.pyplot as plt from scipy import stats import tensorflow as tf import seaborn as sns from pylab import rcParams from pylab import plot from sklearn import metrics from sklearn.model_selection import train_test_split sns.set(style='whitegrid', palette='muted', font_scale=1.5) rcParams['figure.figsize'] = 14, 8 RANDOM_SEED = 42 columns = ['user','activity','timestamp', 'x-axis', 'y-axis', 'z-axis'] df_train = pd.read_csv('test_4.txt', header = None, names = columns) df_test = pd.read_csv('train_4.txt', header = None, names = columns) print('Data read.') df_train['activity'].value_counts().plot(kind='bar', title='Training examples by activity type'); #df['user'].value_counts().plot(kind='bar', title='Training examples by user'); plt.show() df_test['activity'].value_counts().plot(kind='bar', title='Training examples by act…
tagged with: tensorflow
type: Question
downvote count: 0
tagged with: dataset
favorite count: 0
has comment: http://stackoverflow.com/comment/89563521

http://stackoverflow.com/q/51293154
has answer: http://stackoverflow.com/a/51293331
favorite count: 0
possible better answer: http://stackoverflow.com/a/51293331
accepted answer: http://stackoverflow.com/a/51293332
tagged with: python
tagged with: regex
upvote count: 1
has comment: http://stackoverflow.com/comment/89564092
downvote count: 1
has title: Python Regex - extracting multiple sentences containing same keyword
has comment: http://stackoverflow.com/comment/89564193
type: AnsweredQuestion
has body: import re regex = r"[^.?!-]*(?&lt;=[.?\s!-])\b(pfs)\b(?=[\s.?!-])[^.?!-]*[.?!-]" test_str = "pfs alert conf . it is unlikely that we will sign it - pfs of $ 950 filed to driver - we are gathering information" subst = "" result = re.sub(regex, subst, test_str, 0, re.IGNORECASE | re.MULTILINE) if result: print (result) As we see, test_str has two sentences having keyword 'pfs'. However, the above python code can only extract second sentence ' pfs of $ 950 filed to driver', how to modify it to extract 'pfs alert conf' as well?
has answer: http://stackoverflow.com/a/51293332
type: Question
score: 0
answer count: 2

http://stackoverflow.com/comment/89323418
has text: Ok, see the answer below. In your uwsgi.ini update it to module = wsgi:application
comment on: http://stackoverflow.com/q/51169843
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89370033
has text: That is a pity. But I guess I have to live with that.
comment on: http://stackoverflow.com/a/51175506
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/51187868
has answer: http://stackoverflow.com/a/62148094
score: 4
has comment: http://stackoverflow.com/comment/89357616
upvote count: 4
answer count: 3
tagged with: pandas
has answer: http://stackoverflow.com/a/66491956
downvote count: 0
has comment: http://stackoverflow.com/comment/89357757
has comment: http://stackoverflow.com/comment/89358972
has comment: http://stackoverflow.com/comment/89357526
favorite count: 0
linked to: http://stackoverflow.com/q/51175491
has answer: http://stackoverflow.com/a/51189060
tagged with: python
has title: How do I remove and re-sort (reindex) columns after applying style in python pandas?
has body: Is there a way to remove columns or rows after applying style in python pandas? And re-sort them? styled = df.style.apply(colorize, axis=None) #remove _x columns yonly = list(sorted(set(styled.columns) - set(df.filter(regex='_x$').columns))) ###Remove columns that end with "_x" here styled.to_excel('styled.xlsx', engine='openpyxl', freeze_panes=(1,1)) Most things I tried were unavailable, i.e. styled.reindex(columns=yonly) returned AttributeError: 'Styler' object has no attribute 'reindex' styled.columns = yonly returned AttributeError: 'list' object has no attribute 'get_indexer' styled = styled[yonly] returns TypeError: 'Styler' object is not subscriptable Follow-up from Colour specific cells from two columns that don&#39;t match, using python pandas style.where (or otherwise) and export to excel
accepted answer: http://stackoverflow.com/a/51189060
type: Question
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/62148094

http://stackoverflow.com/q/51256964
has comment: http://stackoverflow.com/comment/89492697
type: AnsweredQuestion
has body: My input has a shape: (9, 480, 1) Here is my current function: def f(X): ordered_max_scorers = np.sort(np.max(X, axis=2), axis=1) cd_mat2 = np.array([[0] * len(X)] * len(X), dtype="float64") for ind1, score1 in enumerate(ordered_max_scorers): for ind2, score2 in enumerate(ordered_max_scorers[:ind1]): cognitive_diversity = np.sum((score1 - score2)**2)**(1/2) cd_mat2[ind1][ind2] = cognitive_diversity cd_mat2[ind2][ind1] = cognitive_diversity return cd_mat2 And I am trying to optimize this function so that it runs faster: It is called once by an object B within an object A. B is called a few hundred times everytime A runs (about 2 dozen times) if that makes a difference. I have tried to use a bit of numpy by replacing: cognitive_diversity = np.sum((score1 - score2) ** 2) ** (1/2) with: cognitive_diversity = np.sqrt(np.sum(np.square(score1 - score2))) But that seems to slow the code down. I also tried to optimize using numba: @autojit def temp(x, y): return np.sum((score1 - score2) ** 2) ** (1/2) Which is used for cognitive_diversity again. cognitive_diversity = temp(score1, score2) But it also slowed the code down a lot If anyone has any suggestions for the speed up or any suggestions how to properly re-write the loop to speed it up that would be amazing! EDIT Thank you for the assistance. I used it to come up with a slightly different solution. #Std jit optimization @jit() def cd_matrix_jit(oms,l_oms,l_oms2,cd_mat2): for ind1 in range(l_oms): for ind2 in range(l_oms): d=0.0 for i in range(l_oms2): d = d + (oms[ind1,i]-oms[ind2,i])**2 cd_mat2[ind1,ind2] = d**(1/2) return cd_mat2
tagged with: math
has title: python matrix optimization
score: -1
type: Question
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/89492811
downvote count: 1
has comment: http://stackoverflow.com/comment/89492704
tagged with: python
has answer: http://stackoverflow.com/a/51257177
accepted answer: http://stackoverflow.com/a/51257177
upvote count: 0

http://stackoverflow.com/comment/89344590
comment on: http://stackoverflow.com/a/51180953
type: Comment
has text: Following jpps' suggestion, what does `df['B'].iloc[2] == ''` print ?
score: 0
type: AnswerComment

http://stackoverflow.com/a/51316394
has comment: http://stackoverflow.com/comment/89708193
score: 0
type: Answer
has body: Open up each file, iterate through each line. Append to new file based on value after split of line. with open("&lt;FILENAME&gt;.txt") as FileObj: for line in FileObj: x = line.strip().split()[1] if (x &gt; "2.5"): file = open("&lt;FILENAME&gt;.csv","a") file.write(line) file.close
answers question: http://stackoverflow.com/q/51316221

http://stackoverflow.com/comment/89425127
has text: I need some more information. Can you edit your question to post with your code? How about reading [this](https://stackoverflow.com/help/how-to-ask)?
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51222304

http://stackoverflow.com/comment/89386364
has text: I tried with out XVFB also same issue. I killed the running process for XVFB but issue still persist.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51183229
score: 0

http://stackoverflow.com/comment/89431696
type: Comment
has text: Dude, you are genius' Shame on me' Oh god It works finally, even after all those django project official django auth customization guide, I made a silly mistake. I should die In shame now :p
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51225499

http://stackoverflow.com/q/51270927
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/89520182
has body: import pandas as pd import numpy as np import tensorflow as tf dataframe = pd.read_csv("data.csv") dataframe = dataframe.drop(["id"], axis = 1) train = dataframe[1:250] test = dataframe[251:569] dataY = train["diagnosis"] for key,value in dataY.iteritems(): if value == "M": dataY[key] = 1 if value == "B": dataY[key] = 0 dataY = np.asarray(dataY) dataX = np.asarray(train.drop(["diagnosis"], axis = 1)) trainRows = len(train) trainColumns = len(dataframe.columns)-1 inputX = tf.placeholder(tf.float32, [trainRows, trainColumns]) inputY = tf.placeholder(tf.float32, [trainRows]) W = tf.Variable(tf.zeros([trainColumns, trainRows])) b = tf.Variable(tf.zeros([trainRows])) Y_compare = tf.nn.softmax(tf.matmul(inputX, W)+b) cross_entropy = -tf.reduce_sum(inputY * tf.log(Y_compare)) optimizer = tf.train.GradientDescentOptimizer(.001) trainer = optimizer.minimize(cross_entropy) init = tf.global_variables_initializer() sess = tf.Session() sess.run(init) for step in range(1000): sess.run(trainer, feed_dict={inputX: dataX, inputY: dataY}) print(sess.run(cross_entropy, feed_dict={inputX: dataX, inputY: dataY})) sess.close() When I run this code it just prints nan for every step. I tried changing the error function, but it didn't make a difference. I am pretty sure the issue is either with the error function or the optimizer. Any ideas on what the problem? The data is on breast cancer diagnosis: This is inputX: [[ 20.57 17.77 132.9 1326. ] [ 19.69 21.25 130. 1203. ] [ 11.42 20.38 77.58 386.1 ] [ 20.29 14.34 135.1 1297. ] [ 12.45 15.7 82.57 477.1 ] [ 18.25 19.98 119.6 1040. ] [ 13.71 20.83 90.2 577.9 ] [ 13. 21.82 87.5 519.8 ] [ 12.46 24.04 83.97 475.9 ] [ 16.02 23.24 102.7 797.8 ] [ 15.78 17.89 103.6 781. ] [ 19.17 24.8 132.4 1123. ] [ 15.85 23.95 103.7 782.7 ] [ 13.73 22.61 93.6 578.3 ] [ 14.54 27.54 96.73 658.8 ] [ 14.68 20.13 94.74 684.5 ] [ 16.13 20.68 108.1 798.8 ] [ 19.81 22.15 130. 1260. ] [ 13.54 14.36 87.46 566.3 ] [ 13.08 15.71 85.63 520. ] [ 9.504 12.44 60.34 273.9 ] [ 15.34…
type: Question
score: 0
tagged with: neural-network
has comment: http://stackoverflow.com/comment/89520719
tagged with: python
has title: Tensorflow outputs NaN for Cross Entropy
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89521731

http://stackoverflow.com/a/64718173
score: 16
answers question: http://stackoverflow.com/q/51244223
has body: --key1 value1 value2 --key2 value3 value4 can be passed as "args": ["--key1=value1", "value2", "--key2=value3", "value4"] (Combining the two answers by Pawan Kumar and Chunde Huang.)
upvote count: 16
type: Answer
downvote count: 0

http://stackoverflow.com/comment/89481621
type: AnswerComment
comment on: http://stackoverflow.com/a/51250556
score: 0
type: Comment
has text: I was reading `ascii_uppercase`, my understanding is I am stuck at 26 columns for now unless, there is a way to concatenate `ascii_uppercase` characters to go more than 26 columns. i.e. In excel, after `Z`, it is `AA`, `AB` etc..

http://stackoverflow.com/comment/89385623
type: Comment
type: QuestionComment
has text: *"... gives me a memory error."* 0/0 results in `nan`, so the result of `A/B` is not sparsely populated. It is full of `nan` values, along with `inf` where `A` is nonzero but `B` is zero, and those values must be stored in memory.
score: 1
comment on: http://stackoverflow.com/q/51202024

http://stackoverflow.com/comment/89539097
comment on: http://stackoverflow.com/q/51280064
score: 0
has text: could you upload your `django_project/urls.py`? <= never mind I found it above
type: QuestionComment
type: Comment

http://stackoverflow.com/q/51271225
tagged with: python
has body: header output: array(['Subject_ID', 'tube_label', 'sample_#', 'Relabel', 'sample_ID','cortisol_value', 'Group'], dtype='&lt;U14') body output: array([['STM002', '170714_STM002_1', 1, 1, 1, 1.98, 'HC'], ['STM002', '170714_STM002_2', 2, 2, 2, 2.44, 'HC'],], dtype=object) testing = np.concatenate((header, body), axis=0) ValueError Traceback (most recent call last) &lt;ipython-input-302-efb002602b4b&gt; in &lt;module&gt;() 1 # Merge names and the rest of the data in np array 2 ----&gt; 3 testing = np.concatenate((header, body), axis=0) ValueError: all the input arrays must have same number of dimensions Might someone be able to troubleshoot this? I have tried different commands to merge the two (including stack) and am getting the same error. The dimensions (columns) do seem to be the same though.
tagged with: valueerror
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51271322
has answer: http://stackoverflow.com/a/51271323
type: Question
tagged with: numpy
has title: Concatenating two NumPy arrays gives "ValueError: all the input arrays must have same number of dimensions"
tagged with: arrays
possible better answer: http://stackoverflow.com/a/51271499
has answer: http://stackoverflow.com/a/51271499
answer count: 3
tagged with: concatenation
score: 2
has comment: http://stackoverflow.com/comment/89520594
downvote count: 0
favorite count: 0
linked to: http://stackoverflow.com/q/29241056
has answer: http://stackoverflow.com/a/51271322
upvote count: 2

http://stackoverflow.com/comment/89598667
score: 0
comment on: http://stackoverflow.com/q/51310649
has text: To find out whether you've set up the processes "correctly", run your code. Trace the execution with `print` statements. Work in stages, rather than trying to write the entire design at once. Debugging is a *lot* easier when you're tracking only one problem at a time. I've learned this last item from experience both ways. :-)
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89434484
score: 0
comment on: http://stackoverflow.com/q/51227101
type: Comment
type: QuestionComment
has text: So why vote to close something when Googling 'Value doesn't support membership test' doesn't yield an answer. Never quite got that.

command
tags question: http://stackoverflow.com/q/51174403
tags question: http://stackoverflow.com/q/51174135
tag name: command
tags question: http://stackoverflow.com/q/51272159
type: Tag

http://stackoverflow.com/a/51205584
has body: The problem is that this code p = et.Element("p") child = et.SubElement(p, "s" ) is creating a new &lt;p&gt; element, which is not part of the tree, and attaching a subelement to it. The tree itself is left unchanged. Attach the new subelement to the &lt;p&gt; element that you find in the tree instead. &gt;&gt;&gt; for elem in root: ... if elem.tag == 'p': ... ET.SubElement(elem, 's') ... &lt;Element 's' at 0x7f7810b24e58&gt; &lt;Element 's' at 0x7f780ffdf4f8&gt; &gt;&gt;&gt; ET.tostring(root) b'&lt;text&gt;&lt;p&gt;&lt;s /&gt;&lt;/p&gt;&lt;p&gt;&lt;s /&gt;&lt;/p&gt;&lt;/text&gt;'
type: AcceptedAnswer
score: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/51199765
answers question: http://stackoverflow.com/q/51199765

http://stackoverflow.com/comment/97285562
type: Comment
has text: Thank you! I tested it and you're right. I accepted your answer as this is the one containing no breaking cases that I know of for now.
type: AnswerComment
comment on: http://stackoverflow.com/a/55200461
score: 0

http://stackoverflow.com/a/51279001
score: 3
type: Answer
upvote count: 3
accepted answer of: http://stackoverflow.com/q/51248709
answers question: http://stackoverflow.com/q/51248709
type: AcceptedAnswer
downvote count: 0
has body: The issue only arises when we use cv2.imshow(winname, mat) inside a subscriber's callback function; other OpenCV functions work normally, but this seems to be a bug. One way to overcome this is by analyzing each frame like this: while not rospy.is_shutdown(): data = rospy.wait_for_message(topic, topic_type) # do stuff cv2.imshow(winname, mat) cv2.waitKey(delay) instead of this: def callback(data): # do stuff cv2.imshow(winname, mat) cv2.waitKey(delay) rospy.subscribe(name, data_class, callback=callback) rospy.spin()

http://stackoverflow.com/comment/89348015
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51182746
has text: Is there anyway else when I received data from backend like that? Why we have to push the data to API endpoint, then query again? Why don't directly use it? I have just learned angularjs and bottle a few days ago.

http://stackoverflow.com/a/52704238
has body: From google documentation, you can find how the API response is structured (BLOCK, PARAGRAPH, ...) and how to retrieve corresponding vertices. Particularly this function: def get_document_bounds(image_file, feature): """Returns document bounds given an image.""" client = vision.ImageAnnotatorClient() bounds = [] with io.open(image_file, 'rb') as image_file: content = image_file.read() image = types.Image(content=content) response = client.document_text_detection(image=image) document = response.full_text_annotation # Collect specified feature bounds by enumerating all document features for page in document.pages: for block in page.blocks: for paragraph in block.paragraphs: for word in paragraph.words: for symbol in word.symbols: if (feature == FeatureType.SYMBOL): bounds.append(symbol.bounding_box) if (feature == FeatureType.WORD): bounds.append(word.bounding_box) if (feature == FeatureType.PARA): bounds.append(paragraph.bounding_box) if (feature == FeatureType.BLOCK): bounds.append(block.bounding_box) if (feature == FeatureType.PAGE): bounds.append(block.bounding_box) # The list `bounds` contains the coordinates of the bounding boxes. return bounds
downvote count: 1
score: -1
upvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/51223852

http://stackoverflow.com/a/51262544
has comment: http://stackoverflow.com/comment/89503215
type: Answer
accepted answer of: http://stackoverflow.com/q/51262477
score: 5
upvote count: 5
has body: Yes. numpy.seterr(divide='raise') The numpy.seterr also allows you to define behaviour for overflow, underflow, invalid operations etc. The possible behaviours are error, warning, ignoring the problem, calling a handler function, or just logging the error
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51262477

http://stackoverflow.com/a/51238090
upvote count: 1
type: AcceptedAnswer
has body: The smaller string must be repeated at least m times for the larger string to be contained within. The minimum value that m can assume is the smallest integer greater than the ratio of the lengths of two strings (larger / smaller), because, to contain a substring of length l, a string must have at least length l. Using the example you shared. A = "abcd" B = "cdabcdab" m0 = len(B) / len(A) # m0 == 2.0 m = math.ceil(m0) # m = 2 However, "cdabcdab" is not contained in "abcdabcd". But, if we repeat "abcd" 1 more time, we find that "cdabcdab" is then a substring. Repeating "abcd" further doesn't change whether it may be found as a substring or not. So, it is only necessary to check containment for m &amp; (m+1) repetitions. The python code you shared does not implement any searching algorithm, it just uses whatever searching algorithm is implemented for use with in. The specific algorithm might be implementation dependent, however there is a high likelihood for it to be boyer-moore or a variation of, as it is popular &amp; efficient. edit: the algorithm behind B in A appears to be boyer-moore in cpython
has comment: http://stackoverflow.com/comment/89455191
type: Answer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51237938
score: 1
answers question: http://stackoverflow.com/q/51237938

http://stackoverflow.com/comment/89478456
comment on: http://stackoverflow.com/q/51249630
type: Comment
has text: @coldspeed i added the required quotes
score: 0
type: QuestionComment

http://stackoverflow.com/q/51286999
has answer: http://stackoverflow.com/a/51287198
tagged with: regex
has body: I have a line that needs to be transformed from weekdays to weekday numbers, i.e. mon_fri -> 0_4. I created a small tool using a dict: line = 'mon_fri' replacement_dict = { 'mon': '0', 'tue': '1', 'wed': '2', 'thu': '3', 'fri': '4', 'sat': '5', 'sun': '6' } for pattern, replacement in replacement_dict.items(): line = line.replace(pattern, replacement) print(line) but there is a way to do it via one regular expression using groups. I cannot get my head around named groups in regex; what would be the proper syntax for this?
has comment: http://stackoverflow.com/comment/89551813
has answer: http://stackoverflow.com/a/51287287
type: UnansweredQuestion
tagged with: python
has title: python regex for group replacements
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/89551983
score: 0

http://stackoverflow.com/q/51301647
tagged with: differentiation
type: Question
has title: Calculating acceleration by numerical differentiation in Python
has answer: http://stackoverflow.com/a/51308509
tagged with: python
has body: From stylus movement measurements I got two measurements: the time and the distance. So I have two arrays, first an array of timestamps (in milliseconds) and then an array of the same size of distance measurements. For example the two arrays could look like: distance = [1.4142,1.0000,1,0,1.0000,1.0000,0,0,1.0000,1.0000,0,1.0000,2.0000,2.2361,0,3.0000,3.6056,3.1623,3.1623,0,3.6056,3.1623,3.1623,0,1.4142,2.2361,1.0000,0,0] timestamps = [1563203.5,1563208,1563210.5,1563213.5,1563218.5,1563223.5,1563226.5,1563229,1563233.5,1563238.5,1563242.5,1563245,1563248.5,1563253.5,1563258,1563260.5,1563263.5,1563268.5,1563273.5,1563276.5,1563279,1563283.5,1563288.5,1563292.5,1563295,1563298.5,1563303.5,1563307,1563317.5] I think the first derivative gives me the speed and the second derivative gives me the acceleration. I'm interested in calculating the acceleration using numerical differentiation. How can this be done in python?
tagged with: differential-equations
score: 0
answer count: 2
accepted answer: http://stackoverflow.com/a/51308509
has comment: http://stackoverflow.com/comment/89586679
tagged with: numerical
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51326741
tagged with: numerical-methods
has comment: http://stackoverflow.com/comment/89586071
possible better answer: http://stackoverflow.com/a/51326741

http://stackoverflow.com/a/51288026
has comment: http://stackoverflow.com/comment/89601714
has comment: http://stackoverflow.com/comment/89555815
answers question: http://stackoverflow.com/q/51287713
has comment: http://stackoverflow.com/comment/89553755
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/89599672
has body: There are a few issues with your code. You use lists instead of numpy.ndarray: the numpy and scipy routines are meant to work with numpy.ndarray and they use them internally. You should use them as well. You are likely to get overflow issues with your data and your function, e.g. np.exp(-1000) is already approximated to zero in Python3 You are trying to fit a function that it is unlikely to fit your data. It looks more like an exponential recovery than a decay. The following code tentatively address all these issues: import numpy as np import matplotlib.pyplot as plt from scipy.optimize import curve_fit def func(x, a, b, c): return a * (1 - np.exp(-b * x)) + c x = np.array([333.0,500.0,1000.0,2000.0,5000.0,10000.0]) / 1000 y = np.array([195.3267, 233.0235, 264.5914,294.8728, 328.3523,345.4688]) / 10 popt, pcov = curve_fit(func, x, y) print(popt) plt.figure() plt.plot(x, y, 'ko', label="Original Noised Data") plt.plot(x, func(x, *popt), 'r-', label="Fitted Curve") plt.legend() plt.show()
has comment: http://stackoverflow.com/comment/89554598
has comment: http://stackoverflow.com/comment/89554130
type: Answer
has comment: http://stackoverflow.com/comment/89555693
has comment: http://stackoverflow.com/comment/89553918
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/51287713

selenium-webdriver
tags question: http://stackoverflow.com/q/51205593
tags question: http://stackoverflow.com/q/51306375
tags question: http://stackoverflow.com/q/51279368
tags question: http://stackoverflow.com/q/51320135
tags question: http://stackoverflow.com/q/51313226
tags question: http://stackoverflow.com/q/51237273
tags question: http://stackoverflow.com/q/51187933
tags question: http://stackoverflow.com/q/51323354
tags question: http://stackoverflow.com/q/51276893
tags question: http://stackoverflow.com/q/51230824
tags question: http://stackoverflow.com/q/51276635
tags question: http://stackoverflow.com/q/51175323
tags question: http://stackoverflow.com/q/51312031
tags question: http://stackoverflow.com/q/51240272
tags question: http://stackoverflow.com/q/51207625
tags question: http://stackoverflow.com/q/51236252
tags question: http://stackoverflow.com/q/51181487
tags question: http://stackoverflow.com/q/51188180
tags question: http://stackoverflow.com/q/51195502
tags question: http://stackoverflow.com/q/51188330
tags question: http://stackoverflow.com/q/51175638
tags question: http://stackoverflow.com/q/51198774
tags question: http://stackoverflow.com/q/51279921
tags question: http://stackoverflow.com/q/51266235
tags question: http://stackoverflow.com/q/51199515
tags question: http://stackoverflow.com/q/51217618
tag name: selenium-webdriver
tags question: http://stackoverflow.com/q/51224314
tags question: http://stackoverflow.com/q/51248734
tags question: http://stackoverflow.com/q/51250668
tags question: http://stackoverflow.com/q/51206143
tags question: http://stackoverflow.com/q/51223809
tags question: http://stackoverflow.com/q/51261038
tags question: http://stackoverflow.com/q/51263444
tags question: http://stackoverflow.com/q/51314737
tags question: http://stackoverflow.com/q/51180363
tags question: http://stackoverflow.com/q/51323686
tags question: http://stackoverflow.com/q/51285004
tags question: http://stackoverflow.com/q/51233901
tags question: http://stackoverflow.com/q/51286846
tags question: http://stackoverflow.com/q/51207243
tags question: http://stackoverflow.com/q/51310047
tags question: http://stackoverflow.com/q/51302719
tags question: http://stackoverflow.com/q/51261145
tags question: http://stackoverflow.com/q/51199698
tags question: http://stackoverflow.com/q/51233325
tags question: http://stackoverflow.com/q/51238738
tags question: http://stackoverflow.com/q/51250461
type: Tag
tags question: http://stackoverflow.com/q/51194590
tags question: http://stackoverflow.com/q/51252089
tags question: http://stackoverflow.com/q/51239600
tags question: http://stackoverflow.com/q/51243354
tags question: http://stackoverflow.com/q/51223174
tags question: http://stackoverflow.com/q/51243290
tags question: http://stackoverflow.com/q/51229547
tags question: http://stackoverflow.com/q/51286403
tags question: http://stackoverflow.com/q/51251783
tags question: http://stackoverflow.com/q/51239512
tags question: http://stackoverflow.com/q/51246962

http://stackoverflow.com/comment/89613557
has text: what if @gmail.com is in the middle of the string
type: AnswerComment
comment on: http://stackoverflow.com/a/51318820
score: 0
type: Comment

http://stackoverflow.com/q/51265888
tagged with: dataframe
has title: python: how to sum unique elements respectively of a dataframe column based on another column
type: Question
upvote count: 1
answer count: 1
favorite count: 0
tagged with: pandas
tagged with: python
accepted answer: http://stackoverflow.com/a/51265966
downvote count: 0
has body: For example, I have a df with two columns. Input df = pd.DataFrame({'user_id':list('aaabbbccc'),'label':[0,0,1,0,0,2,0,1,2]}) print('df\n',df) Output df label user_id 0 0 a 1 0 a 2 1 a 3 0 b 4 0 b 5 2 b 6 0 c 7 1 c 8 2 c I want to count the element in label group by user_id respectively. The expected output is shown as follow. Expected df label user_id label_0 label_1 label_2 0 0 a 2 1 0 1 0 a 2 1 0 2 1 a 2 1 0 3 0 b 2 0 1 4 0 b 2 0 1 5 2 b 2 0 1 6 0 c 1 1 1 7 1 c 1 1 1 8 2 c 1 1 1 Briefly, in column label_0, I count the number of 0 in column label based on column user_id. Hopefully for help!
has answer: http://stackoverflow.com/a/51265966
type: AnsweredQuestion
score: 1

http://stackoverflow.com/comment/89362493
score: 3
has text: Possible duplicate of [How to have an image appear in python/pygame](https://stackoverflow.com/questions/8767129/how-to-have-an-image-appear-in-python-pygame)
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51190354

http://stackoverflow.com/q/51302903
tagged with: machine-learning
upvote count: 1
tagged with: python
tagged with: nlp
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51308268
score: 1
type: Question
tagged with: feature-extraction
downvote count: 0
tagged with: pandas
has body: Here I'm working with a Sentiment Classification problem, where I have to predict whether the tweets are positive, negative or neutral. Here's a glimpse of my dataset: tweet_id airline_sentiment_confidence negativereason negativereason_confidence airline name retweet_count text tweet_created tweet location user_timezone airline_sentiment Tr_tweet_1 1.000 NaN NaN Virgin America 0 tweets date Location Time Positive Tr_tweet_2 0.3846 NaN 0.7033 Virgin America 0 tweets date Location Time Negative Tr_tweet_3 0.6837 Bad flight 0.3342 Virgin America 0 tweets date Location Time Negative Tr_tweet_4 1.000 Can't tell 1.000 Virgin America 0 tweets date Location Time Neutral Tr_tweet_5 1.000 NaN NaN Virgin America 0 tweets date Location Time Neutral However text is the column which I'm fitting in my TfIdf_Vectorizer and using logreg to predict the sentiment. However I'm getting a very low accuracy of ~68%, which turns out to be a pure NLP problem. However the other features will surely increase my accuracy if I can somehow use them. I'm interested in knowing how can I combine the other numerical as well as textual columns like negativereason as features with my text column, to increase my accuracy. Or is there any method of stacking that can be done here? Like combining the predictions of Tfidf and then once again doing prediction with rest numerical columns? TL;DR How to deal with numerical as well as textual columns as features to make a good prediction?
has answer: http://stackoverflow.com/a/51308268
answer count: 1
has title: Combining Text and Numerical Columns for ML Algorithm
favorite count: 0

http://stackoverflow.com/q/51173035
has body: I currently have a box plot which plots cgpa vs totalScore for the subject 'Mathematics'. Here is the code for the box plot: a = sns.boxplot(data=masterdata[masterdata.courseName == "Mathematics"], x = "totalScore", y="cgpa") How can I transform the box plot I have to a scatter plot? I don't know how to select the specific subject of 'Mathematics' in the scatter plot. Scatter plots just have x-label, y-label and hue. But how do I plot for "Mathematics" only, like I did in the box plot I have? Thank you in advance for your help.
has title: Convert a boxplot to a scatter plot in seaborn
answer count: 1
downvote count: 0
favorite count: 0
tagged with: seaborn
has answer: http://stackoverflow.com/a/51175379
accepted answer: http://stackoverflow.com/a/51175379
tagged with: python
score: 2
type: AnsweredQuestion
upvote count: 2
type: Question

http://stackoverflow.com/comment/89485973
has text: @MikeMcKerns I did this, and indeed, the problem still persists. Any idea what I could do now?
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51210305
score: 0

http://stackoverflow.com/comment/89625032
has text: @jpp - I try a bit, but it should be better, [so post question](https://stackoverflow.com/questions/51325032/converting-exponential-notation-numbers-to-strings-explanation)
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/51324589
type: Comment

http://stackoverflow.com/comment/137544033
has text: Also, note that you can run the duckdb CLI instead of using Python: `./duckdb -c "COPY(SELECT * FROM 'path/to/file.parquet') TO 'path/to/file.csv' (HEADER, FORMAT 'csv')"`
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/76584719

http://stackoverflow.com/a/51197809
has comment: http://stackoverflow.com/comment/89377771
score: 0
has comment: http://stackoverflow.com/comment/89378026
has body: There's no good reason to make a recursive function in a class a static method unless it is meant to be invoked outside the context of an instance. To initialize a parameter, we usually assign to it a default value in the parameter list, but in case it needs to be a mutable object such as an empty list in this case, you need to default it to None and the initialize it inside the function, so that the list reference won't get reused in the next call: class Myclass(object): def _get_key_list(self, d, keylist=None): if keylist is None: keylist = [] for key, value in d.iteritems(): keylist.append(key) if isinstance(value, dict): self._get_key_list(d.get(key), keylist) return list(set(keylist)) def diff(self, dict2): all_keys1 = self._get_key_list(self.d) all_keys2 = self._get_key_list(dict2) ... # More code
has comment: http://stackoverflow.com/comment/89378116
has comment: http://stackoverflow.com/comment/89377560
type: Answer
has comment: http://stackoverflow.com/comment/89377582
answers question: http://stackoverflow.com/q/51197695
has comment: http://stackoverflow.com/comment/89377632
has comment: http://stackoverflow.com/comment/89377521
has comment: http://stackoverflow.com/comment/89377384
has comment: http://stackoverflow.com/comment/89377727
has comment: http://stackoverflow.com/comment/89377657
has comment: http://stackoverflow.com/comment/89378233
has comment: http://stackoverflow.com/comment/89378044
has comment: http://stackoverflow.com/comment/89377616

http://stackoverflow.com/comment/89325975
type: AnswerComment
has text: "It is advised in python that you avoid as much as possible to use for loops" => Definitly not. What is advised (and not only in Python) is to avoid writing inefficient code when there's a known efficient solution that isn't more (or much more) complicated to implement.
type: Comment
score: 2
comment on: http://stackoverflow.com/a/51171418

http://stackoverflow.com/comment/89483994
type: QuestionComment
has text: Absolutely. It's literally a million times safer than SHA2-256.
comment on: http://stackoverflow.com/q/51251668
score: 0
type: Comment

http://stackoverflow.com/q/51203902
has comment: http://stackoverflow.com/comment/89456143
has comment: http://stackoverflow.com/comment/90425131
tagged with: python
score: 10
has answer: http://stackoverflow.com/a/51738743
has comment: http://stackoverflow.com/comment/89456036
answer count: 1
tagged with: opencv
tagged with: algorithm
has comment: http://stackoverflow.com/comment/89495954
tagged with: image-processing
upvote count: 10
has title: Connect the nearest points in segment and label segment
has comment: http://stackoverflow.com/comment/90425128
tagged with: image-segmentation
accepted answer: http://stackoverflow.com/a/51738743
type: AnsweredQuestion
has body: I using Open CV and skimage for document analysis of datasheets. I am trying to segment out the shade region separately . I am currently able to segment out the part and number as different clusters. Using felzenszwalb() from skimage I segment the parts: import matplotlib.pyplot as plt import numpy as np from skimage.segmentation import felzenszwalb from skimage.io import imread img = imread('test.jpg') segments_fz = felzenszwalb(img, scale=100, sigma=0.2, min_size=50) print("Felzenszwalb number of segments {}".format(len(np.unique(segments_fz)))) plt.imshow(segments_fz) plt.tight_layout() plt.show() But not able to connect them. Any idea to connect methodically and label out the corresponding segment with part and part number would of great help . Thanks in advance for your time – if I’ve missed out anything, over- or under-emphasised a specific point let me know in the comments.
downvote count: 0
has comment: http://stackoverflow.com/comment/89470308
has comment: http://stackoverflow.com/comment/90425065
favorite count: 0
has comment: http://stackoverflow.com/comment/89478309
type: Question

http://stackoverflow.com/comment/89351558
score: 3
comment on: http://stackoverflow.com/q/51184866
type: Comment
type: QuestionComment
has text: You missed `as_view` method for `HTMLALIView` in `urls.py` : `url(r'^html/', HTMLAPIView.as_view(), name='html' ) `

http://stackoverflow.com/comment/89462160
comment on: http://stackoverflow.com/q/51241363
type: Comment
has text: The documentation is very clear about rate limiting. You will find rate limiting quote and information in ```resource``` endpoint response header. ```X-RateLimit-Limit``` means **Number of api calls you can**, ```X-RateLimit-Remaining``` means **remaining api call limit within specific time frame**, ```X-RateLimit-Reset``` means **when rate limiting will be reset to normal**. So, whenever you want to know about rate limit you will have to call ```https://api.sendgrid.com/v3/resource``` endpoint to know that.
type: QuestionComment
score: 1

http://stackoverflow.com/q/51222202
score: 0
has answer: http://stackoverflow.com/a/51272939
answer count: 1
tagged with: spacy
has body: I'm trying to run the following sentence compression locally: https://github.com/zhaohengyang/Generate-Parallel-Data-for-Sentence-Compression So I copied the files and installed all dependencies with conda. I have made minor modifications such as reading the data from url instead of local disk and placed his parallel_data_gen.py bundled in my single py file. However when I run it I get: Spacy library couldn't parse sentence into a tree. Please ignore this sentence pair ----------------59------------------- reducing sentence: This year the Venezuelan government plans to continue its pace of land expropriations in order to move towards what it terms ``agrarian socialism''. reducing headline: Venezuelan government to continue pace of land expropriations for ``agrarian socialism'' Traceback (most recent call last): File "/home/user/dev/projects/python-snippets/zhaohengyang/sentence-compression.py", line 701, in &lt;module&gt; reduce_sentence(sample) File "/home/user/dev/projects/python-snippets/zhaohengyang/sentence-compression.py", line 641, in reduce_sentence sentence_info = parse_info(sentence) File "/home/user/dev/projects/python-snippets/zhaohengyang/sentence-compression.py", line 616, in parse_info heads = [index + item[0] for index, item in enumerate(doc.to_array([HEAD]))] IndexError: invalid index to scalar variable. I'm not sure how to fix that as i'm a rather newbie python user. Here is the full code i'm running to reproduce the problem: https://gist.github.com/avidanyum/3edfbc96ea22807445ab5307830d41db The internal snippet that fails: def parse_info(sentence): doc = nlp(sentence) heads = [index + item[0] for index, item in enumerate(doc.to_array([HEAD]))] and here is now I loaded the nlp: import spacy print('if you didnt run: python -m spacy download en') import spacy.lang.en nlp = spacy.load('en') More info about my env: /home/user/home/user/dev/anaconda3/envs/pymachine/bin/python --version Python 2.7.15 :: Anaconda, Inc.
tagged with: python
has title: invalid index to scalar variable on spacy array enumerate
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51272939
type: Question

http://stackoverflow.com/comment/89555696
comment on: http://stackoverflow.com/q/51286678
score: 0
type: Comment
type: QuestionComment
has text: Thanks @Alasdair.. It worked for me.

http://stackoverflow.com/comment/89367090
has text: Thanks @nosklo , I added the taceback
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51192460
type: AnswerComment

http://stackoverflow.com/comment/89417210
has text: The error message quite clearly states `ImportError: No module named 'tres'`, so you simply have an import which it cannot find.
comment on: http://stackoverflow.com/q/51218025
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51200747
answer count: 1
has answer: http://stackoverflow.com/a/51200875
type: UnansweredQuestion
tagged with: python
tagged with: excel
tagged with: openpyxl
type: Question
has body: I have few .xlsx files in a folder. Each file contains over 30 worksheets. I'm trying to keep a specific sheet (same name) in each file (usually the last sheet of each file). The code below only works on one file in the folder; it does not go through each of them. import openpyxl, glob for file in glob.glob('*.xlsx'): wb = openpyxl.load_workbook(file) for sheetName in wb.worksheets: if sheetName.title != 'abc': wb.remove(sheetName) wb.save(file) What am I doing wrong?
has title: Keep the last worksheet of all the .xlsx within one folder
score: 0

mbcs
type: Tag
tag name: mbcs
tags question: http://stackoverflow.com/q/51245983

http://stackoverflow.com/q/51277238
has comment: http://stackoverflow.com/comment/89532069
tagged with: text
has comment: http://stackoverflow.com/comment/89532152
has title: How do I add multiple user inputs to a text file?
score: 0
has body: I'm trying to figure out how to list user inputs without overwriting the previous text inputted, but instead adding more into it infinitely. This is my code so far: def main(): domain=input('Enter domain: ') email=input('Enter your email or username: ') password=input('Enter your password: ') text_file = open("Data.txt", "w") text_file.write("Domain of login: "+domain+'\n'+"Email/username: "+email+'\n'+"Password: "+password) text_file=open("Data.txt", "r") text = text_file.read() print(text) text_file.close() main() This is the output example: Domain of login: Facebook.com Email/username: 1234567@email.com Password: pas5word This is the concept I'm trying to aim for: Domain of login: Facebook.com Email/username: 1234567@email.com Password: pas5word Domain of login: Youtube.com Email/username: 1234567@email.com Password: pas5word2 Domain of login: Twitter.com Email/username: 54321@email.com Password: pas5word3
type: Question
linked to: http://stackoverflow.com/q/4706499
duplicate of: http://stackoverflow.com/q/4706499
answer count: 0
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/51271726
linked to: http://stackoverflow.com/q/24317469
tagged with: bloomberg
has comment: http://stackoverflow.com/comment/89522251
answer count: 2
has answer: http://stackoverflow.com/a/51274226
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/89522455
upvote count: 2
type: UnansweredQuestion
tagged with: python
score: 2
tagged with: blpapi
has comment: http://stackoverflow.com/comment/89523108
has title: Import error for blpapi module
has answer: http://stackoverflow.com/a/62215340
has comment: http://stackoverflow.com/comment/89521909
type: Question
has body: This is my first post. I run the following: Win 10 Anaconda with Python 3.6.5 Bloomberg Anywhere I am trying to use the blpapi (bloomberg professional API) for Python. Downloaded the Desktop API package (with C++ libraries), downloaded blpapi-3.9.1-cp36-cp36m-win_amd64.whl installer file and ran it succesfully. Finally I added the C:\..\C++API\v3.11.6.1\bin to my path in both user and environment variables (from earlier query here on stackoverflow): Python 2.7 with Bloomberg API import blpapi failure My error message when running import blpapi: &gt;--------------------------------------------------------------------------- &gt;ImportError Traceback (most recent call last) &gt;~\Anaconda3\lib\site-packages\blpapi\internals.py in swig_import_helper() &gt; 38 try: &gt;---&gt; 39 return importlib.import_module(mname) &gt; 40 except ImportError: &gt; &gt;~\Anaconda3\lib\importlib\__init__.py in import_module(name, package) &gt; 125 level += 1 &gt;--&gt; 126 return _bootstrap._gcd_import(name[level:], package, level) &gt; 127 &gt;&gt; &gt; &gt;~\Anaconda3\lib\importlib\_bootstrap.py in _gcd_import(name, package, level) &gt; &gt;~\Anaconda3\lib\importlib\_bootstrap.py in _find_and_load(name, import_) &gt; &gt;~\Anaconda3\lib\importlib\_bootstrap.py in _find_and_load_unlocked(name, &gt;import_) &gt; &gt;~\Anaconda3\lib\importlib\_bootstrap.py in _load_unlocked(spec) &gt; &gt;~\Anaconda3\lib\importlib\_bootstrap.py in module_from_spec(spec) &gt; &gt;~\Anaconda3\lib\importlib\_bootstrap_external.py in create_module(self, spec) &gt; &gt;~\Anaconda3\lib\importlib\_bootstrap.py in _call_with_frames_removed(f, *args, &gt;**kwds) &gt; &gt;ImportError: DLL load failed: The specified module could not be found. &gt; &gt;During handling of the above exception, another exception occurred: &gt; &gt;ModuleNotFoundError Traceback (most recent call last) &gt;~\Anaconda3\lib\site-packages\blpapi\__init__.py in &lt;module&gt;() &gt; 3 try: &gt;----&gt; 4 from .internals import CorrelationId …
tagged with: python-3.6
has comment: http://stackoverflow.com/comment/89523725
has comment: http://stackoverflow.com/comment/89522615

http://stackoverflow.com/comment/89563046
type: QuestionComment
has text: Is ^/path/to/virtual/env` a wrapper script with a weird name, or a directory? The latter won't work. Make your other script into a module and install it in the virtual env; that's what they are for.
comment on: http://stackoverflow.com/q/51292527
score: 0
type: Comment

http://stackoverflow.com/a/51225653
answers question: http://stackoverflow.com/q/51225496
has body: Find your problem my comparing to this implementation. def permute(string): ''' Recursively finds all possible combinations of the elements -- or permuations -- of an input string and returns them as a list. &gt;&gt;&gt;permute('abc') ['abc', 'acb', 'bac', 'bca', 'cab', 'cba'] ''' output = [] if len(string) == 1: output = [string] else: for i, let in enumerate(string): for perm in permute(string[:i] + string[i + 1:]): #print('Let is', let) #print('Perm is', perm) output += [let + perm] return output permute('abc') Out[ ]: ['abc', 'acb', 'bac', 'bca', 'cab', 'cba']
has comment: http://stackoverflow.com/comment/89432192
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89432085
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/89432064
accepted answer of: http://stackoverflow.com/q/51225496

http://stackoverflow.com/a/64473383
downvote count: 0
type: Answer
has body: This question was 2 years ago, but I would like to contribute something. A2Q-1. MSSQL Server, MySQL, Postgre and other latest database applications are now more reliable and more secure. You should try them and then choose which is comfortable for you. A2Q-2. It is still justifiable to use VFP. I know a large company who is still using it and are not having a hard time maintaining it. They've been using it for almost 30 years now. They are now the experts, they no longer need any support from the original creators of VFP.
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/51244350

http://stackoverflow.com/comment/89540456
score: 1
type: AnswerComment
has text: Please don't advice to open and close the output file for each line! Just open it once before the loop in a `with` context manager and let the context manager close it
comment on: http://stackoverflow.com/a/51281187
type: Comment

http://stackoverflow.com/comment/89618950
type: Comment
comment on: http://stackoverflow.com/a/51318112
has text: Thank you @RohithS98 for the answer.
score: 0
type: AnswerComment

http://stackoverflow.com/a/51181775
has body: You need to use: next(inf_data_gen) Rather than: inf_data_gen.next() Python 3 did away with .next(), renaming it as .__next__(), but its best that you use next(generator) instead.
accepted answer of: http://stackoverflow.com/q/51181765
answers question: http://stackoverflow.com/q/51181765
score: 1
upvote count: 2
type: AcceptedAnswer
downvote count: 1
type: Answer

http://stackoverflow.com/q/51189343
type: Question
has answer: http://stackoverflow.com/a/51189939
tagged with: psycopg
score: 0
linked to: http://stackoverflow.com/q/46280558
linked to: http://stackoverflow.com/q/8657508
answer count: 1
tagged with: flask
duplicate of: http://stackoverflow.com/q/46280558
favorite count: 0
has title: Bad Request - The browser (or proxy) sent a request that this server could not understand
accepted answer: http://stackoverflow.com/a/51189939
has body: I'm trying to create a flask app where I have a text box on the webpage. When submit is pressed it searches what was entered into the text box in a postgres datbase table. I'm getting the following error: Bad Request The browser (or proxy) sent a request that this server could not understand." My code is as follows: app.py from flask import Flask, render_template, request from sqlalchemy import create_engine app = Flask(__name__) app.config['DEBUG'] db_string = "postgres://xx:xx@xx:5432/xx" db = create_engine(db_string) @app.route('/', methods=['GET', 'POST']) def homepage(): jn = request.form['jobnumber'] result_set = db.execute("SELECT cost FROM public.options where optionno = (f'%{jn}%')").fetchall() return render_template('main.html', test=result_set, jn=jn) if __name__ == "__main__": app.run(debug=True) and my html file: main.html xxx xxx {{test}} I'm sure it's something real easy and simple that will fix it, but i'm struggling so any help would be hugely appreciated.
tagged with: python
type: AnsweredQuestion
upvote count: 1
downvote count: 1

http://stackoverflow.com/q/51219092
answer count: 2
tagged with: shell
has title: Python Shell - Deleting Files Without .txt Reference
favorite count: 0
tagged with: parsing
accepted answer: http://stackoverflow.com/a/51219139
has body: I'm trying to write a script to check a directory of images and search a text file to see if the name shows up inside it. If the image is not referenced in the text file, I would like the script to delete the image. Here's what I have so far: import os in_gt = False my_dir = 'C:/{...}/test' fname = 'C:/{...}file.txt' for image_name in os.listdir(my_dir): with open(fname, 'r') as gt_file: for line in gt_file: gt_image_name = line if image_name in gt_image_name: in_gt = True if in_gt == False: os.remove(os.path.join(my_dir, fname)) Additional information: In file.txt each line contains an image name and then some unimportant information about the image. Issues: Since my directory contains thousands of photos and file.txt contains thousands of lines, I am concerned about the efficiency of my code. I'm new to Python so I'm not confident about the speed of my script. Every time I run my current script, it deletes file.txt before actually accomplishing anything. Why is it doing this, and how do I stop it? Thanks!
tagged with: python
has answer: http://stackoverflow.com/a/51219188
type: AnsweredQuestion
upvote count: 1
possible better answer: http://stackoverflow.com/a/51219188
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/51219139
score: 0

http://stackoverflow.com/comment/89553043
score: 0
type: Comment
type: QuestionComment
has text: Can you help us with some more info?
comment on: http://stackoverflow.com/q/51287361

http://stackoverflow.com/q/51265578
type: Question
downvote count: 0
tagged with: keras
has comment: http://stackoverflow.com/comment/89510466
has comment: http://stackoverflow.com/comment/89511020
has comment: http://stackoverflow.com/comment/89512215
answer count: 1
tagged with: python
score: 1
favorite count: 0
upvote count: 1
has body: I need to initialize custom Conv2D kernels with weights W = a1b1 + a2b2 + ... + anbn where W = custom weight of Conv2D layer to initialise with a = random weight Tensors as keras.backend.variable(np.random.uniform()), shape=(64, 1, 10) b = fixed basis filters defined as keras.backend.constant(...), shape=(10, 11, 11) W = K.sum(a[:, :, :, None, None] * b[None, None, :, :, :], axis=2) #shape=(64, 1, 11, 11) I want my model to update the 'W' values with only changing the 'a's while keeping the 'b's constant. I pass the custom 'W's as Conv2D(64, kernel_size=(11, 11), activation='relu', kernel_initializer=kernel_init_L1)(img) where kernel_init_L1 returns keras.backend.variable(K.reshape(w_L1, (11, 11, 1, 64))) Problem: I am not sure if this is the correct way to do this. Is it possible to specify in Keras which ones are trainable and which are not. I know that layers can be set trainable = True but i am not sure about weights. I think the implementation is incorrect because I get similar results from my model with or without the custom initializations. It would be immensely helpful if someone can point out any mistakes in my approach or provide a way to verify it.
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51266680
tagged with: conv-neural-network
has comment: http://stackoverflow.com/comment/89510202
linked to: http://stackoverflow.com/q/51304703
has title: Keras Conv2D custom kernel initialization
accepted answer: http://stackoverflow.com/a/51266680

http://stackoverflow.com/comment/89375621
comment on: http://stackoverflow.com/a/51196565
type: AnswerComment
has text: Hmmm ... I think my "increment" is integer?
score: 0
type: Comment

http://stackoverflow.com/q/51196117
tagged with: django
tagged with: python
score: 0
has comment: http://stackoverflow.com/comment/89374231
has comment: http://stackoverflow.com/comment/89373822
type: Question
tagged with: apache
has comment: http://stackoverflow.com/comment/89374361
has body: Hello guys I hope you can help me I’m trying to deploy django 1.11 on a Window machine but it seems to be impossible, I already have apache and wsgi_mod installed correctly in the machine, actually when I setup a project it works fine, the 127.0.0.1 (localhost) show me the django welcome message correctly, I also can install correctly the application, the problem is when I add the application in settings.py it show me (500 Internal Server Error) my project works fine in a virtualenv, even this project was made in the same machine, I hope you can help me because this issue makes me crazy. httpd.conf DocumentRoot "C:\cotizaciones\proyecto" &lt;Directory "C:\cotizaciones\proyecto"&gt; # # Possible values for the Options directive are "None", "All", # or any combination of: # Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews # # Note that "MultiViews" must be named *explicitly* --- "Options All" # doesn't give it to you. # # The Options directive is both complicated and important. Please see # http://httpd.apache.org/docs/2.4/mod/core.html#options # for more information. # Options Indexes FollowSymLinks # # AllowOverride controls what directives may be placed in .htaccess files. # It can be "All", "None", or any combination of the keywords: # Options FileInfo AuthConfig Limit # AllowOverride None # # Controls who can get stuff from this server. # Require all granted &lt;/Directory&gt; &lt;IfModule wsgi_module&gt; WSGIScriptAlias / "C:\cotizaciones\proyecto\proyecto\wsgi.py" WSGIPythonPath "C:\cotizaciones\proyecto" &lt;Directory "C:\cotizaciones\proyecto\proyecto"&gt; &lt;Files wsgi.py&gt; Allow from all &lt;/Files&gt; &lt;/Directory&gt; &lt;/IfModule&gt; settings.py DEBUG = False ALLOWED_HOSTS = ["*"] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'aplicacion', ] I will really apreciate a ha…
has comment: http://stackoverflow.com/comment/89374441
tagged with: windows
linked to: http://stackoverflow.com/q/27093746
has title: Trying to deploy Django in Windows, it seems to be impossible
tagged with: deployment
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89374246

http://stackoverflow.com/q/51193213
has body: I am new in python. I want to read one file and copy data to another file. my code is following. In code below, when I open the files inside the for loop then I can write all the data into dst_file. but it takes 8 seconds to write dst_file. for cnt, hex_num in enumerate(hex_data): with open(src_file, "r") as src_f, open(dst_file, "a") as dst_f: copy_flag = False for src_line in src_f: if r"SPI_frame_0" in src_line: src_line = src_line.replace('SPI_frame_0', 'SPI_frame_' + str(cnt)) copy_flag = True if r"halt" in src_line: copy_flag = False if copy_flag: copy_mid_data += src_line updated_data = WriteHexData(copy_mid_data, hex_num, cnt, msb_lsb_flag) copy_mid_data = "" dst_f.write(updated_data) To improve performance, I am trying to open the files outside of the for loop. but it is not working properly. it is writing only once (one iteration of for loop) in the dst_file. As shown below. with open(src_file, "r") as src_f, open(dst_file, "a") as dst_f: for cnt, hex_num in enumerate(hex_data): copy_flag = False for src_line in src_f: if r"SPI_frame_0" in src_line: src_line = src_line.replace('SPI_frame_0', 'SPI_frame_' + str(cnt)) copy_flag = True if r"halt" in src_line: copy_flag = False if copy_flag: copy_mid_data += src_line updated_data = WriteHexData(copy_mid_data, hex_num, cnt, msb_lsb_flag) copy_mid_data = "" dst_f.write(updated_data) can someone please help me to find my mistake?
type: Question
tagged with: for-loop
has title: object.write() is not working as expected
tagged with: optimization
score: 0
has answer: http://stackoverflow.com/a/51193291
accepted answer: http://stackoverflow.com/a/51193291
answer count: 1
tagged with: python-3.x
tagged with: io
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/a/51262840
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/89504948
has comment: http://stackoverflow.com/comment/89521143
has body: First of all, trying to use eventlet for this is the wrong tool. eventlet is primarily for non-blocking I/O using coroutines in the form of greenlets. It's got little to do with CPU-bound problems (in fact the docs for eventlet.Timeout read): If the code block in the try/finally or with-block never cooperatively yields, the timeout cannot be raised. In Eventlet, this should rarely be a problem, but be aware that you cannot time out CPU-only operations with this class. What this means is that if you have some block of code that's performing a CPU-bound operation, you still won't break out of it because the code never yields to another thread. This is more for cases where you might have some code that, say, checks if a socket has data to read on it, and if not yields. If you want to set an interrupt after some time period to interrupt a long-running calculation, you can use signal.alarm and set a SIGALRM handler. You can wrap this all up in a context manager like: &gt;&gt;&gt; import signal &gt;&gt;&gt; from contextlib import contextmanager &gt;&gt;&gt; class TimeoutError(RuntimeError): pass ... &gt;&gt;&gt; @contextmanager ... def timeout(seconds): ... def handler(*args): ... raise TimeoutError("timed out after {} seconds".format(seconds)) ... orig_handler = signal.signal(signal.SIGALRM, handler) ... signal.alarm(seconds) ... try: ... yield ... finally: ... signal.alarm(0) ... signal.signal(signal.SIGALRM, orig_handler) ... &gt;&gt;&gt; with timeout(10): ... while True: pass ... Traceback (most recent call last): File "&lt;stdin&gt;", line 2, in &lt;module&gt; File "&lt;stdin&gt;", line 4, in handler __main__.TimeoutError: timed out after 10 seconds &gt;&gt;&gt; with timeout(10): ... print(1 + 1) ... 2 &gt;&gt;&gt; with timeout(10): ... 4 ** 5 ** 20 Traceback (most recent call last): File "&lt;stdin&gt;", line 2, in &lt;module&gt; File "&lt;stdin&gt;", line 4, in handler __main__.TimeoutError: timed out after 10 seconds Note: This will only work on *NIX systems, thou…
downvote count: 0
has comment: http://stackoverflow.com/comment/89543922
has comment: http://stackoverflow.com/comment/89532123
type: Answer
answers question: http://stackoverflow.com/q/51262008
has comment: http://stackoverflow.com/comment/89544188

event-handling
tag name: event-handling
tags question: http://stackoverflow.com/q/51209797
type: Tag

http://stackoverflow.com/a/51239090
has body: You could first create column that contains the year-month combination, and then use that column to group by. So a working example would be: import pyspark.sql.functions as F df = sc.parallelize([ ('2018-06-02T00:00:00.000Z','tim', 'page 1' ), ('2018-07-20T00:00:00.000Z','tim', 'page 1' ), ('2018-07-20T00:00:00.000Z','john', 'page 2' ), ('2018-07-20T00:00:00.000Z','john', 'page 2' ), ('2018-08-20T00:00:00.000Z','john', 'page 2' ) ]).toDF(("datetime","user","page" )) df = df.withColumn('yearmonth',F.concat(F.year('datetime'),F.lit('-'),F.month('datetime'))) df_agg = df.groupBy('yearmonth','page').count() df_agg.show() Output: +---------+------+-----+ |yearmonth| page|count| +---------+------+-----+ | 2018-7|page 2| 2| | 2018-6|page 1| 1| | 2018-7|page 1| 1| | 2018-8|page 2| 1| +---------+------+-----+ Hope this helps!
type: Answer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/51236909
answers question: http://stackoverflow.com/q/51236909
score: 1
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/90207944
type: AnswerComment
comment on: http://stackoverflow.com/a/51297918
type: Comment
score: 1
has text: @EricAuld Yes, now the code in answer should work even for classes. I changed the example in the answer as well.

featuretools
tag name: featuretools
type: Tag
tags question: http://stackoverflow.com/q/51191665

http://stackoverflow.com/a/51203861
has body: You should save the plot before closing it: indeed, plt.show() dislays the plot, and blocks the execution until after you close it; hence when you attempt to save on the next instruction, the plot has been destroyed and can no longer be saved. import matplotlib.pyplot as plt plt.plot([1,3,4]) plt.savefig('E:/1.png') # &lt;-- save first plt.show() # &lt;-- then display
has comment: http://stackoverflow.com/comment/118929286
downvote count: 0
score: 13
upvote count: 13
accepted answer of: http://stackoverflow.com/q/51203839
answers question: http://stackoverflow.com/q/51203839
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/118925807
type: Answer

http://stackoverflow.com/comment/124215396
score: 1
has text: crypto is not a supported library on modern machines
type: AnswerComment
comment on: http://stackoverflow.com/a/60215412
type: Comment

http://stackoverflow.com/comment/89501041
score: 0
comment on: http://stackoverflow.com/q/51261340
type: Comment
type: QuestionComment
has text: Are you sure your python packages are in env path?

http://stackoverflow.com/comment/89497271
has text: Cheers! Worked like a charm.
comment on: http://stackoverflow.com/a/51259253
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/89420095
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51219515
has text: thats just an example, I want when you do list(a) for it to run the aslist function

http://stackoverflow.com/comment/89625665
comment on: http://stackoverflow.com/a/51317814
score: 0
type: AnswerComment
type: Comment
has text: I reduced ``max_queue_size`` to 5 even 1, and batch_size(IMAGE_PER_GPU) = 4, it still the same error.

http://stackoverflow.com/comment/89329588
comment on: http://stackoverflow.com/q/51173328
score: 0
type: Comment
has text: https://stackoverflow.com/questions/50799111/unable-to-capture-full-output-from-groovy-execute/50799554#50799554
type: QuestionComment

http://stackoverflow.com/comment/108336621
type: AnswerComment
type: Comment
has text: `.cat.codes` converts your category from a string representation into an integer representation. For example, `media lawyer` would be replaced with 0, `student` would be replaced with 1, `professor` would be replaced with 2. In the other column, `print` would be replaced with 0 and `online` would be replaced with 1
score: 4
comment on: http://stackoverflow.com/a/51241909

http://stackoverflow.com/a/51208861
downvote count: 0
answers question: http://stackoverflow.com/q/51207243
has body: I think you were pretty close. Let us see what went wrong. As per your code first code trial: WebDriverWait(browser, timeout).until(EC.element_to_be_clickable((By.ID, "selectLink"))) In this attempt you have considered the ID attribute of the element where as the element is a &lt;a&gt; tag. As a general practice when you need to interact with a &lt;a&gt; tag is it always a better idea to take help of the linkText present within the &lt;a&gt; tag. As per your code second code trial: WebDriverWait(browser, timeout).until(EC.element_to_be_clickable((By.ID, "aaaa.Isu_Recherche_de_prmAvanceView.Button_Selectionner"))).click() In this attempt the ID attribute which you have considered doesn't matches the ID of the element as per the HTML. Hence you see errors. Solution As per the HTML you have shared to click on the desired element you need to induce WebDriverWait for the element to be clickable and can use either of the solutions: LINK_TEXT: WebDriverWait(browser, timeout).until(EC.element_to_be_clickable((By.LINK_TEXT, "Sélectionner"))).click() PARTIAL_LINK_TEXT: WebDriverWait(browser, timeout).until(EC.element_to_be_clickable((By.PARTIAL_LINK_TEXT, "Sélectionner"))).click() CSS_SELECTOR: WebDriverWait(browser, timeout).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "span.urBtnCntTxt"))).click() XPATH: WebDriverWait(browser, timeout).until(EC.element_to_be_clickable((By.XPATH, "//span[@class='urBtnCntTxt'][contains(.,'Sélectionner')]"))).click() Note : You have to add the following imports : from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC While using CSS_SELECTOR or XPATH it is always better to construct them with the help of minimum two attributes amongst class, id, or others
has comment: http://stackoverflow.com/comment/89402680
type: Answer
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/89402183
has comment: http://stackoverflow.com/comment/89402690
has comment: http://stackoverflow.com/comment/89403115

twilio
tag name: twilio
tags question: http://stackoverflow.com/q/51169705
tags question: http://stackoverflow.com/q/51276872
tags question: http://stackoverflow.com/q/51292817
tags question: http://stackoverflow.com/q/51300159
tags question: http://stackoverflow.com/q/51171539
type: Tag
tags question: http://stackoverflow.com/q/51211937

http://stackoverflow.com/a/51318867
has comment: http://stackoverflow.com/comment/136868710
score: 1
has comment: http://stackoverflow.com/comment/136869851
upvote count: 1
has comment: http://stackoverflow.com/comment/136868158
has comment: http://stackoverflow.com/comment/136868659
accepted answer of: http://stackoverflow.com/q/51318092
has comment: http://stackoverflow.com/comment/136868806
has comment: http://stackoverflow.com/comment/89674718
answers question: http://stackoverflow.com/q/51318092
has comment: http://stackoverflow.com/comment/136868277
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/89675061
type: Answer
has body: In [164]: x = np.array([1,2,3,4]) In [165]: x.__array_interface__ Out[165]: {'data': (40465184, False), 'strides': None, 'descr': [('', '&lt;i8')], 'typestr': '&lt;i8', 'shape': (4,), 'version': 3} The array created with ndarray has the same data buffer: In [166]: y = np.ndarray(shape = (2,1),buffer = x) In [167]: y Out[167]: array([[5.e-324], [1.e-323]]) In [168]: y.__array_interface__ Out[168]: {'data': (40465184, False), # same as for x 'strides': None, 'descr': [('', '&lt;f8')], 'typestr': '&lt;f8', 'shape': (2, 1), 'version': 3} and for an array using the int dtype: In [169]: z = np.ndarray(shape = (2,1),buffer = x, dtype=int) In [170]: z.__array_interface__ Out[170]: {'data': (40465184, False), 'strides': None, 'descr': [('', '&lt;i8')], 'typestr': '&lt;i8', 'shape': (2, 1), 'version': 3} In fact we don't need to pass x as the buffer argument, just its x.data attribute: In [171]: np.ndarray(shape = (2,1), buffer = x.data, dtype=int) Out[171]: array([[1], [2]]) Because of the shared data buffer, modifications to z appear in x as well In [172]: z[:] *= 2 In [173]: z Out[173]: array([[2], [4]]) In [174]: x Out[174]: array([2, 4, 3, 4]) and y: In [175]: y Out[175]: array([[1.e-323], [2.e-323]]) With an offset we can make an array that selects a different part of the data buffer: In [178]: w=np.ndarray(shape = (2,1), buffer = x.data, dtype=int, offset=8) In [179]: w Out[179]: array([[4], [3]]) But normally we don't use ndarray to do this. Instead we use slicing to get a view, with reshape if needed: In [181]: x[1:3].reshape(2,1) Out[181]: array([[4], [3]]) You can construct the equivalent of rand_mat with randoms.reshape(n,m) or np.random.normal(size=(n,m)). ndarray is normally only needed when the buffer comes from so other source, something that isn't already an ndarray which can be reshaped or viewed.

http://stackoverflow.com/comment/89608166
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51315836
has text: Wow, that hid in plain sight. I added code before the initializer, and didn't realize why it doesn't work. Plus, since my functions are inside a `def main()`, they are local, and I used the global initalizer. Thank you!

xmodem
tags question: http://stackoverflow.com/q/51202796
type: Tag
tag name: xmodem

http://stackoverflow.com/a/55265577
upvote count: 4
downvote count: 0
has body: Use this: print("Program for calculating sum") numbers=[1, 2, 3, 4, 5, 6, 7, 8] sum=0 for number in numbers: sum += number print("Total Sum is: %d" %sum )
type: Answer
answers question: http://stackoverflow.com/q/51252580
score: 4

http://stackoverflow.com/q/51207491
favorite count: 0
has comment: http://stackoverflow.com/comment/89396014
has comment: http://stackoverflow.com/comment/89396083
has comment: http://stackoverflow.com/comment/89395992
answer count: 3
tagged with: pandas
has answer: http://stackoverflow.com/a/51207823
tagged with: python
upvote count: 4
has body: EDIT: This question is not a clone of pandas dataframe replace nan values with average of columns because I want to replace the value of each column with the mean of the column and not with the mean of the dataframe values. QUESTION I have a pandas dataframe (train) with a hundred columns to which I have to apply Machine Learning techniques. Usually I made feature engineering by hand but in this case I have a lot of columns to deal with. I would like to build a Python function that: 1) Find the NaN values in each column (I have thought to df.isnull().any() ) 2) For each NaN value, replace it with the mean of the column in which the NaN value has been found. My idea was something like this: def replace(value): for value in train: if train['value'].isnull(): train['value'] = train['value'].fillna(train['value'].mean()) train = train.apply(replace,axis=1) But I receive the following error --------------------------------------------------------------------------- KeyError Traceback (most recent call last) /opt/conda/lib/python3.6/site-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance) 3063 try: -&gt; 3064 return self._engine.get_loc(key) 3065 except KeyError: pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc() pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc() pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item() pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item() KeyError: 'value' During handling of the above exception, another exception occurred: KeyError Traceback (most recent call last) &lt;ipython-input-25-003b3eb2463c&gt; in &lt;module&gt;() ----&gt; 1 train = train.apply(replace,axis=1) /opt/conda/lib/python3.6/site-packages/pandas/core/frame.py in apply(self, func, axis, broadcast, raw, reduce, result_type, args, **kwds) 6012 args=args, 6013 kwds=kwds) -&gt; 6014 return op.get_result() 6015 6016 def applymap(self, func): …
has title: Function to replace NaN values in a dataframe with mean of the related column
has comment: http://stackoverflow.com/comment/89395840
linked to: http://stackoverflow.com/q/18689823
accepted answer: http://stackoverflow.com/a/51207616
type: AnsweredQuestion
score: 3
linked to: http://stackoverflow.com/q/29530232
tagged with: dataframe
has answer: http://stackoverflow.com/a/51207616
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/89395963
possible better answer: http://stackoverflow.com/a/51207842
has comment: http://stackoverflow.com/comment/106563694
has answer: http://stackoverflow.com/a/51207842
downvote count: 1
linked to: http://stackoverflow.com/q/15913064

http://stackoverflow.com/q/51187751
favorite count: 0
has comment: http://stackoverflow.com/comment/89358522
has body: Here is the Python code I've got: d = {'ToGoFirst': 'aaa', 'Second': 'bbb', 'Pagargaph': '''Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.''', 'Integer': 25} with open('d.yaml', 'w') as f: yaml.safe_dump(d, f, default_flow_style=False) What I keep getting: Integer: 25 Pagargaph: "Lorem ipsum dolor sit amet, \nconsectetur adipiscing elit, \nsed do eiusmod\ \ tempor incididunt \nut labore et dolore magna aliqua." Second: bbb ToGoFirst: aaa How do I change it to produce: ToGoFirst: aaa Second: bbb Pagargaph: Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Integer: 25 In other words I want to: Avoid quotation marks and escape characters in the output so non-technical users can read and edit those config files. Ideally preserve the order of parameters. This is to be able to load a YAML file, add more parameters and still be able to save it in a human-friendly format.
tagged with: python
type: AnsweredQuestion
score: 2
has comment: http://stackoverflow.com/comment/89358179
downvote count: 0
tagged with: file
accepted answer: http://stackoverflow.com/a/51188996
type: Question
has title: How to make Python Yaml library save in a human-friendly way?
tagged with: human-readable
tagged with: configuration
has answer: http://stackoverflow.com/a/51188996
upvote count: 2
tagged with: yaml
answer count: 1

http://stackoverflow.com/q/51291380
favorite count: 0
type: Question
tagged with: python
score: -1
tagged with: classification
answer count: 2
downvote count: 1
has answer: http://stackoverflow.com/a/51291537
has body: Getting a valueerror when entering the classifier - the series in campaign_name is a string and tokenized_sents are several strings. What is happening? df['campaign_name'] = str.lower(df.campaign_name) df['tokenized_sents'] = df.campaign_name.apply(nltk.word_tokenize) X = df['tokenized_sents'] y = df['campaign_name'] xTrain, xTest, yTrain, yTest = tts(X, y, train_size=0.65, random_state=1) classifier = nltk.NaiveBayesClassifier.train(xTrain,yTrain) [ValueError: too many values to unpack (expected 2)][1]
has title: NLP Classifier - Python too many values to unpack
tagged with: nltk
has answer: http://stackoverflow.com/a/51291484
type: AnsweredQuestion
upvote count: 0
possible better answer: http://stackoverflow.com/a/51291484
accepted answer: http://stackoverflow.com/a/51291537

machine-learning
tags question: http://stackoverflow.com/q/51198120
tags question: http://stackoverflow.com/q/51187280
tags question: http://stackoverflow.com/q/51178132
tags question: http://stackoverflow.com/q/51308607
tags question: http://stackoverflow.com/q/51275590
tags question: http://stackoverflow.com/q/51221549
tags question: http://stackoverflow.com/q/51185079
tags question: http://stackoverflow.com/q/51267673
tags question: http://stackoverflow.com/q/51229016
tags question: http://stackoverflow.com/q/51179084
tags question: http://stackoverflow.com/q/51306645
tags question: http://stackoverflow.com/q/51192220
tags question: http://stackoverflow.com/q/51283580
tags question: http://stackoverflow.com/q/51210686
tags question: http://stackoverflow.com/q/51273582
tags question: http://stackoverflow.com/q/51286963
tags question: http://stackoverflow.com/q/51302275
tags question: http://stackoverflow.com/q/51221952
tags question: http://stackoverflow.com/q/51258645
tags question: http://stackoverflow.com/q/51183040
tags question: http://stackoverflow.com/q/51266728
tags question: http://stackoverflow.com/q/51317810
tags question: http://stackoverflow.com/q/51178041
tags question: http://stackoverflow.com/q/51198474
tags question: http://stackoverflow.com/q/51172889
tags question: http://stackoverflow.com/q/51300559
tags question: http://stackoverflow.com/q/51198184
tags question: http://stackoverflow.com/q/51172473
tags question: http://stackoverflow.com/q/51261257
tags question: http://stackoverflow.com/q/51269683
tags question: http://stackoverflow.com/q/51305199
tags question: http://stackoverflow.com/q/51195017
tags question: http://stackoverflow.com/q/51302903
tags question: http://stackoverflow.com/q/51255191
tags question: http://stackoverflow.com/q/51234934
tags question: http://stackoverflow.com/q/51185093
tags question: http://stackoverflow.com/q/51276877
tags question: http://stackoverflow.com/q/51181152
tags question: http://stackoverflow.com/q/51187225
tag name: machine-learning
tags question: http://stackoverflow.com/q/51315626
tags question: http://stackoverflow.com/q/51235911
tags question: http://stackoverflow.com/q/51181393
tags question: http://stackoverflow.com/q/51169773
tags question: http://stackoverflow.com/q/51201789
tags question: http://stackoverflow.com/q/51245877
tags question: http://stackoverflow.com/q/51181754
tags question: http://stackoverflow.com/q/51305682
tags question: http://stackoverflow.com/q/51168896
tags question: http://stackoverflow.com/q/51261565
tags question: http://stackoverflow.com/q/51277247
tags question: http://stackoverflow.com/q/51256927
tags question: http://stackoverflow.com/q/51220868
tags question: http://stackoverflow.com/q/51247304
tags question: http://stackoverflow.com/q/51253977
tags question: http://stackoverflow.com/q/51317311
tags question: http://stackoverflow.com/q/51269109
tags question: http://stackoverflow.com/q/51256753
tags question: http://stackoverflow.com/q/51181170
tags question: http://stackoverflow.com/q/51203869
tags question: http://stackoverflow.com/q/51308325
type: Tag
tags question: http://stackoverflow.com/q/51195939
tags question: http://stackoverflow.com/q/51281917
tags question: http://stackoverflow.com/q/51317313
tags question: http://stackoverflow.com/q/51180033
tags question: http://stackoverflow.com/q/51241717
tags question: http://stackoverflow.com/q/51206457
tags question: http://stackoverflow.com/q/51172775
tags question: http://stackoverflow.com/q/51255290
tags question: http://stackoverflow.com/q/51264478
tags question: http://stackoverflow.com/q/51297423
tags question: http://stackoverflow.com/q/51167682
tags question: http://stackoverflow.com/q/51209514
tags question: http://stackoverflow.com/q/51272531
tags question: http://stackoverflow.com/q/51234035
tags question: http://stackoverflow.com/q/51308774
tags question: http://stackoverflow.com/q/51216470
tags question: http://stackoverflow.com/q/51321826
tags question: http://stackoverflow.com/q/51226450

http://stackoverflow.com/q/51197960
has answer: http://stackoverflow.com/a/51198173
has title: Elif Command Not Working Even When It's Response Is Typed
tagged with: python
possible better answer: http://stackoverflow.com/a/51198173
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89377873
has answer: http://stackoverflow.com/a/51198104
type: Question
has body: So, I'm quite new to python and I've been trying make a game. It goes as follows. -Asks for name (Done) -Returns a username made of the first two letters of each name (Done) -Asks user to play (Issue is here) What happens is that it rolls the dice if you pick yes but is meant to give you a simple goodbye when you say no, however when you say no it still rolls the dice and then returns the result and tell you if you've won or not. Everything else seems to work fine, it's just where even if you type the response to the elif, the if still takes place. If anybody could take a look at this for me I'd be thankful. from random import randint print ("Hello, whats is your first name?") first_name = input() print ("What is your second name?") second_name = input() username = first_name[0] + first_name[1] + second_name[0] + second_name[1] print (username + ", I want to play a game. Do you accept?") game = input() if game.lower() == "yes": print ("Great, let's play. I'm going to roll a dice, if it lands on a 6, you win. If not, you lose.") dice_roll = (randint(1,6)) print (dice_roll) if dice_roll == 6: print ("Congrats, you win.") elif dice_roll != 6: print ("Sorry. You lose.") elif game.lower() == "no": print ("Fine, leave then.")
score: 0
answer count: 2
accepted answer: http://stackoverflow.com/a/51198104

http://stackoverflow.com/a/51264450
type: Answer
score: 4
answers question: http://stackoverflow.com/q/51264353
accepted answer of: http://stackoverflow.com/q/51264353
downvote count: 0
has body: You also have the test_action_01.pyc file that contains ( byte code ) , you need to check, maybe: if not os.path.basename(__file__).endswith('c'): ...
upvote count: 4
type: AcceptedAnswer

http://stackoverflow.com/comment/89367146
type: Comment
comment on: http://stackoverflow.com/a/51189502
score: 0
type: AnswerComment
has text: If you do not want to search the entire set of processors for the one with the least work, you must use and maintain a list of processor assignments sorted by their current work so you can find the one with the least work on `O(log P)`. Python isn't so great with sorted data structures, so you could go with something from [sortedcollections](https://pypi.org/project/sortedcollections/).

http://stackoverflow.com/q/51295178
tagged with: python
has comment: http://stackoverflow.com/comment/89569442
has comment: http://stackoverflow.com/comment/89567961
downvote count: 0
has title: aggregating finer resolutions to lower ones using Pandas or numpy
has body: I have a data with 15 minute resolution as below: year rainfall(per 15 min) 2006 1 2006 1.2 2006 1.3 2006 0 Where I need to aggregate the second column as 30 min, 60 min, 1 hr, 2 hr, 6 hr, 12 hr, and 24 hr. I also want the corresponding years to be translated to the new aggregated matrices. I was wondering if somebody could help me to do this using numPy or Pandas?
has comment: http://stackoverflow.com/comment/89568117
score: 2
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51296019
type: Question
upvote count: 2
tagged with: numpy
has comment: http://stackoverflow.com/comment/89568394
answer count: 1
has answer: http://stackoverflow.com/a/51296019
favorite count: 0
has comment: http://stackoverflow.com/comment/89568177
tagged with: pandas

http://stackoverflow.com/q/51309164
has comment: http://stackoverflow.com/comment/89600735
downvote count: 0
has comment: http://stackoverflow.com/comment/89594919
has title: Python multiple divs in a row dependent on screen width
has body: Hello dear stackoverflow community, as this is my first time ever asking something here please excuse me if I miss any necessary information. I started to learn Python and the Framework Django by reverse engineering the following website: thieve.co as a practice. Now I am stuck with the following issue: All my uploaded articles, that are displayed as cards (bootstrap) are automatically arranged below each other. What I actually want to do is that they are displayed in rows, where the number of cards depend on the screen size. views.py: from django.shortcuts import render,redirect from .models import Article from django.http import HttpResponse from django.contrib.auth.decorators import login_required from articles import forms def article_list(request): articles = Article.objects.all().order_by('date') return render(request,'articles/article_list.html',{'articles':articles}) def article_detail(request,slug): #return HttpResponse(slug) article = Article.objects.get(slug=slug) return render(request,'articles/article_detail.html',{'article': article}) @login_required(login_url="/accounts/login/") def article_create(request): if request.method == 'POST': form = forms.CreateArticle(request.POST, request.FILES) if form.is_valid(): instance = form.save(commit=False) instance.author = request.user instance.save() return redirect('articles:list') else: form = forms.CreateArticle() return render(request,'articles/article_create.html',{'form':form}) urls.py: from django.urls import path from articles import views app_name='articles' urlpatterns = [ path('',views.article_list,name="list"), path('create/', views.article_create,name="create"), path('&lt;slug:slug&gt;',views.article_detail, name="detail"), ] models.py: from django.db import models from django.contrib.auth.models import User # Create your models here. class Article(models.Model): title = models.CharField(max_length=100) slug = models.SlugField() body = models.TextField() date = models.DateTimeField(auto_now_add=Tru…
has answer: http://stackoverflow.com/a/51327189
tagged with: http://stackoverflow.com/tag/html
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: django
tagged with: python
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/89602105
type: Question

http://stackoverflow.com/q/51301149
has answer: http://stackoverflow.com/a/51301252
type: Question
answer count: 2
tagged with: python
upvote count: 3
accepted answer: http://stackoverflow.com/a/51301252
tagged with: numpy
has title: Numpy Where with more than 2 conditions
tagged with: dataframe
tagged with: series
tagged with: pandas
type: AnsweredQuestion
has body: Good Morning, I have the following a dataframe with two columns of integers and a Series (diff) computed as: diff = (df["col_1"] - df["col_2"]) / (df["col_2"]) I would like to create a column of the dataframe whose values are: equal to 0, if (diff >= 0) &amp; (diff &lt;= 0.35) equal to 1, if (diff > 0.35) equal to 2, if (diff &lt; 0) &amp; (diff >= - 0.35) equal to 3, if (diff &lt; - 0.35) I tried with: df["Class"] = np.where( (diff &gt;= 0) &amp; (diff &lt;= 0.35), 0, np.where( (diff &gt; 0.35), 1, np.where( (diff &lt; 0) &amp; (diff &gt;= - 0.35) ), 2, np.where( ((diff &lt; - 0.35), 3) ))) But it reports the following error: SystemError: &lt;built-in function where&gt; returned a result with an error set How can I fix it?
possible better answer: http://stackoverflow.com/a/51301323
score: 3
downvote count: 0
has answer: http://stackoverflow.com/a/51301323
favorite count: 0

http://stackoverflow.com/q/51216954
type: Question
score: 1
has title: Assigning New Column's Value From a List of Values Warning For Large DataSets - Pandas
has comment: http://stackoverflow.com/comment/89415219
has body: I have a list of Data Frames like this: sm = pd.DataFrame([["Forever", 'BenHarper'],["Steel My Kisses", 'Kack Johnson'],\ ["Diamond On the Inside",'Xavier Rudd'],[ "Count On Me", "Bruno Mars"]],\ columns=["Song", "Artist"]) pm = pd.DataFrame([["I am yours", 'Jack Johnson'],["Chasing Cars", 'Snow Patrol'],\ ["Kingdom Comes",'Cold Play'],[ "Time of your life", "GreenDay"]],\ columns=["Song", "Artist"]) df_list = [sm,pm] Now, I have another list of values that I like to assign as a new column to Data Frames in my list of Data Frames. years = ["1999", "2003"] I used the following code, (it works okay for smaller data sets) df_with_year = [] for df in df_list: for j in years: df["Year"] = j df_with_year.append(df) However, when I use this same logic for bigger dataset, I am getting an 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 Any ideas why I am getting this Copying error. I went through the provided link, it talks about a column that already exists, in which case I can use .loc. In my case, I am creating a new column and assigning values.
tagged with: replace
has answer: http://stackoverflow.com/a/51217066
has comment: http://stackoverflow.com/comment/89415194
answer count: 1
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/51217066
tagged with: pandas
tagged with: python
has comment: http://stackoverflow.com/comment/89415312
type: AnsweredQuestion
tagged with: python-3.x
upvote count: 1

http://stackoverflow.com/comment/89618428
comment on: http://stackoverflow.com/q/51320554
has text: provide data sample and don't post images
type: Comment
type: QuestionComment
score: 3

http://stackoverflow.com/q/51293520
has comment: http://stackoverflow.com/comment/89594159
type: Question
linked to: http://stackoverflow.com/q/41610667
upvote count: 2
has comment: http://stackoverflow.com/comment/89596367
has comment: http://stackoverflow.com/comment/89589440
tagged with: pandas-groupby
tagged with: pandas
has comment: http://stackoverflow.com/comment/89594289
downvote count: 0
has comment: http://stackoverflow.com/comment/89595184
favorite count: 0
type: UnansweredQuestion
has body: I'm encountering an unhelpful ValueError when attempting to do a simple diff on a moderately sized dataframe. I've tracked it down to occuring at a particular line but there's nothing unusual about that line. (It does correspond to a value where there's only one instance for the group_by key, but it's not the only such instance in the data). tp1 = to_predict'user_id', 'time_period', 'view_count'.head(74105).copy() tp2 = to_predict'user_id', 'time_period', 'view_count'.head(74106).copy() tp1['date_diff'] = tp1.groupby('user_id')['view_count'].diff(1) tp2['date_diff'] = tp2.groupby('user_id')['view_count'].diff(1) For this snippet, on the last quoted line I get: ValueErrorTraceback (most recent call last) &lt;ipython-input-109-5d39d01dba69&gt; in &lt;module&gt;() 3 4 tp1['date_diff'] = tp1.groupby('user_id')['dates_viewed'].diff(1) ----&gt; 5 tp2['date_diff'] = tp2.groupby('user_id')['dates_viewed'].diff(1) C:\Users\aleistra-admin\AppData\Local\Continuum\anaconda2\lib\site-packages\pandas\core\groupby\groupby.pyc in diff(self, periods) C:\Users\aleistra-admin\AppData\Local\Continuum\anaconda2\lib\site-packages\pandas\core\groupby\groupby.pyc in wrapper(*args, **kwargs) 849 *args, **kwargs) 850 except (AttributeError): --&gt; 851 raise ValueError 852 853 return wrapper ValueError: (That's the total error message; nothing further about the ValueError). If I extract just the few rows around the problematic row and repeat the groupby, it runs without error: tp3 = to_predict'user_id', 'time_period', 'view_count'[74100:74110].copy() tp3['date_diff'] =tp3.groupby('user_id')['view_count'].diff(1) Since the problem occurs only in the context of a largish dataframe, I can't provide a meaningful small dataset that reproduces it; as noted, an extract of a few rows does not exhibit the issue. What's the actual error here, and how do I address it? Edit: Both 'view_count' and 'time_period' are integers, ranging from 0-30 or so. As requested in comments: ('248560ea75', us…
has title: Cryptic ValueError in groupby.diff
has comment: http://stackoverflow.com/comment/89596450
tagged with: python
has comment: http://stackoverflow.com/comment/89595631
score: 2
has comment: http://stackoverflow.com/comment/89566377
has comment: http://stackoverflow.com/comment/89594155
has comment: http://stackoverflow.com/comment/89593962
answer count: 0

http://stackoverflow.com/q/51220805
tagged with: python
score: 0
has comment: http://stackoverflow.com/comment/89476654
upvote count: 1
answer count: 1
downvote count: 1
has title: How to extract data from a non animated gif file using python
has answer: http://stackoverflow.com/a/51221168
type: UnansweredQuestion
tagged with: graph
favorite count: 0
tagged with: statistics
has body: Newbie to python and doing some tutorials on how to use Python. I have now been tasked to use a non animated GIF graph to create a predication. Im not looking for the code to do this but direction on what to use. So far matplotlib and PIl are the libraries which I think are required . Reason being is to create a graph I use matplotlib's pyplot. How do I now take the end result image and retrieve x and y axis data from it? I will be using a list of .gif images as source data to create a prediction. Regards, Romano
type: Question
has comment: http://stackoverflow.com/comment/89422877

http://stackoverflow.com/a/51178919
has comment: http://stackoverflow.com/comment/89340475
has comment: http://stackoverflow.com/comment/89340489
answers question: http://stackoverflow.com/q/51178847
has comment: http://stackoverflow.com/comment/89340605
accepted answer of: http://stackoverflow.com/q/51178847
score: 4
upvote count: 4
has body: A class is an instance of its metaclass. Ergo: The type of Child is AMeta The type of a Child() is Child
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/89340443
type: Answer

http://stackoverflow.com/q/51211463
has title: Creating new list from 2 existing lists, where their values match
has comment: http://stackoverflow.com/comment/89404826
has comment: http://stackoverflow.com/comment/89404752
favorite count: 0
type: UnansweredQuestion
tagged with: python
downvote count: 1
tagged with: list
has body: I would like to do that in the screenshot. Could you please help me on that? Code: import numpy as np op = np.array([[46, 29], [39, 47], [25, 47], [31, 24]]) rt = np.array([[1, 1, 1, 0], # op[0][1]+op[1][1]+op[2][1]+op[3][0]= 29 + 47 + 47 + 31 = 154 [1, 0, 1, 1], [1, 0, 1, 0], [0, 1, 0, 1], [1, 1, 0, 0], [0, 1, 1, 1], [0, 1, 0, 1], [1, 1, 1, 0], [0, 1, 1, 0], [1, 0, 1, 0]])
score: -1
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/51211514
has answer: http://stackoverflow.com/a/51211616
has comment: http://stackoverflow.com/comment/89403791
upvote count: 0

http://stackoverflow.com/comment/89400239
type: AnswerComment
score: 0
type: Comment
has text: @JoelSaarinen Final remark for the IDE, most of them have a outline window which propose you a high view of the program with every functions. It is capable of catching special comments, such as section titles: `# ---------------------------- Main program -----------------------------------`. It is really helpful on long program to navigate through it. Thus it's quite important to get good habits and to structure properly your program, with at least `Imports`, `Class`, `Functions`, and `Main`.
comment on: http://stackoverflow.com/a/51207420

http://stackoverflow.com/comment/90063018
type: QuestionComment
has text: Here is how I solved this, for whatever it's worth. `TLDR: Make a standalone python.py script with #!path/to/python and run that directly` -- but the real answer is that I never found out what was up.
score: 4
comment on: http://stackoverflow.com/q/51234994
type: Comment

mongoengine
tags question: http://stackoverflow.com/q/51220364
type: Tag
tags question: http://stackoverflow.com/q/51242939
tag name: mongoengine
tags question: http://stackoverflow.com/q/51275815

http://stackoverflow.com/q/51212779
tagged with: python
has answer: http://stackoverflow.com/a/51213124
has comment: http://stackoverflow.com/comment/89406507
type: AnsweredQuestion
has title: Python - Dataframe - split column data into new columns - explain what some of code means
type: Question
tagged with: split
tagged with: dataframe
score: 0
has body: I am learning dataframes and wanted to breakup one column into new columns. I accomplished it with the 3 lines of code below (probably could be accomplished in one line but I wasn't sure how) by try and error, but I don't really understand some parts of the code I wrote. I was hoping someone can explain what the "1" and "2" in the split and ".str[1]" and ".str[2]" at the end means. Thanks DataRow: Customer 1234M01 123 BurOak St, 823-123-4567 Customer 5678M02 567 Young St, 819-1234567 Py_Cust['TEMP']=Py_Cust.DataRow.str.split('Customer ', 1).str[1] Py_Cust['ID']=Py_Cust.TEMP.str.split(' ', 2).str[1] Py_Cust['ADDR']=Py_Cust.TEMP.str.split(' ', 2).str[2]
answer count: 1
accepted answer: http://stackoverflow.com/a/51213124

http://stackoverflow.com/a/79230113
score: 0
has body: Building on @ethanhs's answer... A version that is usable without errors looks like: from typing import TYPE_CHECKING if TYPE_CHECKING: import _csv def myfunc(csv_writer: "_csv._writer"): ... the types come from https://github.com/python/typeshed/blob/main/stdlib/_csv.pyi and are bundled with all the type-checkers but would usually not be available at runtime
type: Answer
answers question: http://stackoverflow.com/q/51264355

http://stackoverflow.com/comment/89558542
type: AnswerComment
has text: Really helpful, thanks. I gave this a shot and it works on small lists. I'll keep testing on longer lists, but it seems like a the right track. Adding that f += 1 line is so logical I don't know how I missed it.
type: Comment
comment on: http://stackoverflow.com/a/51289936
score: 0

http://stackoverflow.com/comment/89399595
comment on: http://stackoverflow.com/a/51209383
type: Comment
has text: so you don't want the columns that are not in double_list?
score: 2
type: AnswerComment

http://stackoverflow.com/q/51223702
has body: I want to merge two small list share same values in the nested list in python as below. Input: listL = [[1,2,3,4],[5,6,7,8],[1,2,9,10]] ListL[0] and List[2] share same values 1 and 2, so the output should be: listL = [[1,2,3,4,9,10],[5,6,7,8]] The output result ListL still need to keep the same name and id as the input.
downvote count: 5
type: UnansweredQuestion
score: -3
tagged with: python
tagged with: list
has comment: http://stackoverflow.com/comment/89427772
has title: How to merge two small list in the same nested list in python?
has answer: http://stackoverflow.com/a/51223928
type: Question
upvote count: 2
answer count: 2
has answer: http://stackoverflow.com/a/51223858
has comment: http://stackoverflow.com/comment/89427681
has comment: http://stackoverflow.com/comment/89427719
has comment: http://stackoverflow.com/comment/89427724
favorite count: 0

http://stackoverflow.com/comment/89600613
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51310197
score: 0
has text: Yeah, I think I need the debug symbols and a gdb that is compiled with the -with-python flag. https://sumitkgaur.wordpress.com/2014/05/13/python-debugging/ https://www.youtube.com/watch?v=rB9rPdMRxIA Unfortunately, I don't have either of these things, and my environment isn't managed by me so I can't just install them, and even if I could the existing process is running in a version of python without debug symbols. I have to literally use the low-level gdb commands and reconstruct the python somehow. Where exactly in memory should I look? How can I make a python object out of those bits?

http://stackoverflow.com/comment/89483855
type: Comment
comment on: http://stackoverflow.com/q/51243526
score: 0
has text: I have a totally different idea, how about ssim (structural similarity index)?
type: QuestionComment

http://stackoverflow.com/q/51203779
linked to: http://stackoverflow.com/q/15868512
answer count: 0
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/15868512
has comment: http://stackoverflow.com/comment/89389934
upvote count: 1
has comment: http://stackoverflow.com/comment/89389118
downvote count: 1
type: Question
has title: How to convert from array to matrix in Python
has body: I would like to seek a help to convert from a list into the matrix. I have a list of array like this: output [[[ 0.] [ 0.] [ 0.] [ 1.]] [[ 0.] [ 0.] [ 1.] [ 0.]] [[ 0.] [ 0.] [ 1.] [ 0.]]] And I need to convert it in the matrix: X [matrix([[0], [0], [0], [1]]), matrix([[0], [0], [1], [0]]), matrix([[0], [0], [1], [0]]) Hopefully, somebody may help me. Thank you.
has comment: http://stackoverflow.com/comment/89388715
tagged with: numpy
score: 0
favorite count: 0
tagged with: matrix
tagged with: python
has comment: http://stackoverflow.com/comment/89388605

http://stackoverflow.com/comment/89517466
score: 1
type: Comment
has text: Sure this is doable, `pytest` provides built in caching mechanism for that - check out [my answer](https://stackoverflow.com/questions/22768976/how-to-share-a-variable-across-modules-for-all-tests-in-py-test/50611422#50611422) to the question [how to share a variable across modules for all tests in py.test](https://stackoverflow.com/questions/22768976) for a working example. When looking at the other answers, keep in mind that they are outdated; sharing the data via `pytest.cache` is the preferred solution nowadays.
comment on: http://stackoverflow.com/a/51221814
type: AnswerComment

http://stackoverflow.com/comment/89870340
comment on: http://stackoverflow.com/q/51218711
has text: The method linked to shows how to add other data (in that case the letters, "B" in the picture).
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51206696
has title: ModelForm with user-defined fields and choices from foreign keys
type: UnansweredQuestion
tagged with: django
upvote count: 1
tagged with: python
answer count: 0
score: 1
tagged with: django-forms
type: Question
downvote count: 0
has body: In my app, I have Study as the central model. Studys have multiple Strata, and each Strata has multiple Levels. Users create Allocations for a study by choosing one level for each Strata linked to that study, like: class Study(models.Model): name = models.CharField(max_length=100) class Stratum(models.Model): study = models.ForeignKey(Study, on_delete=models.CASCADE, related_name='strata') name = models.CharField(max_length=100) class Level(models.Model): stratum = models.ForeignKey(Stratum, on_delete=models.CASCADE, related_name='levels') label = models.CharField(max_length=100) class Allocation(models.Model): study = models.ForeignKey(Study, on_delete=models.CASCADE, related_name='allocations') code = models.CharField(blank=False, max_length=100) levels = models.ManyToManyField(Level, related_name='allocations') In order to create fields for the allocation creation form, I am currently finding all the Strata and associated levels in the form's constructor, but hiding the strata as the user doesn't interact with them: class AllocationForm(forms.ModelForm): class Meta: model = Allocation fields = ('code',) def __init__(self, *args, **kwargs): study = kwargs.pop('study') super(AllocationForm, self).__init__(*args, **kwargs) strata = Stratum.objects.filter(study=study) for stratum in strata: self.fields[stratum.name] = forms.IntegerField( widget=forms.HiddenInput() ) self.fields[stratum.name].initial = stratum.id self.fields[stratum.name].disabled = True self.fields[stratum.name + '_level'] = forms.ModelChoiceField( queryset=Level.objects.filter(stratum=stratum) ) Is this a safe and sensible way to attach the associated objects to the form? I worry that I will lose track of the connection between Strata and Levels when trying to create the allocation. Is this something that would be better performed in the view?
favorite count: 0

http://stackoverflow.com/q/51225080
has comment: http://stackoverflow.com/comment/89430623
type: Question
answer count: 1
favorite count: 0
score: 0
tagged with: typeerror
has body: I am unable to understand why the my jupyter notebook is showing TypeError for float, each time I execute it. A = np.random.rand(1e4, 1e4).astype('float32') B = np.random.rand(1e4, 1e4).astype('float32') c1 = [] c2 = [] def matpow(M, n): if n &lt; 1: #Abstract cases where n &lt; 1 return M else: return tf.matmul(M, matpow(M, n-1)) Error: Traceback (most recent call last) &lt;ipython-input-5-61ea4b300d55&gt; in &lt;module&gt;() 1 # Example: compute A^n + B^n on 2 GPUs 2 #Create random Large matrix ----&gt; 3 A = np.random.rand(1e4, 1e4).astype('float32') 4 B = np.random.rand(1e4, 1e4).astype('float32') 5 mtrand.pyx in mtrand.RandomState.rand() mtrand.pyx in mtrand.RandomState.random_sample() mtrand.pyx in mtrand.cont0_array() TypeError: 'float' object cannot be interpreted as an index
type: UnansweredQuestion
has title: TypeError: 'float' object cannot be interpreted as an index in Multi GPU's
upvote count: 1
tagged with: python
downvote count: 1
has answer: http://stackoverflow.com/a/51225250
has comment: http://stackoverflow.com/comment/89440567
linked to: http://stackoverflow.com/q/32687012
has comment: http://stackoverflow.com/comment/89431306
tagged with: tensorflow

pca
tags question: http://stackoverflow.com/q/51300559
tag name: pca
type: Tag
tags question: http://stackoverflow.com/q/51303638
tags question: http://stackoverflow.com/q/51291082

http://stackoverflow.com/comment/89355407
comment on: http://stackoverflow.com/q/51186790
score: 0
type: Comment
type: QuestionComment
has text: Welcome to stackoverflow.com. Please take some time to read the [help pages](https://stackoverflow.com/help), especially the sections named ["What topics can I ask about here?"](https://stackoverflow.com/help/on-topic) and ["What types of questions should I avoid asking?"](https://stackoverflow.com/help/dont-ask). Also please [take the tour](https://stackoverflow.com/tour) and read about [how to ask](https://stackoverflow.com/help/how-to-ask) good questions. Lastly please learn how to create a [Minimal, Complete, and Verifiable Example](https://stackoverflow.com/help/mcve).

http://stackoverflow.com/a/51573063
score: 0
answers question: http://stackoverflow.com/q/51323218
type: Answer
has body: Just to close the question for any future possible check. The solution I used was to use list in lists. Thus the index of the element was the ordering and the tasks and the completion status was the 0 and 1 elements of the list-in-lists.

http://stackoverflow.com/comment/89326952
type: Comment
has text: See the image above for what happens when I try to change the python version
type: AnswerComment
comment on: http://stackoverflow.com/a/51171899
score: 0

http://stackoverflow.com/q/51187719
has body: I have discovered that I have an installed library in my django app(as a dependecy for another one i think) and I want to know which package/library has introduced. How can I do that the installed library is: pathspec my requirements.txt file is: Babel==2.4.0 coreapi==2.3.3 coreschema==0.0.4 django-admin-list-filter-dropdown==1.0.1 django-admin-sortable2==0.6.19 django-background-tasks==1.1.12 django-categories==1.5.4 django-ckeditor==5.3.1 django-cors-headers==2.1.0 django-filter==1.0.4 django-import-export==1.0.0 django-markdownx==2.0.22 django-object-actions==0.10.0 django-rest-auth[with_social]==0.9.2 django-simple-metatags==0.9.1 django-static-sitemaps==4.4.0 django-storages==1.5.2 django-taggit==0.22.2 django-taggit-helpers==0.1.4 Django==1.11.10 djangorestframework~=3.6.4
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/89357299
has comment: http://stackoverflow.com/comment/89357188
tagged with: python
favorite count: 0
has title: Check python/django library dependencies
has answer: http://stackoverflow.com/a/51208191
type: UnansweredQuestion
tagged with: pip
tagged with: django
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/89357128
score: 1
has comment: http://stackoverflow.com/comment/89373063

http://stackoverflow.com/comment/89484702
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51252820
has text: Yes, you will need JS.
score: 0

http://stackoverflow.com/q/51251626
upvote count: 0
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89482463
has comment: http://stackoverflow.com/comment/89483848
score: -4
has answer: http://stackoverflow.com/a/51251956
has comment: http://stackoverflow.com/comment/89482189
type: Question
has body: Here I am trying to understand how perform_math_task is defined and how it is being accessed later on with add function. class Human(): def __init__(self, name, gender): self.name = name self.gender = gender def speak_name(self): print "My name is %s" % self.name def speak(self, text): print text def perform_math_task(self, math_operation, *args): print "%s is champion in mathmatic operation %f" %(self.name, math_operation(*args)) def add (a, b): return a+b will = Human("XYZ", "Female") print will.name print will.gender will.speak_name will.speak("I love Python Programming.") will.perform_math_task(add, 34, 67)
has title: I am trying to understand the arguments in __init__ and function in below code
downvote count: 4

http://stackoverflow.com/q/51245800
tagged with: python
tagged with: quantization
tagged with: tensorflow
has body: What I want to do I'm trying to create a quantized version of the Inception-ResNet-v1 model used in facenet - with not only quantized weights, but quantized nodes as well, according to Tensorflow's graph_transform guide. What I have tried Using a model pretrained on the CASIA webface dataset, I tried to finetune the model with fake quantization nodes, by adding the following line tf.contrib.quantize.create_training_graph(quant_delay=0) in the facenet training script train_softmax.py, after calculating the total loss (line 178), and the below line just before saving the checkpoints (line 462): tf.contrib.quantize.create_eval_graph() I then finetuned the pretrained model for 1000 iterations, using a learning rate of 0.0005: python3 src/train_softmax.py \ --logs_base_dir ~/logs/facenet/ \ --models_base_dir ${model_path} \ --data_dir ${casia_path} \ --image_size 160 \ --model_def models.inception_resnet_v1 \ --lfw_dir ${lfw_path} \ --optimizer ADAM \ --learning_rate -1 \ --max_nrof_epochs 150 \ --keep_probability 0.8 \ --random_crop \ --random_flip \ --use_fixed_image_standardization \ --learning_rate_schedule_file data/learning_rate_schedule_classifier_casia.txt \ --weight_decay 5e-4 \ --embedding_size 128 \ --lfw_distance_metric 1 \ --lfw_use_flipped_images \ --lfw_subtract_mean \ --validation_set_split_ratio 0.05 \ --validate_every_n_epochs 5 \ --prelogits_norm_loss_factor 5e-4 \ --center_loss_factor 2e-4 \ --gpu_memory_fraction 0.7 \ --pretrained_model ${model_path}/20180614-060325/model-20180614-060325.ckpt-90 So far, so good. Next, I froze the resulting graph using facenet's freeze_graph: python3 src/freeze_graph.py ${model_path}/20180709-100209/ ${model_path}/20180709-100209/model-20180709-100209-frozen.pb Finally I tried to use transform_graph to create a fully quantized model: bazel build tensorflow/tools/graph_transforms:transform_graph bazel-bin/tensorflow/tools/graph_transforms/transform_graph \ --in_graph=${modelpath}/20180709-100209/model-20180709-100209-f…
score: 8
has title: How can I quantize facenet's Inception-ResNet-v1 model in Tensorflow?
answer count: 0
downvote count: 0
type: UnansweredQuestion
favorite count: 0
upvote count: 8
type: Question

http://stackoverflow.com/comment/89411668
comment on: http://stackoverflow.com/q/51215163
has text: yes, only the first element should be considered for sorting the lines
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51321791
has body: Im a Python beginner and I wondered if anyone could advice me on how to check a list for pre- defined number of pairs. green = yellow and blue purple = blue and red orange = red and yellow grey = white and black beige = white and yellow brown = black and yellow These are a number of example list that I would like to iterate through and check if any of the above pairs exist in it. If they do exist in the list then I would like to return the name of the pair. Lists: List1 ['white','black','yellow'] (return: brown, beige) List2 ['yellow','white','black','red'](return: beige, grey, orange) List3 ['blue','yellow','red'] (return: green, purple) List4 ['white','red','blue'] (return: purple) I have tried to filter lists by their length and then check membership of each element so far but it does not return all possible pairs. Thank you for your help! These are the things that I have tried so far: (1) loop through each list and test for every item (this however does not return all possible solutions) if "white" and "yellow" in list1: result = 'beige' elif 'yellow' and 'black' in list1: result = 'brown' else: result = 'None' (2) len_of_list = len(lists) if len_of_list == 3: three = lists for item in three: if any (colour in three for colour in ('yellow','black')): print(three) (3) if len_of_list ==3: three = lists first_el = three[0] second_el = three[1] last_el = three[-1] if "yellow" in first_el and "black" in second_el: result = 'brown' elif 'yellow' in first_el and 'black' in last_el: result = 'brown' elif 'yellow' in second_el and 'black' in last_el: result = 'brown'
has comment: http://stackoverflow.com/comment/89619680
score: 0
has answer: http://stackoverflow.com/a/51322237
answer count: 1
tagged with: python
favorite count: 0
tagged with: pattern-matching
tagged with: python-3.x
upvote count: 1
downvote count: 1
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51322237
tagged with: list
has title: Check python list for predefined matches
type: Question

http://stackoverflow.com/q/51254724
tagged with: python
has answer: http://stackoverflow.com/a/51254790
upvote count: 1
type: AnsweredQuestion
has body: Some classes, such as Series in pandas produce instances that can be called by numpy.array and turned into numpy arrays. How do I make instances of a class that I'm writing (which works with a few arrays at the core) be allowed to be passed as argument to numpy.array and converted to a numpy array? (perhaps "callable" is not the right word)
type: Question
tagged with: numpy
accepted answer: http://stackoverflow.com/a/51254790
has title: How to make python object callable by numpy.array()
tagged with: pandas
answer count: 1
downvote count: 0
score: 1
tagged with: inheritance
linked to: http://stackoverflow.com/q/7875911
favorite count: 0

http://stackoverflow.com/q/51323218
tagged with: python
tagged with: dictionary
favorite count: 0
tagged with: command-line
possible better answer: http://stackoverflow.com/a/51573063
has title: Python 3.7 - how to index console commands to use as a reference
has body: I'm learning Python and stuck with below task thus appreciate some help. (version 3.7) Task: Record console inputs into a file - assign an ID to it to be able to delete based on the ID. Be able to list it. Full code below for reference - yet I struggle with assigning an index to the user input and delete it based on that ID. I was advised that it is possible relying on sys.argv - yet I kinda feel this is rather expecting a dictionary usage (which I am not familiar with yet). I was trying to add a number prior to the user input in the file (so the text file would look like 001. *user input*,\n 002. *user input*, etc), thus all lines shall get numbered. Based on that when the user enters a certain number(=certain line) to be deleted the script should delete the given line. Yet I failed to look up and make python understand the number reference at the beginning of the line (some sort of search function would work I assume). Can I tell the script to delete based online reference? edit: given that the program shuts down after every entry len(sys.argv) will remain 1. A possible solution could be -if I don't shut it down- to refer to the index number to delete certain line based on the reference. But how do I feed again the variable/index number after restarting the program? The index will start again from 1 (as 0 reserved) and will disregard the number of lines already in the text. Thanks in advance! import sys menu = input("What o you want to do?\n add new idea(1)\n delete an idea(2)\n list all ideas(3)") if menu == "1": myfile = open("ideabank.txt", 'a+', encoding = 'utf-8') newidea = input("What is your new idea?:") print('Argument List:', str(sys.argv)) myfile.write(newidea) myfile.write("\n") myfile.close() elif menu == "2": print("delete") else: myfile = open("ideabank.txt", 'r', encoding = 'utf-8') for line in myfile: print(line, end="") myfile.close()
has answer: http://stackoverflow.com/a/51573063
tagged with: indexing
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89621550
has comment: http://stackoverflow.com/comment/89625967
accepted answer: http://stackoverflow.com/a/51323336
score: 1
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/51323336
has comment: http://stackoverflow.com/comment/89626002
downvote count: 0
has comment: http://stackoverflow.com/comment/89624551
upvote count: 1

http://stackoverflow.com/comment/89437253
type: QuestionComment
comment on: http://stackoverflow.com/q/51223025
has text: Thank you for your comment! Turns out the above line of code `driver.find_element_by_xpath('//*[@id="getJBJ"]').click();` does work too. I managed to resolve my solution by upgrading chrome driver to the latest version. My code works and achieves selecting both the month and date now.
score: 0
type: Comment

flask
tags question: http://stackoverflow.com/q/51169160
tags question: http://stackoverflow.com/q/51213590
tags question: http://stackoverflow.com/q/51199475
tags question: http://stackoverflow.com/q/51226976
tags question: http://stackoverflow.com/q/51288677
tags question: http://stackoverflow.com/q/51315879
tags question: http://stackoverflow.com/q/51252936
tags question: http://stackoverflow.com/q/51214191
tags question: http://stackoverflow.com/q/51215919
tags question: http://stackoverflow.com/q/51220670
tags question: http://stackoverflow.com/q/51275940
tags question: http://stackoverflow.com/q/51236611
tags question: http://stackoverflow.com/q/51176036
tags question: http://stackoverflow.com/q/51282011
tags question: http://stackoverflow.com/q/51234212
tags question: http://stackoverflow.com/q/51198043
tags question: http://stackoverflow.com/q/51308651
tags question: http://stackoverflow.com/q/51292905
tags question: http://stackoverflow.com/q/51318988
tags question: http://stackoverflow.com/q/51309895
tags question: http://stackoverflow.com/q/51219565
tags question: http://stackoverflow.com/q/51251668
tags question: http://stackoverflow.com/q/51311365
tags question: http://stackoverflow.com/q/51187180
tags question: http://stackoverflow.com/q/51277003
tags question: http://stackoverflow.com/q/51275815
tags question: http://stackoverflow.com/q/51174915
tags question: http://stackoverflow.com/q/51220364
tags question: http://stackoverflow.com/q/51192534
tags question: http://stackoverflow.com/q/51254518
tags question: http://stackoverflow.com/q/51253294
tags question: http://stackoverflow.com/q/51289930
tags question: http://stackoverflow.com/q/51231808
tags question: http://stackoverflow.com/q/51295557
tags question: http://stackoverflow.com/q/51255660
tags question: http://stackoverflow.com/q/51299411
tags question: http://stackoverflow.com/q/51238014
tags question: http://stackoverflow.com/q/51234995
tags question: http://stackoverflow.com/q/51207503
tags question: http://stackoverflow.com/q/51251273
tags question: http://stackoverflow.com/q/51193774
tags question: http://stackoverflow.com/q/51178143
tags question: http://stackoverflow.com/q/51276872
tags question: http://stackoverflow.com/q/51293118
tags question: http://stackoverflow.com/q/51304378
tags question: http://stackoverflow.com/q/51254226
tags question: http://stackoverflow.com/q/51276878
tags question: http://stackoverflow.com/q/51201107
tags question: http://stackoverflow.com/q/51181638
tags question: http://stackoverflow.com/q/51257153
tags question: http://stackoverflow.com/q/51307810
type: Tag
tags question: http://stackoverflow.com/q/51289421
tags question: http://stackoverflow.com/q/51174199
tags question: http://stackoverflow.com/q/51228118
tags question: http://stackoverflow.com/q/51285853
tags question: http://stackoverflow.com/q/51313324
tags question: http://stackoverflow.com/q/51263829
tags question: http://stackoverflow.com/q/51227351
tags question: http://stackoverflow.com/q/51287464
tags question: http://stackoverflow.com/q/51181324
tags question: http://stackoverflow.com/q/51263328
tags question: http://stackoverflow.com/q/51175627
tags question: http://stackoverflow.com/q/51234120
tags question: http://stackoverflow.com/q/51249243
tags question: http://stackoverflow.com/q/51315151
tags question: http://stackoverflow.com/q/51232534
tags question: http://stackoverflow.com/q/51314091
tags question: http://stackoverflow.com/q/51230473
tags question: http://stackoverflow.com/q/51220394
tags question: http://stackoverflow.com/q/51312381
tags question: http://stackoverflow.com/q/51252852
tags question: http://stackoverflow.com/q/51278974
tags question: http://stackoverflow.com/q/51180795
tags question: http://stackoverflow.com/q/51257431
tags question: http://stackoverflow.com/q/51227394
tags question: http://stackoverflow.com/q/51172720
tags question: http://stackoverflow.com/q/51211937
tags question: http://stackoverflow.com/q/51286193
tags question: http://stackoverflow.com/q/51209613

http://stackoverflow.com/comment/89565466
type: AnswerComment
score: 0
type: Comment
has text: I edited my code and I made some changes. Now I have error while running myClient.py which you can see here: [https://ibb.co/d4EynT ] - after running: print(data[:10]), it is printing Exif. And also, I was not able to observe the result of print(f.tell(), data[:10]) in client side, Since I encountered the error.
comment on: http://stackoverflow.com/a/51275377

http://stackoverflow.com/q/51209582
has comment: http://stackoverflow.com/comment/89401999
favorite count: 0
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/html
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/89402041
score: 1
upvote count: 1
has title: Django: dictionary to HTML table, when values are generators
has answer: http://stackoverflow.com/a/51210806
type: Question
has comment: http://stackoverflow.com/comment/89402612
has body: I have a dictionary containing scraped Airbnb listings data: all_data = { 'name' : self.detail('listing', 'name'), 'city' : self.detail('listing', 'city'), 'id' : self.detail('listing', 'id'), 'latitude' : self.detail('listing', 'lat'), 'longitude' : self.detail('listing', 'lng'), 'picture' : self.detail('listing', 'picture_url'), 'pictures' : self.detail('listing', 'picture_urls'), 'price' : self.detail('pricing_quote', 'rate', 'amount'), 'currency' : self.detail('pricing_quote', 'rate', 'currency') } That I am passing from Django view to template like this: context = {'all_data':all_data} return render(request, 'javascript/testjson.html', context) The values in this dictionary are generators, yielding a specific listing detail. How do I present this data in a HTML table form in the template? So far I have the following for displaying the headers, but I don't know how to extract the data from generators into columns below those headers: &lt;table&gt; &lt;tr&gt; {% for key, value in all_data.items %} &lt;th&gt;{{key}}&lt;/th&gt; {% endfor %} &lt;/tr&gt; &lt;/table&gt;
answer count: 1
downvote count: 0

http://stackoverflow.com/a/51184846
accepted answer of: http://stackoverflow.com/q/51179906
has comment: http://stackoverflow.com/comment/89351870
has comment: http://stackoverflow.com/comment/89354446
has comment: http://stackoverflow.com/comment/89376758
has comment: http://stackoverflow.com/comment/89361019
score: 0
type: AcceptedAnswer
has body: you can use csv library to do it. it's a python built-in library. I don't known what type is your compustatq. but find your way to read it by each row. use it like this: import csv writer = csv.writer(open('path.csv', 'wb+'), dialect='excel') for row in compustatq: writer.writerow([str(v) for v in row]) ref: csv I just read the source code of wrds.Connection.raw_sql. it tells your compustatq is an instance of pandas.DataFrame. So you can still use the method to_csv but in a slightly different way: f = open('path.csv', 'wb+') for i in xrange(len(compustatq)): f.write(df[i:i+1].to_csv(header=i==0)) f.close()
answers question: http://stackoverflow.com/q/51179906
has comment: http://stackoverflow.com/comment/89358940
type: Answer

http://stackoverflow.com/comment/89571479
score: 3
comment on: http://stackoverflow.com/q/51297129
has text: Just enter `!type examples/ex1.csv`
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51291728
has comment: http://stackoverflow.com/comment/89561146
type: Question
accepted answer: http://stackoverflow.com/a/51291845
has title: Rotate matrix built from 1d array
score: 0
answer count: 2
tagged with: matrix
favorite count: 0
downvote count: 2
has answer: http://stackoverflow.com/a/51291845
has body: Hello I have a sorted list ['a','b','c','d','e','f'] that is currently displayed on the front end as the matrix ['a','c','e'], ['b,'d','f'], When it should be ['a','b','c'], ['d,'e','f'], Unfortunately I'm not able to modify the front end to display the object horizontally so I would like to be able to rearrange the 1d array into another 1d array with the correct order ['a','d','b','e','c',f']. I conceptually know how it could be done by converting the 1d array into a 2d array, then rotating the matrix, then converting the 2d array back into a 1d array. However I was wondering if there is a more pythonic way/faster general algorithm for achieving this.
tagged with: python
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/51291807
upvote count: 2
has answer: http://stackoverflow.com/a/51291807

http://stackoverflow.com/comment/89492837
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51256927
has text: How did you perfrom one-hot encoding.? Manually or by using sklearn.?
score: 0

http://stackoverflow.com/comment/89568195
has text: Those look like box and whisker plots: https://matplotlib.org/gallery/pyplots/boxplot_demo_pyplot.html?highlight=boxplot
type: Comment
score: 0
comment on: http://stackoverflow.com/a/51295311
type: AnswerComment

http://stackoverflow.com/a/51178676
type: Answer
has comment: http://stackoverflow.com/comment/89425756
has comment: http://stackoverflow.com/comment/89340279
has body: If you did not want to use a writer, you could do this manually. But note that managing quotes for columns that contain the delimiter would be a little hard: Simplest method: numItems = len(l1) outputStr = '' for i in range(0,numItems): outputStr += l1[i] + "\t" + l2[i] + "\t" + l3[i] + "\n" with open('output.tsv', "w") as outputter: outputter.write(outputStr) If col data also contains a '\t', you'll have to search each list item and wrap it in quotes...can update if necessary. If there are unicode characters, you can define that in the writing operation when you open the file. Hope that helps
answers question: http://stackoverflow.com/q/51178613
score: 0

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

http://stackoverflow.com/comment/89511925
type: AnswerComment
type: Comment
score: 1
has text: @ceds: well you can for example override the object manager to encapsulate these calls, which might be the best way to hide all this annotation. But as far as I know, no; there is no elegant way to specify annotations.
comment on: http://stackoverflow.com/a/51266562

http://stackoverflow.com/comment/89402475
type: QuestionComment
comment on: http://stackoverflow.com/q/51210433
has text: It calls other java files to connect to an API to retrieve information; no I started adding logging to the top of the code during trial/error to see if I can disable, latest one I used was logging.getLogger('suds.client').setLevel(logging.CRITICAL) which resulted in same behavior, but OOB I haven't configured logging at all
score: 0
type: Comment

http://stackoverflow.com/q/51303995
score: 0
tagged with: matrix
has comment: http://stackoverflow.com/comment/89584734
tagged with: python
answer count: 0
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/46445894
has comment: http://stackoverflow.com/comment/89584891
duplicate of: http://stackoverflow.com/q/46445894
tagged with: matrix-multiplication
type: Question
tagged with: numpy
has title: numpy fill_between() different diagonal values
has comment: http://stackoverflow.com/comment/89585232
has comment: http://stackoverflow.com/comment/89584815
has body: I have created a 3x3 np.array full of zeros with a = np.zeros((3,3)). I have another 3x1 numpy array b = np.array([[1],[2],[3]]) which values I want to set for the diagonal values in a. Hence I as result I want to have a matrix with the values of b on the diagonal and zeros everywhere else. I tried using the np.fill_diagonal() function with the following code: a = np.zeros((3,3)) b = np.array([[1],[2],[3]]) print(np.fill_diagonal(a,b)) As result I get: None What I am doing wrong and how can I accomplish the above?
has comment: http://stackoverflow.com/comment/89585074

http://stackoverflow.com/a/51298324
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51298258
has body: You can do so by nesting a dict comparison and a list comparison as follows mydict = { '1': ['4', '3', '8'], '2': ['3', '7', '5'] } letterdict = { key + 'a' : [e + 'b' for e in value] for key, value in mydict.items() } letterdict &gt; dict_items([('1a', ['4b', '3b', '8b']), ('2a', ['3b', '7b', '5b'])])

http://stackoverflow.com/q/51289736
has body: For example we have 2 lists of dictionaries a = [{'fruit_id':234, 'type':'apple', 'color':'red'}] b = [{'fruit_id':235, 'type':'kiwi', 'color':'brown'},{'fruit_id':234, 'type':'apple', 'color':'green'}] I want to update list A with list B if they have the same fruit_id, so for this example list A will have the color value changed to green. What is a good algorithm for this?
tagged with: python
tagged with: dictionary
has title: Update one list of dictionaries with the values of another list of dictionaries if they have the same specific value
accepted answer: http://stackoverflow.com/a/51290350
type: AnsweredQuestion
tagged with: list
score: 1
has comment: http://stackoverflow.com/comment/89557620
has answer: http://stackoverflow.com/a/51290163
upvote count: 1
has answer: http://stackoverflow.com/a/51290350
type: Question
possible better answer: http://stackoverflow.com/a/51290163
answer count: 2
tagged with: pandas
downvote count: 0
favorite count: 0

http://stackoverflow.com/q/51270584
accepted answer: http://stackoverflow.com/a/51280857
type: Question
has body: I am having a go at using the sentinelsat python API to download satellite imagery. However, I am receiving error messages when I try to convert to a pandas dataframe. This code works and downloads my requested sentinel satellite images: from sentinelsat import SentinelAPI, read_geojson, geojson_to_wkt from datetime import date api = SentinelAPI('*****', '*****', 'https://scihub.copernicus.eu/dhus') footprint = geojson_to_wkt(read_geojson('testAPIpoly.geojson')) products = api.query(footprint, cloudcoverpercentage = (0,10)) #this works api.download_all(products) However if I instead attempt to convert to a pandas dataframe #api.download_all(products) #this does not work products_df = api.to_dataframe(products) api.download_all(products_df) I receive an extensive error message that includes "sentinelsat.sentinel.SentinelAPIError: HTTP status 500 Internal Server Error: InvalidKeyException : Invalid key (processed) to access Products " (where processed is also replaced with title, platformname, processingbaseline, etc.). I've tried a few different ways to convert to a dataframe and filter/sort results and have received an error message every time (note: I have pandas/geopandas installed). How can I convert to a dataframe and filter/sort with the sentinelsat API?
score: 2
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/51280857
favorite count: 0
tagged with: sentinelsat
tagged with: pandas
tagged with: geopandas
tagged with: python
type: AnsweredQuestion
has title: Python API sentinelsat error in download
tagged with: sentinel1
upvote count: 2

http://stackoverflow.com/comment/89547290
score: 0
has text: what do u mean base?
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51283383

http://stackoverflow.com/comment/89605979
score: 1
has text: Anyway, please (1) give us the whole exception (with the traceback), not just a description of it, (2) format your code as code, and (3) make sure what you've given us is enough to diagnose the problem. (See [mcve] in the help if needed; there's a lot of useful guidance there on what is helpful.)
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51314619

http://stackoverflow.com/a/51206227
has body: If your tuple is named as tpls, then you can sort all the lists within that tuple as follows tuple(sorted(t, reverse=True) if type(t) == list else t for t in tpls) # ('100460040', [(0.6915704982169979, '100461026'), (0.5341613659423828, '100462023'), (0.424943345091376, '100460139'), (0.2915704982169979, '100464122'), (0.2915704982169979, '100461025'), (0.27074189424335177, '100410120'), (0.1915704982169979, '100461066'), (0.10862458037004655, '100490118')])
downvote count: 0
answers question: http://stackoverflow.com/q/51206110
type: Answer
has comment: http://stackoverflow.com/comment/89393380
has comment: http://stackoverflow.com/comment/89393717
score: 1
upvote count: 1

http://stackoverflow.com/q/51281714
downvote count: 1
has answer: http://stackoverflow.com/a/51283069
type: Question
score: 1
answer count: 2
has comment: http://stackoverflow.com/comment/89540803
has answer: http://stackoverflow.com/a/51283171
favorite count: 0
has title: missing 1 required positional argument: 'request'
tagged with: python
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89540771
tagged with: django
has body: here is my view.py class categAdmin(admin.ModelAdmin): change_form_template = 'category_forms.html' list_display = ['title'] model = Category fields = ['status','title','category_post','body', 'photo', 'url','slider','Gallery','lists','pk_tree','video','maps'] # def render_change_form(self, request, context, **kwargs): # post = Post.objects.all() # context['eve'] = post # return super(categAdmin,self).render_change_form(request, context, **kwargs) def item_add(request, self, post_id): tree = post_id return self.add_view(request, extra_context={'tree': tree}) i am getting error item_add() missing 1 required positional argument: 'request'

http://stackoverflow.com/a/51301796
has body: You can use boolean indexing with iloc for select last column: df = df[df.iloc[:, -1] &gt; 4] print (df) 0 1 2 1 a2 b2 5 2 a3 b3 8 Detail: print (df.iloc[:, -1]) 0 3 1 5 2 8 Name: 2, dtype: int64
type: Answer
has comment: http://stackoverflow.com/comment/89685103
has comment: http://stackoverflow.com/comment/89580743
has comment: http://stackoverflow.com/comment/89580846
score: 1
has comment: http://stackoverflow.com/comment/89580620
upvote count: 1
answers question: http://stackoverflow.com/q/51301688
has comment: http://stackoverflow.com/comment/89580622
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51301688

http://stackoverflow.com/q/51320121
has body: I am using tesseract (through the python wrapper) in order to extract text from documents. These documents do not include any images or tables, simply text. Is there any option to distinguish the titles/headings from the text? Ideally I want to be able to have something like a xml tree rather than the full string chain (I do not need to have a visual of the document layout). I found some third party tools that seem to be able to help but I was wondering if I can do it directly from tesseract.
has answer: http://stackoverflow.com/a/68443271
downvote count: 0
has comment: http://stackoverflow.com/comment/96396900
has comment: http://stackoverflow.com/comment/96419967
answer count: 3
has answer: http://stackoverflow.com/a/59613184
tagged with: python
tagged with: ocr
upvote count: 11
favorite count: 0
has title: How to separate title and headers from body text in image
tagged with: python-tesseract
type: UnansweredQuestion
score: 11
tagged with: tesseract
tagged with: opencv
has comment: http://stackoverflow.com/comment/110181343
has answer: http://stackoverflow.com/a/62298680
has comment: http://stackoverflow.com/comment/94458598
type: Question

http://stackoverflow.com/comment/89611792
type: QuestionComment
has text: Know that a `lambda` or other one line form will have far greater `O` complexity than using this function or `itertools.accumulate`. I think this is a step in the *wrong* direction.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/51317541

http://stackoverflow.com/comment/89318554
has text: If the value is going to be a log level name you could use `getattr`, but it might be clearer to have e.g. `logger.setLevel(logging.DEBUG if dev_mode else logging.INFO)`.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51167593
type: Comment

countvectorizer
type: Tag
tags question: http://stackoverflow.com/q/51243650
tag name: countvectorizer

http://stackoverflow.com/comment/89422212
type: Comment
comment on: http://stackoverflow.com/a/51212881
score: 0
type: AnswerComment
has text: Thanks! Have roll back to Python 3.6.5 to wait for other module to catch up. Also encounter an unexpected error with peewee on python 3.7.

http://stackoverflow.com/comment/89611836
type: Comment
comment on: http://stackoverflow.com/a/51317321
score: 0
type: AnswerComment
has text: Learned from training

http://stackoverflow.com/q/51235303
linked to: http://stackoverflow.com/q/42496508
has answer: http://stackoverflow.com/a/51235447
score: 1
has answer: http://stackoverflow.com/a/51235466
tagged with: date
type: Question
accepted answer: http://stackoverflow.com/a/51235447
downvote count: 0
has comment: http://stackoverflow.com/comment/89449525
tagged with: python
has answer: http://stackoverflow.com/a/51235348
tagged with: regex
answer count: 4
has answer: http://stackoverflow.com/a/51235415
favorite count: 0
tagged with: parsing
has title: bulding an array of dates from text
linked to: http://stackoverflow.com/q/25962114
possible better answer: http://stackoverflow.com/a/51235348
upvote count: 1
has body: I have a log (text) file with this syntax 1/21/18, 22:48 - ~text~ 1/21/18, 22:48 - ~text~ 1/23/18, 22:48 - ‪~text~ ~text~ ~text~ 1/24/18, 22:48 - ~text~ And I would like to get an array of all dates, for example ["1/21/18","1/21/18","1/23/18","1/24/18"] Because my final goal is to build an histogram of frequencies for each date to know the amount of events that each day had (just to know the evolution of events through time) (so, if you want to give a tip to do this easier, its welcome!) Ive tried regex according to question 4709652 but thats not working as expected. Anyways, one of my issues is that the textfile is big (hundreds of megabytes) which causes to slow down. Whats the optimal way to do this? Thanks!
tagged with: text
type: AnsweredQuestion

http://stackoverflow.com/q/51252555
has body: I created a Sequential model using tf.keras as follows: model = tf.keras.Sequential() model.add(tf.keras.layers.Dense(8, input_dim=4)) model.add(tf.keras.layers.Dense(3, activation=tf.nn.softmax)) opt = tf.train.AdamOptimizer(learning_rate=0.001) model.compile(optimizer=opt, loss="categorical_crossentropy", metrics=["accuracy"]) model.summary() After that, I created a training process using train_on_batch: EPOCHS=50 for epoch in range(EPOCHS): for metrics, labels in dataset: # Calculate training loss and accuracy tr_loss, tr_accuracy = model.train_on_batch(metrics, labels) When I try to save the model, I receive a warning. I can't understand why, because I included the optimizer as part of the model.compile: tf.keras.models.save_model( model, "./model/iris_model.h5", overwrite=True, include_optimizer=True ) WARNING:tensorflow:TensorFlow optimizers do not make it possible to access optimizer attributes or optimizer state after instantiation. As a result, we cannot save the optimizer as part of the model save file.You will have to compile your model again after loading it. Prefer using a Keras optimizer instead (see keras.io/optimizers). The TF version I used is 1.9.0-rc2.
type: AnsweredQuestion
tagged with: tensorflow
type: Question
possible better answer: http://stackoverflow.com/a/53749704
score: 5
has answer: http://stackoverflow.com/a/53749704
upvote count: 5
tagged with: keras
tagged with: optimization
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/51252809
favorite count: 0
has title: tf.keras.models.save_model and optimizer warning
accepted answer: http://stackoverflow.com/a/51252809
tagged with: machine-learning
tagged with: python

sockets
tags question: http://stackoverflow.com/q/51248067
tags question: http://stackoverflow.com/q/51323887
tags question: http://stackoverflow.com/q/51281111
tags question: http://stackoverflow.com/q/51174703
tags question: http://stackoverflow.com/q/51312354
tags question: http://stackoverflow.com/q/51185293
tags question: http://stackoverflow.com/q/51294154
tags question: http://stackoverflow.com/q/51294742
tags question: http://stackoverflow.com/q/51270047
tags question: http://stackoverflow.com/q/51309895
tags question: http://stackoverflow.com/q/51190998
tags question: http://stackoverflow.com/q/51214972
tags question: http://stackoverflow.com/q/51295792
tags question: http://stackoverflow.com/q/51220668
tags question: http://stackoverflow.com/q/51276461
type: Tag
tags question: http://stackoverflow.com/q/51309341
tags question: http://stackoverflow.com/q/51222060
tags question: http://stackoverflow.com/q/51317060
tags question: http://stackoverflow.com/q/51311741
tag name: sockets
tags question: http://stackoverflow.com/q/51179778
tags question: http://stackoverflow.com/q/51234623
tags question: http://stackoverflow.com/q/51268671
tags question: http://stackoverflow.com/q/51308870
tags question: http://stackoverflow.com/q/51323494
tags question: http://stackoverflow.com/q/51230046

http://stackoverflow.com/comment/89616731
has text: Thanks, that works exactly as I need it!
score: 0
comment on: http://stackoverflow.com/q/51320142
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89415766
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/51217105
type: Comment
has text: it's no longer necessary except if the pattern must be `ports <something>` not just `<something>` so it's not wrong.

updates
tags question: http://stackoverflow.com/q/51313649
tag name: updates
type: Tag
tags question: http://stackoverflow.com/q/51308683

http://stackoverflow.com/comment/89374280
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51195679
has text: I have it there. I want to fetch it in author_total_blogs. I have tried your code, it gives the error that 'blog' is not a field

http://stackoverflow.com/q/51171367
tagged with: pandas
upvote count: 0
accepted answer: http://stackoverflow.com/a/51171744
favorite count: 0
has comment: http://stackoverflow.com/comment/89328369
tagged with: python
has body: I have a big dataframe in pandas that looks like this: from_node to_node 0 0 1 1907 2343 0.1 2 2343 2344 0.2 3 2050 2051 0.1 4 2050 2344 0.4 .... I want to create 2 new dataframes on with node_loss so the data from the 0 column grouped and added with an index from the from_node and one dataframe withe the node_add so the same data from the 0 column grouped and added with an index from the to_node column. How do I do this?
has answer: http://stackoverflow.com/a/51171620
downvote count: 1
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/51171620
score: -1
has comment: http://stackoverflow.com/comment/89325506
has answer: http://stackoverflow.com/a/51171744
type: Question
tagged with: python-2.7
answer count: 2
has title: Grouping and adding large dataframe python pandas

scikit-learn
tags question: http://stackoverflow.com/q/51200437
tags question: http://stackoverflow.com/q/51215433
tags question: http://stackoverflow.com/q/51221303
tags question: http://stackoverflow.com/q/51303638
tags question: http://stackoverflow.com/q/51241340
tags question: http://stackoverflow.com/q/51291082
tags question: http://stackoverflow.com/q/51243650
tags question: http://stackoverflow.com/q/51295841
tags question: http://stackoverflow.com/q/51295392
tags question: http://stackoverflow.com/q/51254818
tags question: http://stackoverflow.com/q/51210210
tags question: http://stackoverflow.com/q/51275590
tags question: http://stackoverflow.com/q/51282423
tags question: http://stackoverflow.com/q/51229016
tags question: http://stackoverflow.com/q/51306645
tags question: http://stackoverflow.com/q/51200281
tags question: http://stackoverflow.com/q/51278752
tags question: http://stackoverflow.com/q/51172335
tags question: http://stackoverflow.com/q/51217367
tags question: http://stackoverflow.com/q/51309166
tags question: http://stackoverflow.com/q/51320227
tags question: http://stackoverflow.com/q/51258645
tags question: http://stackoverflow.com/q/51247739
tags question: http://stackoverflow.com/q/51295724
tags question: http://stackoverflow.com/q/51317810
tags question: http://stackoverflow.com/q/51225794
tags question: http://stackoverflow.com/q/51286339
tags question: http://stackoverflow.com/q/51276171
tags question: http://stackoverflow.com/q/51172889
tags question: http://stackoverflow.com/q/51272258
tags question: http://stackoverflow.com/q/51300559
tags question: http://stackoverflow.com/q/51194627
tags question: http://stackoverflow.com/q/51308291
tags question: http://stackoverflow.com/q/51256769
tags question: http://stackoverflow.com/q/51308994
tags question: http://stackoverflow.com/q/51322554
tags question: http://stackoverflow.com/q/51294587
tags question: http://stackoverflow.com/q/51185274
tags question: http://stackoverflow.com/q/51298992
tags question: http://stackoverflow.com/q/51245311
tags question: http://stackoverflow.com/q/51301570
tag name: scikit-learn
tags question: http://stackoverflow.com/q/51204532
tags question: http://stackoverflow.com/q/51274560
tags question: http://stackoverflow.com/q/51317311
tags question: http://stackoverflow.com/q/51256753
tags question: http://stackoverflow.com/q/51181170
tags question: http://stackoverflow.com/q/51217867
tags question: http://stackoverflow.com/q/51257116
tags question: http://stackoverflow.com/q/51271368
type: Tag
tags question: http://stackoverflow.com/q/51318367
tags question: http://stackoverflow.com/q/51180033
tags question: http://stackoverflow.com/q/51206457
tags question: http://stackoverflow.com/q/51314845
tags question: http://stackoverflow.com/q/51263896
tags question: http://stackoverflow.com/q/51278660
tags question: http://stackoverflow.com/q/51208115
tags question: http://stackoverflow.com/q/51264478
tags question: http://stackoverflow.com/q/51297423
tags question: http://stackoverflow.com/q/51177205
tags question: http://stackoverflow.com/q/51216470
tags question: http://stackoverflow.com/q/51196227
tags question: http://stackoverflow.com/q/51197496
tags question: http://stackoverflow.com/q/51201789
tags question: http://stackoverflow.com/q/51234485
tags question: http://stackoverflow.com/q/51272642
tags question: http://stackoverflow.com/q/51189676
tags question: http://stackoverflow.com/q/51313599
tags question: http://stackoverflow.com/q/51203869
tags question: http://stackoverflow.com/q/51235597
tags question: http://stackoverflow.com/q/51168298
tags question: http://stackoverflow.com/q/51309526
tags question: http://stackoverflow.com/q/51237635
tags question: http://stackoverflow.com/q/51306881
tags question: http://stackoverflow.com/q/51282098
tags question: http://stackoverflow.com/q/51223052
tags question: http://stackoverflow.com/q/51230654
tags question: http://stackoverflow.com/q/51307275
tags question: http://stackoverflow.com/q/51216020

http://stackoverflow.com/comment/89556002
type: Comment
type: QuestionComment
has text: Thank you for your help. I already tested it with "create" and it creates me one record with the market_id and application_id and n records for n selected records (in my case sale.order.line). I want to have n records with market_id, application_id and the partner_id (one record for each partner_id without double records). Best regards, Paul
score: 0
comment on: http://stackoverflow.com/q/51204422

http://stackoverflow.com/q/51228548
has body: I have an application using tkinter where different actions are required on mouse click, double click and when the mouse is being moved. The following class works however I wonder if there is no easier- or tkinter builtin way of doing this? from tkinter import Tk, Canvas class MouseControl: ''' Class for mouse control to establish if there is a 'click', 'double click' or mouse is being moved ''' def __init__(self, aw): self.double_click_flag = False self.button_released_flag = False self.aw = aw self.aw.bind('&lt;Button-1&gt;', self.clicked) # bind left mouse click self.aw.bind('&lt;Double-1&gt;', self.double_click) # bind double left clicks self.aw.bind('&lt;ButtonRelease-1&gt;', self.button_released) # bind button release self.aw.bind('&lt;B1-Motion&gt;', self.moved) # bring when mouse is moved def clicked(self, event): ''' add a little delay before calling action to allow for double click and button released to have occurred ''' self.double_click_flag, self.button_released_flag = False, False self.aw.after(300, self.action, event) def double_click(self, event): ''' set flag when there is a double click ''' self.double_click_flag = True def button_released(self, event): ''' set flag when button is released ''' self.button_released_flag = True def moved(self, event): ''' define action on when mouse is moved in this case just printing the coordinates''' print('mouse position is at ({:03}. {:03})'. format(event.x, event.y), end='\r') def action(self, event): ''' define action on click and double click in this case just printing the event ''' if self.button_released_flag: if self.double_click_flag: print('double mouse click event') else: print('single mouse click event') root = Tk() window = Canvas(root, width=400, height=400, bg='grey') mouse = MouseControl(window) window.place(x=0, y=0) window.mainloop()
tagged with: tkinter
has comment: http://stackoverflow.com/comment/89436999
type: UnansweredQuestion
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/89437710
type: Question
has comment: http://stackoverflow.com/comment/89437563
has title: On click, doubleclick and mouse moving
score: 0

http://stackoverflow.com/q/51243185
tagged with: argparse
tagged with: python
has answer: http://stackoverflow.com/a/51249513
type: AnsweredQuestion
score: 0
type: Question
has title: Selected options activate right subparsers
accepted answer: http://stackoverflow.com/a/51249513
answer count: 1
has body: I have to invoke my script in this way. script.py multiple --ways aa bb -as abab -bs bebe In this case -as abab reffers to "aa" option from --ways parameter and -bs bebe to "bb" option. And all chosed options should affect what "fulfill" method will be used. If we chose 'aa' and 'bb' there should only be options '-as' and '-bs' not '-cs'. import sys from argparse import ArgumentParser def fulfill_aa_parser(aa_parser): aa_parser.add_argument('--ass', '-as', type=str, required=True, choices=['abababa']) def fulfill_bb_parser(aa_parser): aa_parser.add_argument('--bass', '-bs', type=str, required=True, choices=['bebebe']) def fulfill_cc_parser(aa_parser): aa_parser.add_argument('--cass', '-cs', type=str, required=True, choices=['cycycyc']) def fulfill_multiple_parser(multiple_parser): multiple_parser.add_argument('--ways', '-w', type=str, choices=['aa','bb', 'cc'], nargs='+', required=True) def main(argv): parser = ArgumentParser(description='TEST CASE') subparsers = parser.add_subparsers(dest='type') multiple_parser = subparsers.add_parser( 'multiple' ) aabbparsers = multiple_parser.add_subparsers() aa_parser = aabbparsers.add_parser('aa') bb_parser = aabbparsers.add_parser('bb') cc_parser = aabbparsers.add_parser('cc') fulfill_multiple_parser(multiple_parser) fulfill_aa_parser(aa_parser) fulfill_bb_parser(bb_parser) fulfill_cc_parser(cc_parser) args = parser.parse_args(argv) if args.type is None: parser.print_help() return if __name__ == '__main__': main(sys.argv[1:]) Parsing this in this way: fulfill_aa_parser(multiple_parser) fulfill_bb_parser(multiple_parser) fulfill_cc_parser(multiple_parser) will lead to parser always asking for '-as', '-bs' ,'-cs' and options in '--ways' will not affect this EDIT : \ This is it looks when there is some thought put to it. Just simply pass parser to this function def fulfill_apple_argparser(parser): parser.add_argument("--apple_argument") def fulfill_banana_argparser(parser): parser.add_argument("--banana_argument") def fulfill_pe…
tagged with: python-3.x

http://stackoverflow.com/a/51191605
has body: If it's just the intention to find the closest k points, what do you think of this one? Start by putting the first k points into some sorted array (based on distance to your source point), and calculate the maximum distance, call this d_max. For every new point p, do following check: if (x_p - x_start &gt; d_max) or (y_p - y_start &gt; d_max) then disregard(x) else: d = distance (x, start); if d &lt; d_max then: insert_into_array(x) // obviously the array must stay sorted d_max = distance(array[k],start) The idea behind is the following: if the difference between the X-coordinates or the Y-coordinates is larger than the maximal distance, then the distance will be larger too. E.g. Imagine your starting point is (2,2), and you have already added (2,6), (2,3) and (3,2), then d_max will be 4. Your other points are (10,0), (0,20) and (5,6), then the following will happen: Add (10,0)? No, because 10 - 2 &gt; 4 (x_p - x_start &gt; d_max) Add (0,20)? No, because 20 - 2 &gt; 4 (y_p - y_start &gt; d_max) Add (5,6) ? Maybe: 5 - 2 &lt;= d_max (X-coordinates) =&gt; ok 6 - 2 &lt;= d_max (Y-coordinates) =&gt; ok distance((5,6),(2,2)) = 5, which is larger than 4 =&gt; don't add (5,6) Obviously, you need to create some kind of "array": where you can add a point, somewhere in the middle, so that the others shift accordingly (linked list). in case you add a point and you already have k entries, the last entry should be removed. As you only need to compare the distances, there's no need to calculate the square root.
score: 0
answers question: http://stackoverflow.com/q/51188662
type: Answer

http://stackoverflow.com/comment/89435339
type: QuestionComment
has text: It will be much easier to answer your question if you give the full traceback of exception.
comment on: http://stackoverflow.com/q/51227600
score: 0
type: Comment

http://stackoverflow.com/a/51251141
downvote count: 0
score: 1
type: Answer
upvote count: 1
has body: You used from datetime import datetime which means your datetime name is already pointing to datetime.datetime. If you try to access datetime.datetime you will end up accessing datetime.datetime.datetime which doesn't exist. You should use just import datetime instead, and in your code use datetime.datetime and datetime.timedelta, but if you still want to use from datetime import datetime, timedelta, you have to change all datetime.datetimes in your code to say only datetime and datetime.timedelta to say only timedelta.
accepted answer of: http://stackoverflow.com/q/51251113
answers question: http://stackoverflow.com/q/51251113
has comment: http://stackoverflow.com/comment/89481655
type: AcceptedAnswer

http://stackoverflow.com/q/51242520
tagged with: python
score: 0
answer count: 1
has title: Unable to open/include a YARA file
has body: I created a script that analyzes files based on yara rules ( the yara are the ones from this repository https://github.com/Yara-Rules/rules). My script import a yara file that include all other rules.When i try to compile it, i receive a syntax error: "can't open include file: rules_for_files\Antidebug_AntiVM_index.yar", pointing me to one of the rules. I tried to exclude it but it continue points to others. I tried to use different versions of python: 1.i used python2.7 and i received the mentioned error in both case when i use a binary string/raw string. About python 3.5 when i mentioned a binary string like the one from my code sample, the interpreter broke/reset(in case i use a GUI). How can i resolve this? Thank you. rules = yara.compile(filepaths={ "malware_set1 rules": b'C:/Users/g_bondrila/Desktop/phishme/functionalitati/yararules/importyara.yar'}) def yara_match(file_path, rules=rules): try: matches = rules.match(file_path, timeout=60) return matches #except TimeoutError: # print("the time is running out") except: print("something")
type: UnansweredQuestion
tagged with: python-2.7
tagged with: yara
tagged with: python-3.x
type: Question
has answer: http://stackoverflow.com/a/51242642

http://stackoverflow.com/comment/89368205
comment on: http://stackoverflow.com/q/51193354
has text: dont you need to activate unicode or something?
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/89462490
comment on: http://stackoverflow.com/q/51240882
type: QuestionComment
type: Comment
score: 2
has text: From the image you show, the text is flipped vertically, not horizontally. Can you be more clear on what you want to achieve? Why not plot all letters in a non-flipped fashion?

http://stackoverflow.com/a/51283886
has body: These are basically stopwords.To remove them,you need to download nltk package which has all the english stopwords from nltk.corpus import stopwords w = stopwords.words('english') #lets say data is a string which has your sentence for word in w: if word in data: data.replace(word,'')
accepted answer of: http://stackoverflow.com/q/51283580
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51283580
type: Answer

http://stackoverflow.com/q/51190447
has answer: http://stackoverflow.com/a/51190591
accepted answer: http://stackoverflow.com/a/51190591
answer count: 1
downvote count: 0
favorite count: 0
tagged with: rest
tagged with: python
score: 1
has title: is the following a valid json ? how do I convert it into a dict in python
upvote count: 1
type: Question
type: AnsweredQuestion
tagged with: http://stackoverflow.com/tag/json
has body: Is the following a valid JSON : "AGENT ": { "pending": [], "active": null, "completed": [{}] }, "MONITORING": { "pending": [], "active": null, "completed": [{}] } json validator sites (https://jsonlint.com/) says it it isn't. How can I make this a valid json ? converting this to a dict in python truncates blocks of json (the "AGENT" part). How can I convert this block to a dict in python without losing json blocks ? This is JSON returned from a GET request. Using the following does not work response = requests.get(&lt;url&gt;) data = response.content json_data = json.dumps(data) item_dict = json.loads(data) item_dict = data

http://stackoverflow.com/comment/89521789
comment on: http://stackoverflow.com/q/51270560
type: QuestionComment
has text: Using @Patrick Haugh's above comment, I finally got it figured out.
score: 0
type: Comment

http://stackoverflow.com/q/51254057
has comment: http://stackoverflow.com/comment/89487408
favorite count: 0
tagged with: apache-beam
tagged with: python
score: 4
has body: I tag input elements based on one of input data elements(date). class TagElementsWithDate(beam.DoFn): def process(self, element): dt = element['date'].replace('-', '')[:6] yield pvalue.TaggedOutput(dt, element) input_data = p | 'Read Input' &gt;&gt; beam.io.Read(beam.io.BigQuerySource(query='select id, date from `project.dataset.tablename`', use_standard_sql=True)) tagged_data = input_data | 'tag data' &gt;&gt; beam.ParDo(TagElementsWithDate()).with_outputs() tagged_data is DoOutputsTuple. I'm looking to iterate this and write each tagged data to a separate file.
type: UnansweredQuestion
type: Question
has title: Apache beam write each tagged output to separate file
upvote count: 4
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/70900518

http://stackoverflow.com/comment/89486996
score: 1
comment on: http://stackoverflow.com/q/51253916
has text: Can't reproduce the problem. I run your exact code and get lots of links printed, like `/Notice/Details/999999` in addition to the ones you added to the question.
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/138392703
type: AnswerComment
type: Comment
has text: To make `csv_to_df` more reliable, you could use `replace` on the column names. Or you could just iterate over all columns e.g. with `df.shape[2]`.
comment on: http://stackoverflow.com/a/51245663
score: 0

http://stackoverflow.com/comment/89484490
type: AnswerComment
comment on: http://stackoverflow.com/a/51252567
type: Comment
score: 3
has text: Abuse? I didn't mean to abuse you. Note that `span` is simply a "container" for text node. Clicking `button` node should be sufficient to trigger required behavior

http://stackoverflow.com/comment/89329419
type: Comment
has text: [`ResultSet`](http://influxdb-python.readthedocs.io/en/latest/api-documentation.html#resultset) doesn't have a method for csv export
score: 1
comment on: http://stackoverflow.com/q/51172784
type: QuestionComment

http://stackoverflow.com/comment/89599458
type: AnswerComment
comment on: http://stackoverflow.com/a/51310505
type: Comment
score: 0
has text: @KirillBulygin Okay, good to know. I checked, and the one from itertools is also implemented with shallow copying.

django-generic-views
type: Tag
tag name: django-generic-views
tags question: http://stackoverflow.com/q/51219209

http://stackoverflow.com/comment/89525235
has text: i have two text files, and let's say if I enter a number, will it output the correct information associated with that line, the 6 variables in the class
comment on: http://stackoverflow.com/q/51273207
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89397908
comment on: http://stackoverflow.com/q/51208397
score: 0
type: Comment
type: QuestionComment
has text: @GoogleUser: whatever could be your reason for removing the tag `python`!?

http://stackoverflow.com/comment/89558669
score: 0
comment on: http://stackoverflow.com/a/51290164
has text: This will leave whitespace in `df['name_of_code']`. I think you need an additional `str.strip`.
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/94199574
type: QuestionComment
comment on: http://stackoverflow.com/q/51180191
score: 0
has text: There is not a very obvious answer to this, you can use native python `list` to do the job, if you are working with `dict` objects, then opting for `json` might be beneficial. However, given that `pandas` is built on augmenting `np.array`, which is mainly designed to handle vectorized data formats.
type: Comment

http://stackoverflow.com/q/51253977
tagged with: machine-learning
tagged with: python
has title: Azure: Training a machine learning model dynamically through a ASP.NET MVC web application
has body: Is there a way to dynamically train a model through a web application in AZURE? It does not seem they have any sort of API to do this. I know I can train a model then create a web service through AZURE. I can then call this model and either re train it or make predictions. But i want to train a model through a C# .NET application. I am trying to create a web application that allows users to up load data then have them be able to create a model to make predictions. I wanted to use AZURE on the back end for the statistical analysis rather then creating a class and web service in Python. I basically do not want to use the AZURE studio or command line but i would like to train it through an API or another service (that im hoping they offer!)
tagged with: azure-machine-learning-service
type: Question
tagged with: c#
has answer: http://stackoverflow.com/a/51254853
score: 0
tagged with: azure
answer count: 1
type: UnansweredQuestion

http://stackoverflow.com/a/66194137
has comment: http://stackoverflow.com/comment/137058507
type: Answer
upvote count: 3
score: 3
answers question: http://stackoverflow.com/q/51285717
has body: Shortly: Developers of drf-yasg have answered about it. Problem in OpenAPI 2.0 specification and you could use https://github.com/tfranzel/drf-spectacular (it support OpenAPI 3.0) instead of drf-yasg. You could in create special serializer for decorator only @swagger_auto_schema(responses={200: CustomResponseSerializer()}) or make your serilializer's fields dynamic(Django Rest Framework: Dynamically return subset of fields) and decorate action in viewset like this @swagger_auto_schema(responses={200: YourSerializer(fields=['some_field_name', 'another_...')}) Also in https://github.com/axnsan12/drf-yasg/issues/70 you could find another way from https://github.com/axnsan12/drf-yasg/issues/70#issuecomment-698288806
downvote count: 0

http://stackoverflow.com/q/51196227
accepted answer: http://stackoverflow.com/a/51196339
answer count: 2
possible better answer: http://stackoverflow.com/a/57863188
has answer: http://stackoverflow.com/a/57863188
tagged with: scikit-learn
has body: I'm teaching myself some more tricks with python and scikit, and I'm trying to plot a linear regression model. My code can be seen below. But my program and console give the following error: x and y must be the same size. Additionally, my program makes it to the end of my code, but nothing gets plotted. To fix the size error, the first thing that came to mind was testing the length of x and y with something like len(x) == len(y). But as far as I can tell, my data seems to be the same length. Maybe the error is referring to something other than length (if so, I'm not sure what). Would really appreciate any help. from sklearn import cross_validation from sklearn.naive_bayes import GaussianNB from sklearn.model_selection import train_test_split from sklearn import linear_model import numpy as np import pandas as pd import matplotlib.pyplot as plt # Create linear regression object regr = linear_model.LinearRegression() #load csv file with pandas df = pd.read_csv("pokemon.csv") #remove all string columns df = df.drop(['Name','Type_1','Type_2','isLegendary','Color','Pr_Male','hasGender','Egg_Group_1','Egg_Group_2','hasMegaEvolution','Body_Style'], axis=1) y= df.Catch_Rate x_train, x_test, y_train, y_test = cross_validation.train_test_split(df, y, test_size=0.25, random_state=0) # Train the model using the training sets regr.fit(x_train, y_train) # Make predictions using the testing set pokemon_y_pred = regr.predict(x_test) print (pokemon_y_pred) # Plot outputs plt.title("Linear Regression Model of Catch Rate") plt.scatter(x_test, y_test, color='black') plt.plot(x_test, pokemon_y_pred, color='blue', linewidth=3) plt.xticks(()) plt.yticks(()) plt.show()
has comment: http://stackoverflow.com/comment/89374180
has comment: http://stackoverflow.com/comment/89374116
favorite count: 0
has comment: http://stackoverflow.com/comment/89374426
tagged with: prediction
upvote count: 2
has comment: http://stackoverflow.com/comment/89374089
has comment: http://stackoverflow.com/comment/89374284
has title: Python - Plotting and linear regression - x and y must be the same size
tagged with: python
tagged with: plot
type: AnsweredQuestion
tagged with: linear-regression
score: 1
has comment: http://stackoverflow.com/comment/89374141
has answer: http://stackoverflow.com/a/51196339
has comment: http://stackoverflow.com/comment/89374622
has comment: http://stackoverflow.com/comment/89374168
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/89374364

http://stackoverflow.com/q/51217344
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51217365
upvote count: 1
has body: test = {'a':{'aa':'value','ab':'value'},'b':{'aa':'value','ab':'value'}} #test 1 for x in test: print(x['aa']) #test 2 for x in test: print(test[x]['aa']) Why does test 1 give me a TypeError: string indices must be integers but test 2 pass? Does the for loop turn the dictionary into a string?
has answer: http://stackoverflow.com/a/51217372
type: Question
score: 1
possible better answer: http://stackoverflow.com/a/51217372
accepted answer: http://stackoverflow.com/a/51217365
answer count: 2
downvote count: 0
has title: Iterating over dictionaries within dictionaries, dictionary object turning into string?
favorite count: 0
has comment: http://stackoverflow.com/comment/89415927
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89416124

http://stackoverflow.com/q/51314091
has answer: http://stackoverflow.com/a/51352125
has title: Flask: each route in its own module file?
type: Question
tagged with: restful-architecture
score: -1
tagged with: flask
has comment: http://stackoverflow.com/comment/89605839
downvote count: 1
answer count: 1
favorite count: 0
tagged with: python-3.x
has body: I have am developing a flask app that is both a regular website (serving HTML) and and a JSON API. It's structured like this (using blueprints for api and site) Project | +-- views | | | +-- api.py &lt;-- all routes for api | +-- site.py &lt;-- all routes for regular site | +-- __init__.py +-- category.py &lt;-- main project dir contains shared object modules +-- helpers.py +-- product.py ... That works OK, except that as the project grows, having all the routes in the api.py and site.py modules causes them to grow a mile long. I'd like to split out each route into its own module like this: Project | +-- views | | + |-- api | | | | | +-- __init__.py | | +-- cart.py &lt;-- each route has its own file | | +-- category.py | | +-- user.py | | +-- ... | | | + |-- site | | +-- __init__.py | | +-- cart.py | | +-- category.py | | +-- user.py | | +-- ... | | +-- __init__.py +-- category.py +-- helpers.py +-- product.py ... Or at least into modules that are grouped together like /user and all /user/* sub-routes would be put into ./views/api/user.py (for example). How can this be accomplished? or, is there a better way to approach?
type: UnansweredQuestion
tagged with: python
upvote count: 0

http://stackoverflow.com/q/51176030
has comment: http://stackoverflow.com/comment/89335069
tagged with: dataframe
score: -1
linked to: http://stackoverflow.com/q/51543616
type: Question
has answer: http://stackoverflow.com/a/51176513
has title: Filtering a DataFrame for data of id's of which the values are decreasing over time
downvote count: 2
answer count: 3
tagged with: pandas
upvote count: 1
has comment: http://stackoverflow.com/comment/89336335
has body: I have a large time series dataset of patient results. A single patient has one ID with various result values. The data is sorted by date and ID. I want to look only at patients of which the values are strictly descending over time. For example patient x has result values 5, 3, 2, 1 would be true. However 5,3,6,7,1 would be false. Example data: import pandas as pd df = pd.read_excel(...) print(df.head()) PSA PSAdate‎ PatientID ... datefirstinject ADTkey RT_PSAbin 0 2.40 2007-06-26 11448 ... 2006-08-05 00:00:00 1 14 1 0.04 2007-09-26 11448 ... 2006-08-05 00:00:00 1 15 2 2.30 2008-01-14 11448 ... 2006-08-05 00:00:00 1 17 3 4.03 2008-04-16 11448 ... 2006-08-05 00:00:00 1 18 4 6.70 2008-07-01 11448 ... 2006-08-05 00:00:00 1 19 So for this example, I want to only see lines with PatientIDs for which the PSA Value is decreasing over time. groupID = df.groupby('PatientID') def is_desc(d): for i in range(len(d) - 1): if d[i] &gt; d[i+1]: return False return True x = groupID.PSA.apply(is_desc) df['is_desc'] = groupID.PSA.transform(is_desc) #patients whose PSA values is decreasing overtime. df1 = df[df['is_desc']] I get: KeyError: 0 I suppose the loop cant make its way through the grouped values as it requires an array to find the 'range'. Any ideas for editing the loop?
has answer: http://stackoverflow.com/a/51177065
has comment: http://stackoverflow.com/comment/89390099
favorite count: 0
possible better answer: http://stackoverflow.com/a/51176513
has answer: http://stackoverflow.com/a/51180003
tagged with: python
has comment: http://stackoverflow.com/comment/89342487
accepted answer: http://stackoverflow.com/a/51180003
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89334996

http://stackoverflow.com/a/51304735
has comment: http://stackoverflow.com/comment/89588776
type: Answer
has comment: http://stackoverflow.com/comment/89622521
has comment: http://stackoverflow.com/comment/89592466
has comment: http://stackoverflow.com/comment/89761139
has comment: http://stackoverflow.com/comment/89761365
has comment: http://stackoverflow.com/comment/89587375
has comment: http://stackoverflow.com/comment/89628175
answers question: http://stackoverflow.com/q/51304490
has comment: http://stackoverflow.com/comment/89628426
accepted answer of: http://stackoverflow.com/q/51304490
has comment: http://stackoverflow.com/comment/89627848
has comment: http://stackoverflow.com/comment/89613742
has body: Since your img list is sorted by time already, you can iterate through the records and append them to the last sub-list of the output list (named groups in my example code) if the time difference to the last entry is no more than 5 seconds; otherwise put the record into a new sub-list of the output list. Keep in mind that in Python a subscript of -1 means the last item in a list. groups = [] for r in img: if groups and r[0] - groups[-1][-1][0] &lt;= 5: groups[-1].append(r) else: groups.append([r]) for g in groups: print(g[0][1], g[0][0], g[-1][0], g[-1][1])
score: 0
has comment: http://stackoverflow.com/comment/89613404
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89587288
has comment: http://stackoverflow.com/comment/89761601

http://stackoverflow.com/a/51235202
score: 1
has body: There are a few problems here: if you iterate over a list, you iterate over the elements of the list, not the indices; and if you query for type(..) you do not get a string as return element, but a reference to the class. So you can fix this like: board = [[1,2,3],[4,5,6],[7,8,9]] def drawboard(board): for row in board: for item in row: if type(item) == int: print(str(item)) print("|") else: print(item) print("|") print("\n") print("------") print("\n") drawboard(board) Since non-str items are typically str(..)-ed when you call print on them, we can even merge the if and else branch into: def drawboard(board): for row in board: for item in row: print(item) print("|") print("\n") print("------") print("\n") drawboard(board) If you proceed with this typecheck, typically checking for type equality is not really a good idea either. Since if the element is subclassed, the type is no longer int. You then better use isinstance(..).
upvote count: 1
has comment: http://stackoverflow.com/comment/89449460
answers question: http://stackoverflow.com/q/51235129
type: Answer
downvote count: 0

http://stackoverflow.com/q/51307191
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89592574
has comment: http://stackoverflow.com/comment/89591956
has comment: http://stackoverflow.com/comment/89591886
has comment: http://stackoverflow.com/comment/89591410
downvote count: 1
has comment: http://stackoverflow.com/comment/89592100
type: Question
has comment: http://stackoverflow.com/comment/89591172
has title: Python Regular Expression Finding No Matches
has comment: http://stackoverflow.com/comment/89591759
linked to: http://stackoverflow.com/q/1732348
score: 0
has comment: http://stackoverflow.com/comment/89591118
has body: I am looking for matches in the following string of text: ' \n \n \n \n SN G2250-010\n \n <!--[if gte mso 9]> \n<mso:CustomDocumentProperties>\r\n<mso:Service_x0020_Note msdt:dt="string">SN</mso:Service_x0020_Note>\r\n<mso:Order msdt:dt="string">1493700.00000000</mso:Order>\r\n<mso:ContentType msdt:dt="string">Document</mso:ContentType>\r\n</mso:CustomDocumentProperties>\n <![endif]-->\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n Life Sciences and Chemical Analysis Service Note\n \n \n \n \n \n \n \n SERVICE NOTE G2250-010\n \n Supersedes: None\r\n \r\nINB22000 compatibility with Windows 2000 and ChemStation A.9.01\r\n\r\nSerial Numbers:\r\nUS00000000 - US99999999\r\n\r\nThe CCMode software is in general compatible with Windows 2000 and \r\nChemStation Revision A.9.01. Please see required settings!\r\n\r\nTo Be Performed By:\r\nAgilent-Qualified Personnel\r\n\r\nParts Required:\r\n\r\nNone\r\n\r\nSituation:\r\nChanges of operating software to Windows 2000 and implementation\r\nof ChemStation Rev. A.9.01 required some testing of the CCMode \r\n\r\nsoftware INB22000 / INB22002 / INB22003 and INB22004 Rev. A.03.02.\r\n\r\nSolution/Action:\r\nBefore using the Micro-plate Sampling Software INB22000 / INB22002 \r\n/ INB22003 or INB22004 Rev. A.03.02 (CCMode) on a PC with \r\nWindows 2000 a minor change in the "Control panel" must be made. \r\nIf this change is not made some icons in the user interface will \r\nnot be represented correctly. The functionality itself is not \r\ninfluenced:\r\n\r\nOpen "Settings", "Control Panel", "Display", "Appearance".\r\n\r\nGo to the "Scheme" and select the choice "Windows Classic". \r\nPress "OK" and close the "Control Panel" window.Required "Regional \r\nSettings" for both WIN NT and WIN2000\r\n\r\nIn order to run and edit parameters within CC-Mode your \r\nPC must be setup in this way:\r\n\r\n- Regional settings: English (United States)\r\n- Number format (default for English (United States)) \r\n Decimal symbol \'.\'\r\n- Number fo…
has comment: http://stackoverflow.com/comment/89591216
answer count: 1
accepted answer: http://stackoverflow.com/a/51307340
has comment: http://stackoverflow.com/comment/89592351
has comment: http://stackoverflow.com/comment/89592288
favorite count: 0
has comment: http://stackoverflow.com/comment/89592047
has answer: http://stackoverflow.com/a/51307340
has comment: http://stackoverflow.com/comment/89591360
upvote count: 1
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/89591128
has comment: http://stackoverflow.com/comment/89592504
has comment: http://stackoverflow.com/comment/89591616
has comment: http://stackoverflow.com/comment/89591090

http://stackoverflow.com/comment/89461670
has text: Your python version ? i guess it is 2.7. Updated the answer to deal with the problem on line 3
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/51240619
score: 0

http://stackoverflow.com/comment/89422342
type: QuestionComment
comment on: http://stackoverflow.com/q/51199996
score: 0
type: Comment
has text: So, you don't find it necessary to respond even when you have got a solution @user1420492!!! What's wrong?

http://stackoverflow.com/comment/89597693
comment on: http://stackoverflow.com/a/51290150
has text: Thank you, most of the development I have done in the past was using Perl. I am relatively new to Python and am learning my way around as I go. I, unfortunately, find myself in the position of needing to get things done in a hurry, and my job requires me to wear a lot of hats and limits me in how I can focus on one particular subject. I don't like it as I don't get a complete education on things and it is somewhat frustrating. I will focus on the interactive interpreter as I kind of brushed it off as just interesting, but I can definitely see the value in it now.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/89592351
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/51307191
has text: @JoshDetwiler Please either explain how this is a duplicate of your link, where someone is actually trying to parse an html string without a parser. Otherwise, please remove the duplicate tag.
type: Comment

http://stackoverflow.com/q/51249781
upvote count: 3
tagged with: scikit-image
tagged with: image-processing
has comment: http://stackoverflow.com/comment/89493152
type: Question
has comment: http://stackoverflow.com/comment/89478797
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/51455694
has title: Using regionprops in Python
has comment: http://stackoverflow.com/comment/89479469
favorite count: 0
has answer: http://stackoverflow.com/a/58472209
type: UnansweredQuestion
tagged with: python
tagged with: matlab
score: 3
has body: I am trying to analyze greyscale TIFF stacks, in which a given frame will look like this. I filter it (using Gaussian blur), and then binarize it (using Otsu's method for threshold). MATLAB code, which works great: image_conncomp = bwconncomp(image_binary); # entire stack is held in image_binary for i=1:image_conncomp.NumObjects object_size = length(image_conncomp.PixelIdxList{i}); end Each white spot in the example image is picked up, and its volume (in pixels) is pretty accurately given by object_size. Python code: from skimage import measure labels = measure.label(image_binary, background=1) # same image_binary as above propsa = measure.regionprops(labels) for label in propsa: object_size = len(label.coords) The Python code seems to work decently... except that most detected objects will have object_size of 1 - 200, and then a couple will have a size of several thousand pixels. What are these functions doing differently? I would be happy to try another approach in Python to get calculate object sizes, but I struggled to find another one. It'd be great to have a Python version of this code, if I could find a good substitute for Matlab's bwconncomp function.
tagged with: scipy.ndimage

http://stackoverflow.com/comment/107609595
comment on: http://stackoverflow.com/a/51243274
score: 9
type: AnswerComment
type: Comment
has text: Thanks for the workaround. I'm facing the same issue in 2020, really wish there's a better solution

http://stackoverflow.com/q/51195964
score: 1
has answer: http://stackoverflow.com/a/51255347
tagged with: scipy
type: Question
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/51287842
has title: How can I change the number of basis functions when performing B-Spline fitting in scipy (python)?
upvote count: 1
favorite count: 0
tagged with: interpolation
type: UnansweredQuestion
tagged with: bspline
tagged with: python
has body: I have a discrete set of points (x_n, y_n) that I would like to approximate/represent as a linear combination of B-spline basis functions. I need to be able to manually change the number of B-spline basis functions used by the method, and I am trying to implement this in python using scipy. To be specific, below is a bit of code that I am using: import scipy spl = scipy.interpolate.splrep(x, y) However, unless I have misunderstood or missed something in the documentation, it seems I cannot change the number of B-spline basis functions that scipy uses. That seems to be set by the size of x and y. So, my specific questions are: Can I change the number of B-spline basis functions used by scipy in the "splrep" function that I used above? Once I have performed the transformation shown in the code above, how can I access the coefficients of the linear combination? Am I correct in thinking that these coefficients are stored in the vector spl[1]? Is there a better method/toolbox that I should be using? Thanks in advance for any help/guidance you can provide.

command-prompt
tags question: http://stackoverflow.com/q/51318362
tag name: command-prompt
type: Tag
tags question: http://stackoverflow.com/q/51312237

http://stackoverflow.com/comment/89466645
comment on: http://stackoverflow.com/q/51243386
has text: @gyx-hh Thanks for the quick update; I will surely check it.
type: Comment
score: 0
type: QuestionComment

pyserial
tags question: http://stackoverflow.com/q/51246764
tags question: http://stackoverflow.com/q/51182316
tags question: http://stackoverflow.com/q/51202387
type: Tag
tags question: http://stackoverflow.com/q/51169104
tags question: http://stackoverflow.com/q/51192715
tag name: pyserial
tags question: http://stackoverflow.com/q/51175606

http://stackoverflow.com/a/51252382
accepted answer of: http://stackoverflow.com/q/51252129
score: 2
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/89484004
has body: try to do the following changes with the remove_newlines function def remove_newlines(fname): with open(fname) as f: return f.read().replace("\n"," ") print(remove_newlines("test.txt")) One more thing i think of is, in window's line endings are "\r\n", may be try with that
type: Answer
upvote count: 2
answers question: http://stackoverflow.com/q/51252129

http://stackoverflow.com/a/51251008
type: AcceptedAnswer
downvote count: 0
score: 9
type: Answer
has body: Seems to be a continuing issue for Windows machines as seen on Github. A workaround seems to be uninstalling the pyreadline package.
has comment: http://stackoverflow.com/comment/123011480
has comment: http://stackoverflow.com/comment/89481001
answers question: http://stackoverflow.com/q/51250796
has comment: http://stackoverflow.com/comment/109019366
has comment: http://stackoverflow.com/comment/89481248
accepted answer of: http://stackoverflow.com/q/51250796
upvote count: 9
has comment: http://stackoverflow.com/comment/100228677

http://stackoverflow.com/comment/89433212
score: 0
comment on: http://stackoverflow.com/q/51226369
type: Comment
type: QuestionComment
has text: Maybe this title would work better then? _How to return the remaining elements of a list after the last match?_

http://stackoverflow.com/q/51248813
has comment: http://stackoverflow.com/comment/89485242
upvote count: 2
answer count: 2
has comment: http://stackoverflow.com/comment/125260991
has answer: http://stackoverflow.com/a/51270565
has answer: http://stackoverflow.com/a/75142133
tagged with: keras
favorite count: 0
tagged with: python
has title: Any ideas on what might be causing this TensorFlow error? (Object was never used)
score: 2
type: AnsweredQuestion
downvote count: 0
possible better answer: http://stackoverflow.com/a/75142133
tagged with: tensorflow
type: Question
accepted answer: http://stackoverflow.com/a/51270565
has body: I am training a sequence-to-sequence model on Keras with a Tensorflow backend, mostly following the tutorial here. I'm using TensorFlow v1.2.1 on a IBM Power8 machine with a P100 GPU When it hits my model.fit_generator() line, TensorFlow throws the following error: Object was never used (type &lt;class 'tensorflow.python.ops.tensor_array_ops.TensorArray'&gt;): &lt;tensorflow.python.ops.tensor_array_ops.TensorArray object at 0x3bfffc096dd8&gt; If you want to mark it as used call its "mark_used()" method. I tried looking for unused operations/tensors, but couldn't find any. Then, I marked every operation/tensor as used, but I still cannot get rid of this error.

http://stackoverflow.com/q/51298027
has answer: http://stackoverflow.com/a/51298067
answer count: 2
possible better answer: http://stackoverflow.com/a/51298067
score: 0
has title: Get values using regex in Python
tagged with: python
tagged with: regex
has answer: http://stackoverflow.com/a/51298289
has body: How can I get the values 4 and 5 for test1 using only regex. I have this string: test1 = -2, 2, 2, 0, 0, 0, 0, 0, 0, 0 test2= 27000, 20000, 30000, 16200, 8000, 8000, 8000, 8000, 8000, 8000 test3 = 1500, 1500, 1500, 1500, 1500, 1500, 1500, 1500, 1500, 1500 test4 = 7000, 7000, 7000, 8000, 8000, 4000, 4000, 4000, 4000, 4000 test5 = 500 I have this command: `\s(test)\s*=(?P&lt;test&gt;\D.*)` It selects 2 groups, but I would like to have the values 4 and 5. Or is there any other way? I don't want to use pandas.
tagged with: regex-group
type: Question
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51298289

http://stackoverflow.com/q/51323703
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51324321
favorite count: 0
type: Question
answer count: 2
downvote count: 2
tagged with: python
score: -2
tagged with: regex
accepted answer: http://stackoverflow.com/a/51324321
has title: Values inside specific parenthesis
upvote count: 0
possible better answer: http://stackoverflow.com/a/51323949
has body: I have text value as below, i need to find all the value between opening ( just before array['nosql'] and its corresponding closing parenthesis. There could be space or no space between ( and array['nosql'] Entire Text 2118|"((value5 IN('X5','X1','Y1.6','Z2.3','NO23') AND value1 NOT LIKE('%RISP%')) OR ( value5 is null AND ( array['nosql'] &lt;@ type_list AND (array['S4'] &lt;@ value_list OR array['Z6'] &lt;@ value_list OR array['C2.6'] &lt;@ value_list OR array['C2.5'] &lt;@ value_list OR array['NO24'] &lt;@ value_list)) AND ( array['no_key'] &lt;@ value_list AND NOT array['RISP'] &lt;@ value_list))) AND SL IN ('FS025','FS028','FS071','FPG01','FPG02','FPG03','FPG04','FPG05','FPG06','FPG07','FPG09','FPG10','FPG12','FPG13','FPG16','FPG17','FPG18', 'FPG19','FPG26','FPG28','FPG29','FPG30','FPG31','FPG34','FPG35','FPG40','FPG32','FPG45','FPG55','FPG56','FPG57','FPG58','FPG66','FPG97', 'FPG32','FPG33','FPG36','FPG37','FPG42','FPG59','FPG60')"|""|"CT"|"{FPG44,FPG09,FPG18,FPG59,FPG32,FPG11,FPG56,FPG03,FPG10,FPG58,FPG37, FPG04,FPG17,FPG60,FPG66,FS025,FPG28,FPG12,FPG16,FPG07,FPG31,FPG34,FPG40,FPG06,FPG55,FPG36,FPG19,FPG30,FS028,FPG26,FPG97,FPG42,FPG01, FPG29,FPG02,FS071,FPG33,FPG05,FPG45,FPG35,FPG13}"|""|"XSQC Target"|""|""|"1"|"Active"|""|"Speed ACP_ASiR"|"" Need below output since parenthesis ( just before array['nosql'] has all below record. ( array['nosql'] &lt;@ type_list AND (array['S4'] &lt;@ value_list OR array['Z6'] &lt;@ value_list OR array['C2.6'] &lt;@ value_list OR array['C2.5'] &lt;@ value_list OR array['NO24'] &lt;@ value_list)) I tried regex, but i cant get specific parenthesis, i am getting all parenthesis using below code but i need specific one. re.findall('\((.*?)\)',text)
has answer: http://stackoverflow.com/a/51323949

http://stackoverflow.com/a/51259383
has body: Defining a class for a network is not a bad idea. Danijar (LINK) states that all models in the TensorFlow codebase are defined this way. To tackle your problem, you could do several things. Firstly, when you define the __init__() method, you could define a session for the object: class AffineNetwork: def __init__(self, trainingData, targets, initialParams): self.trainingData = trainingData self.targets = targets self.weights = tf.get_variable("weights", initializer = tf.constant(initialParams[0])) self.bias = tf.get_variable("bias", initializer = tf.constant(initialParams[1])) self.outputs = tf.expand_dims(self.weights,0) @ trainingData + self.bias self.loss = tf.reduce_mean(tf.square(self.targets - self.outputs)) self.optimizer = tf.train.GradientDescentOptimizer(0.001) self.train_step = self.optimizer.minimize(self.loss) self.init = tf.global_variables_initializer() self.loss_summary = tf.summary.scalar("loss", self.loss) self.sess = tf.Session() This way, you have the same session available for all your operations. You have to adapt the rest of your code though, e.g. use self.sess.run() for evaluating your operations. Another option would be that you train the model in a session, save it to disk, and restore it in another session to do inference. That answers your first question, as different sessions do wipe out information, but it can be stored on disk (which makes sense considering that you don't wanna train every time before you do inference once).
downvote count: 0
has comment: http://stackoverflow.com/comment/89497636
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/51256365
score: 1
has comment: http://stackoverflow.com/comment/89497383

http://stackoverflow.com/a/51212802
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/51211892
upvote count: 1
has body: You've been shown a better Fibonacci function, but for learning purposes here's why yours isn't working. Let's look at your while loop. The first time through, you'll go through the if block. This sets num3 to 3, and then sets num2 to 3 as well. So your variables are (num, num2, num3) == (1, 3, 3). The next iteration will then take you into the elif block. I've removed the print for clarity. elif num3 &lt; 10000: num3 = num + num2 num2 = num num = num2 As you can see, after the first time you hit num2 = num, you are no longer ever changing the value of either num or num2. You just keep setting them equal to each other. As such, num3 will never change again after the first time through either, since it depends only on num and num2. It looks to me like what you actually meant to do was set num = num3 in that last line, using num3 as sort of a temp variable for holding a value while swapping the others. Making that simple change makes the code almost do what you're trying to do, only it turns out your if block isn't actually necessary at all. There's nothing special about the num3 == 2 case, and that's actually throwing off your results. So get rid of the if block and promote the elif to if, and your program will do more or less what you expect: while Katan == True: if num3 &lt; 10000: num3 = num + num2 num2 = num print num,num2,num3 num = num3 else: Katan = False There's still some trouble with the beginning of the sequence, but depending on where you're actually taking your final values from, that may be fixable by just changing your initial variables to (num, num2, num3) == (0, 1, 1).
type: Answer

http://stackoverflow.com/q/51250644
tagged with: python
has title: error with surf.get_at() pygame
has comment: http://stackoverflow.com/comment/89515647
tagged with: pygame-surface
type: Question
has answer: http://stackoverflow.com/a/65492766
score: 0
answer count: 1
tagged with: pygame
tagged with: python-3.x
has body: I have a game and I need to know what colour is under the player's feet but when I use surf.get_at_(x, y), it gives me white instead of blue or green. Any help would be appreciated, Thanks!
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89481170

http://stackoverflow.com/a/51264975
type: Answer
answers question: http://stackoverflow.com/q/51264727
has comment: http://stackoverflow.com/comment/89511511
score: 1
has comment: http://stackoverflow.com/comment/89516081
upvote count: 1
type: AcceptedAnswer
downvote count: 0
has body: The cause of the AttributeError is that the default argument is an empty tuple (), not an empty list []. Now, you're right not to use an empty list as a default argument for various reasons, but since you want to mutate this object, you do need a list. The solution is to do something like def podzb(x, lista=None): if lista is None: lista = [] ... # rest of function
accepted answer of: http://stackoverflow.com/q/51264727

http://stackoverflow.com/comment/89550345
type: QuestionComment
has text: For this type of things I usually use selenium to fill out the form for me in the browser, and then I save the cookie in a requests session. If the other answer does not help, or if you do not want to try selenium, maybe you can log in manually first and paste in the cookie to the session?
comment on: http://stackoverflow.com/q/51286018
score: 0
type: Comment

http://stackoverflow.com/q/51301426
answer count: 2
has comment: http://stackoverflow.com/comment/89581176
has body: I have written the following code for getting an output of the various districts located in the given city and their respective postal codes. I want my code to be able to receive input from the user (District Name) and output the City in which it is located and it's postal code. If the user inputs a postal code they'll get the respective district(s). zipcode = {"Trap City":{"C District": 100, "D District": 103, "E District": 104, "S District": 105}, "Zap City":{"R District": 200, "D District": 201}, "Los City": {"X District": 207, "Y District": 208}} district=input('Enter your district: ') for city in zipcode: if district in city: print(city,zipcode[city][district]) d_district = {k2: (k1, v2) for k1, v1 in zipcode.items() for k2, v2 in v1.items()} print(d_district) {'C District': ('Trap City', 100), 'D District': ('Zap City', 201), 'E District': ('Trap City', 104), 'R District': ('Zap City', 200), 'S District': ('Trap City', 105), 'X District': ('Los City', 207), 'Y District': ('Los City', 208)} d_code = {v2: k2 for k1, v1 in zipcode.items() for k2, v2 in v1.items()} print(d_code) {100: 'C District', 103: 'D District', 104: 'E District', 105: 'S District', 200: 'R District', 201: 'D District', 207: 'X District', 208: 'Y District'} Output: Enter your district: X District {'C District': ('Trap City', 100), 'D District': ('Zap City', 201), 'E District': ('Trap City', 104), 'S District': ('Trap City', 105), 'R District': ('Zap City', 200), 'X District': ('Los City', 207), 'Y District': ('Los City', 208)} {100: 'C District', 103: 'D District', 104: 'E District', 105: 'S District', 200: 'R District', 201: 'D District', 207: 'X District', 208: 'Y District'} &gt;&gt;&gt; The program instead just dumps all the information instead of searching for the value?
score: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51322210
type: UnansweredQuestion
has title: Value Search from Dictionary via User Input
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/51301693
type: Question

http://stackoverflow.com/q/51187280
has body: I am building an offline ionic application and need to be integrate it with my python script contains a standalone ML model trained and exported from the microsoft custom vision which classifies the trees.it takes picture as an input and returns a string. python server.py image.png this returns an output as Mango tree How can we access the python script or how to make it as a service ?
has title: can i access python script from ionic application
tagged with: python
has answer: http://stackoverflow.com/a/51187532
score: 2
upvote count: 2
type: UnansweredQuestion
tagged with: machine-learning
type: Question
tagged with: ionic-framework
downvote count: 0
answer count: 1
favorite count: 0

http://stackoverflow.com/q/51317270
type: Question
accepted answer: http://stackoverflow.com/a/51317646
has comment: http://stackoverflow.com/comment/89610656
has body: If I have a python list say : ['aaa', 'bbb']. Is this list stored in 2x8 bytes (for 64-bit addressing) - that is we have only pointers to strings in the list or is it stored in [len('aaa')+len('bbb')]*size_of_char - that is we have a contiguous storage of characters of each string in the list.
answer count: 2
has comment: http://stackoverflow.com/comment/89610645
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/89645921
tagged with: python
has answer: http://stackoverflow.com/a/51317646
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/1090104
score: 1
possible better answer: http://stackoverflow.com/a/51317427
has title: Are strings addressed by reference or value in Python?
upvote count: 1
has comment: http://stackoverflow.com/comment/89650253
has answer: http://stackoverflow.com/a/51317427

http://stackoverflow.com/a/51214336
accepted answer of: http://stackoverflow.com/q/51214041
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51214041
type: Answer
has body: It's possible that Python is using a cached bytecode version of your file, rather than reading the new version. If you have a __pycache__ directory, or any files with the extension .pyc, try deleting them and importing your file again.
score: 4
upvote count: 4

http://stackoverflow.com/comment/137542503
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51319484
has text: You can use this funtion ---> _convert_vector
type: AnswerComment

http://stackoverflow.com/q/51186646
has title: replace 'Decimal' from a list generated from dataframe
has answer: http://stackoverflow.com/a/51187402
type: Question
has comment: http://stackoverflow.com/comment/89355364
tagged with: dataframe
score: -1
tagged with: pandas
answer count: 1
downvote count: 1
favorite count: 0
has body: input_list is generated from pandas dataframe. I am looking to replace all such entries at once in pandas dataframe. input_list = {'borrower_master_id': 1000, 'attribute_derived_master_id': 100, 'year_id': 2018, 'quarter_id': 1.0, 'month_id': None, 'param1_value': Decimal('3.00'), 'param2_value': Decimal('223.00'), 'param3_value': None, 'param4_value': None, 'param5_value': None, 'formula_expression': 'param1+param2', 'attrib_type': 'Actual', 'derived_attrib_value': 226.0, 'is_active': True} expected_list = {'borrower_master_id': 1000, 'attribute_derived_master_id': 100, 'year_id': 2018, 'quarter_id': 1.0, 'month_id': None, 'param1_value': 3.0, 'param2_value': 223 'param3_value': None, 'param4_value': None, 'param5_value': None, 'formula_expression': 'param1+param2', 'attrib_type': 'Actual', 'derived_attrib_value': 226.0, 'is_active': True}
tagged with: python
accepted answer: http://stackoverflow.com/a/51187402
type: AnsweredQuestion
upvote count: 0

http://stackoverflow.com/q/51228874
downvote count: 0
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/89529943
tagged with: pyinstaller
tagged with: python
tagged with: exe
favorite count: 0
has body: I have a basic program for editing Google sheets, it doesn't have a big work load or anything. And it runs fine on my computer, which is the one it was designed on. But it doesn't work on the other two computers I've tried it on. It wont even open, it will pop up the window, and be blank and just keep loading for minutes, and stop responding. The computers are all 64 bit Windows OS, no while loops or anything that could get stuck in a loop are even in the code. So I'm guessing it has to do with my imports maybe? I don't know. import gspread from oauth2client.service_account import ServiceAccountCredentials import re import Tkinter as Tk from ttk import * import tkMessageBox import pickle from datetime import datetime import webbrowser import threading I import all of these, and use PyInstaller, any ideas why its not opening on others computers? I can share the code in entirety if needed but it is about 350 lines, so I assume no one needs it lol.
tagged with: tkinter
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89494263
upvote count: 1
has comment: http://stackoverflow.com/comment/89490817
score: 1
has title: Python 2.7 executable GUI wont load
type: Question
has comment: http://stackoverflow.com/comment/89494221

http://stackoverflow.com/comment/89378470
type: QuestionComment
comment on: http://stackoverflow.com/q/51198333
score: 2
has text: Please include the full traceback. Currently we don't know what line of code throws that error.
type: Comment

http://stackoverflow.com/comment/89618559
has text: you probably have a `time = datetime` somewhere else in your code, assigning a `datetime` object to the variable `time`
comment on: http://stackoverflow.com/q/51321564
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51293558
tagged with: python
has comment: http://stackoverflow.com/comment/89607268
has comment: http://stackoverflow.com/comment/89607225
tagged with: parsing
type: AnsweredQuestion
upvote count: 3
has comment: http://stackoverflow.com/comment/89569714
has comment: http://stackoverflow.com/comment/89607292
tagged with: pyparsing
type: Question
score: 3
has answer: http://stackoverflow.com/a/51335710
has comment: http://stackoverflow.com/comment/89591606
tagged with: logfile
answer count: 2
downvote count: 0
linked to: http://stackoverflow.com/q/50958427
has body: This is similar to a question I've asked before. I have written a pyparsing grammar logparser for a text file which contains multiple logs. A log documents every function call and every function completion. The underlying process is multithreaded, so it is possible that a slow function A is called, then a fast function B is called and finishes almost immediately, and after that function A finishes and gives us its return value. Due to this, the log file is very difficult to read by hand because the call information and return value information of one function can be thousands of lines apart. My parser is able to parse the function calls (from now on called input_blocks) and their return values (from now on called output_blocks). My parse results (logparser.searchString(logfile)) look like this: [0]: # first log - input_blocks: [0]: - func_name: 'Foo' - parameters: ... - thread: '123' - timestamp_in: '12:01' [1]: - func_name: 'Bar' - parameters: ... - thread: '456' - timestamp_in: '12:02' - output_blocks: [0]: - func_name: 'Bar' - func_time: '1' - parameters: ... - thread: '456' - timestamp_out: '12:03' [1]: - func_name: 'Foo' - func_time: '3' - parameters: ... - thread: '123' - timestamp_out: '12:04' [1]: # second log - input_blocks: ... - output_blocks: ... ... # n-th log I want to solve the problem that input and output information of one function call are separated. So I want to put an input_block and the corresponding output_block into a function_block. My final parse results should look like this: [0]: # first log - function_blocks: [0]: - input_block: - func_name: 'Foo' - parameters: ... - thread: '123' - timestamp_in: '12:01' - output_block: - func_name: 'Foo' - func_time: '3' - parameters: ... - thread: '123' - timestamp_out: '12:04' [1]: - input_block: - func_name: 'Bar' - parameters: ... - thread: '456' - timestamp_in: '12:02' - output_block: - func_name: 'Bar' - func_time: '1' - parameters: ... - thread: '456' - timestamp_out: '12:03' [1]: # second log - …
has comment: http://stackoverflow.com/comment/89569681
has comment: http://stackoverflow.com/comment/89584102
possible better answer: http://stackoverflow.com/a/72580269
favorite count: 0
accepted answer: http://stackoverflow.com/a/51335710
has answer: http://stackoverflow.com/a/72580269
has title: Editing pyparsing parse results
has comment: http://stackoverflow.com/comment/89607264

http://stackoverflow.com/q/51278473
type: AnsweredQuestion
has title: filling new dataframe column using corresponding past indices values and specific unique column values
tagged with: dataframe
type: Question
tagged with: for-loop
accepted answer: http://stackoverflow.com/a/51278881
score: 0
has answer: http://stackoverflow.com/a/51278881
tagged with: pandas
answer count: 1
tagged with: python
tagged with: python-3.x
has body: I want to know whether there is an elegant way of doing, what i did in a very long and i believe very crude manner. Lets say we have a dataframe where we have two columns: 'col1','col2'. Number of rows are 13. 'Col1' contains three variables: 'a', 'b' and 'c'. 'col2' contain random numerical values. Now i want to create a new column named 'teststat' which contains the value contained in 'col2' by variable in 'col1' the last time it occurred or is equal to the present value if this is it's first occurrence. For example if if 'a' occurs in row 0,1,4,6 and 12 and it's col2 value at these index locations is 32, 432 , 56, 4 and 34 then the value of test stat at these locations should be 32, 32, 432, 56 and 4. sample dataset of what i want: index col1 teststat col2 0 a 32.0 32 1 a 32.0 432 2 b 433.0 433 3 c 4.0 4 4 a 432.0 56 5 c 4.0 64 6 a 56.0 4 7 b 433.0 535 8 c 64.0 643 9 c 643.0 356 10 b 535.0 32 11 b 32.0 535 12 a 4.0 34 I have used the following code which uses the logic of storing the indices of where particular value out of 'a', 'b', 'c' occurs and then writing individual codes with for loops but I can see that this can become a problem while scaling up, for example if instead of only 3 unique values in 'col1' we have 500+ separate unique values. I want a solution/logic on what could be done for that scenario. I have added the code for what i have done below: cell[1]: for vals in list(df['col1'].unique()): if vals=='a': idxa = df.index[df['col1']=='a'] if vals=='b': idxb = df.index[df['col1']=='b'] if vals=='c': idxc = df.index[df['col1']=='c'] cell[2]: for i in range(len(idxa)): if i==0: df.loc[idxa[i],'test_stat']=df.loc[idxa[i],'col2'] else: df.loc[idxa[i],'test_stat']=df.loc[idxa[i-1],'col2'] for i in range(len(idxb)): if i==0: df.loc[idxb[i],'test_stat']=df.loc[idxb[i],'col2'] else: df.loc[idxb[i],'test_stat']=df.loc[idxb[i-1],'col2'] for i in range(len(idxc)): if i==0: df.loc[idxc[i],'test_stat']=df.loc[idxc[i],'col2'] else: df.loc[idxc[i],'test_stat']=df.l…

http://stackoverflow.com/comment/89337835
has text: Since `train_generator` uses `threading.Lock`, I would suppose, it somehow falls into a deadlock. Try to debug it. I've moved from similar generators to subclasses of `keras.utils.Sequence`
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51176661

http://stackoverflow.com/a/51207017
type: Answer
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/51201380
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51201380
has body: This should do the trick. I don't think you can improve much upon iterating through the dataframe in order to assign the ID's, since they're based on a chained connection to previous values in the column: d = {"created_at": pd.to_datetime(["2018-07-03 02:12:33", "2018-07-03 02:12:35","2018-07-03 02:12:40","2018-07-03 02:12:45","2018-07-03 02:12:48","2018-07-03 03:15:17","2018-07-03 03:15:20","2018-07-03 03:15:23","2018-07-03 03:15:28","2018-07-03 03:15:33","2018-08-03 09:00:00","2018-09-03 10:15:00"]), "message": ["knock knock","who's there","Europe","Europe who?","No - you're a poo","knock knock","who's there","the KGB","the KGB who?","SLAP the KGB will ask q's!","Hello?","Hello, again?"]} import pandas as pd import numpy as np #60mins in secs thresh = 60*60 df = pd.DataFrame(data=d) #Creating time delta from previous message df["delta"] = df["created_at"].diff().fillna(0).dt.total_seconds() #Normalising delta based on threshold as a flag for new convos df["id"] = np.where(df["delta"] &lt; thresh, 0, 1) df = df.drop(["delta"], axis=1) #Assigning ID's to each convo for i in range(1, len(df)): df.loc[i, 'id'] += df.loc[i-1, 'id'] print(df) created_at message id 0 2018-07-03 02:12:33 knock knock 0 1 2018-07-03 02:12:35 who's there 0 2 2018-07-03 02:12:40 Europe 0 3 2018-07-03 02:12:45 Europe who? 0 4 2018-07-03 02:12:48 No - you're a poo 0 5 2018-07-03 03:15:17 knock knock 1 6 2018-07-03 03:15:20 who's there 1 7 2018-07-03 03:15:23 the KGB 1 8 2018-07-03 03:15:28 the KGB who? 1 9 2018-07-03 03:15:33 SLAP the KGB will ask q's! 1 10 2018-08-03 09:00:00 Hello? 2 11 2018-09-03 10:15:00 Hello, again? 3
upvote count: 1
has comment: http://stackoverflow.com/comment/89408814

pytorch
tags question: http://stackoverflow.com/q/51304809
tags question: http://stackoverflow.com/q/51243969
tags question: http://stackoverflow.com/q/51183040
tags question: http://stackoverflow.com/q/51198474
tags question: http://stackoverflow.com/q/51322688
tags question: http://stackoverflow.com/q/51234035
tags question: http://stackoverflow.com/q/51180423
tags question: http://stackoverflow.com/q/51173695
tag name: pytorch
type: Tag
tags question: http://stackoverflow.com/q/51202485
tags question: http://stackoverflow.com/q/51259119
tags question: http://stackoverflow.com/q/51296898
tags question: http://stackoverflow.com/q/51257780
tags question: http://stackoverflow.com/q/51179133
tags question: http://stackoverflow.com/q/51227017
tags question: http://stackoverflow.com/q/51231852
tags question: http://stackoverflow.com/q/51252221

authentication
tags question: http://stackoverflow.com/q/51254264
tags question: http://stackoverflow.com/q/51312601
tags question: http://stackoverflow.com/q/51209613
tag name: authentication
type: Tag
tags question: http://stackoverflow.com/q/51233792
tags question: http://stackoverflow.com/q/51224079
tags question: http://stackoverflow.com/q/51264436

http://stackoverflow.com/comment/89497838
has text: Meanwhile: why don't you just try it instead of guessing? If you have your 1.0.4 version ready to go, sdist upload it. Either it will work, and you don't need to ask, or it will give you an error, and then you can ask a more specific and better-researched question about how to work around that problem; it's not obviously going to delete your 1.0.3 or anything like that.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51259599
score: 2

http://stackoverflow.com/q/51254244
has comment: http://stackoverflow.com/comment/89487526
type: UnansweredQuestion
upvote count: 1
tagged with: opencv
score: 1
type: Question
tagged with: python-2.7
has body: So I use rawpy.imread to read an .dng image file and made some processes, now I want to save it as a new .dng file. is there any way I can achieve that?
downvote count: 0
favorite count: 0
has title: How to save a processed .dng image to .dng
tagged with: python
has comment: http://stackoverflow.com/comment/89487477
tagged with: computer-vision
answer count: 0

http://stackoverflow.com/comment/89407961
has text: @Brenlla That would work, even with the outer ndarray being 2d. However, I'm a bit concerned about the speed of the double conversion, given that these arrays actually have thousands of elements. It also seems kind of ugly and unfortunate. I was really hoping for a numpy method to do this, or an explanation of why the builtins fail. I'd definitely upvote this as an answer though.
type: Comment
comment on: http://stackoverflow.com/q/51211176
score: 0
type: QuestionComment

http://stackoverflow.com/comment/89607233
has text: I should be better about testing these things. Working on it. Thanks again.
comment on: http://stackoverflow.com/a/51315287
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/52806983
downvote count: 0
type: Answer
score: 2
upvote count: 2
has body: pandas version df = pd.DataFrame({ 'Item': ['A', 'B'], 'Date': ['2018-08-03', '2018-08-20'] }) df['Date'] = pd.to_datetime(df.Date) #Use pd.Timestamp df.Date - pd.TimedeltaIndex(df.Date.dt.dayofweek,unit='d') Output: 0 2018-07-30 1 2018-08-20 dtype: datetime64[ns] Docs on used functions: pd.TimedeltaIndex, pd.to_datetime Working with date and time: Time Series / Date functionality
answers question: http://stackoverflow.com/q/51208570

http://stackoverflow.com/a/51169614
type: AcceptedAnswer
has body: The key is 'add', the value is a list containing two arguments -- name and aixbuildhost. To access the values: args['add'][0] - will return 'name' args['add'][1] - will return 'aixbuildhost' See more on how to use and parse dictionaries here.
upvote count: 2
type: Answer
has comment: http://stackoverflow.com/comment/89322565
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/89322363
answers question: http://stackoverflow.com/q/51169541
accepted answer of: http://stackoverflow.com/q/51169541

http://stackoverflow.com/q/51225423
tagged with: python
has title: Python exponentiation speed
has comment: http://stackoverflow.com/comment/89431339
possible better answer: http://stackoverflow.com/a/51225556
type: AnsweredQuestion
has body: Any idea how do I estimate how long this program will take? I have already ran the program for 8 hours and have no idea how much longer I will need to wait. print (9 ** ((9 ** 9) + 9)) I know the answer is huge (I know it will spill out billion of digits). I just want to know how long it will take.
tagged with: performance
has answer: http://stackoverflow.com/a/51228253
has comment: http://stackoverflow.com/comment/89431666
type: Question
upvote count: 2
tagged with: number-theory
linked to: http://stackoverflow.com/q/34936226
has comment: http://stackoverflow.com/comment/89431158
has comment: http://stackoverflow.com/comment/89437256
answer count: 2
has comment: http://stackoverflow.com/comment/89431324
has answer: http://stackoverflow.com/a/51225556
score: 0
has comment: http://stackoverflow.com/comment/89431226
has comment: http://stackoverflow.com/comment/89431369
favorite count: 0
has comment: http://stackoverflow.com/comment/89437030
accepted answer: http://stackoverflow.com/a/51228253
downvote count: 2
has comment: http://stackoverflow.com/comment/89431139

http://stackoverflow.com/q/51322818
tagged with: python-multiprocessing
tagged with: multiprocessing
type: Question
upvote count: 0
has body: I have implemented my program earlier by multiprocessing but now I am using Numba so I want to remove multiprocessing. But, I am having some problem. The part of the program is given here, I am using spyder version 3.2.8 which is using python 2.7. theta = 0 sin_theta = math.sin(math.radians(theta)) Multiprocessing is implemented as follows dataset = [] for i in range(0, 375, 15): for j in range(0, 195, 15): for k in range(0, 375, 15): dataset.append([i, j, k]) agents = 40 chunksize = 4 pool = mp.Pool(processes = agents) result = pool.map(calling, dataset, chunksize) After removing multiprocessing as follows import os dataset = [] for i in range(0, 375, 15): for j in range(0, 195, 15): for k in range(0, 375, 15): dataset.append([i, j, k]) calling(dataset) Calling funtion is def calling(dataset): l1 = dataset[0] l2 = dataset[1] l3 = dataset[2] import random i = random.sample(range(9000), 1) t = 0 f = 0 z = 0 global g_r global g_o g_o_r = grid_one global s_a_r, p_l rt(p_l, l1, l2, l3, i) The rt function is def rt(p, f, t, z, i): import math import cmath sin_t = math.sin(math.radians(t)) sin_f = math.sin(math.radians(f)) sin_z = math.sin(math.radians(z)) cos_t = math.cos(math.radians(t)) cos_f = math.cos(math.radians(f)) cos_z = math.cos(math.radians(z)) The error is sin_t = math.sin(math.radians(t)) TypeError: a float is required Please tell if any further info or data is required.
has answer: http://stackoverflow.com/a/51344097
score: -1
answer count: 1
has title: Why does removing multiprocessing from my program throws an "A float is needed" error in math.sin() function?
favorite count: 0
accepted answer: http://stackoverflow.com/a/51344097
tagged with: python
type: AnsweredQuestion
tagged with: floating-point
downvote count: 1
has comment: http://stackoverflow.com/comment/89621989

http://stackoverflow.com/comment/89484527
type: AnswerComment
has text: @cap the `bin/` folder is for scripts that should be installed with your package. When you run `python setup.py install` your package gets installed to `site-packages` and the contents of `bin` go to `Scripts` folder. When your package is installed, importing it from anywhere will work. If you want the code to work without installing the package with `setup.py` then the script must be in the root folder (where `setup.py` is) and not inside `bin`
type: Comment
comment on: http://stackoverflow.com/a/51251695
score: 0

http://stackoverflow.com/a/51200327
answers question: http://stackoverflow.com/q/51200111
score: 0
has body: Your immediate problem is that final line in tail is: print(return deque(open(csv_file), n)) I'll bet you had print(deque(open(csv_file), n)) while you were developing and meant to edit it to return(deque(open(csv_file), n)). But there's more wrong here. The tail method is never invoked. As you go further, I think you'll find that everything that uses your csv reader will need to be in side the with statement. Try this as a starter: import csv from collections import deque def tail(csv_file_name, n=13): 'Return the last n lines of a file' with open(csv_file_name, 'r') as csv_file: csv_reader = csv.reader(csv_file) return(deque(csv_reader, n)) last_13 = tail('updated_quotes') print(last_13)
type: Answer
has comment: http://stackoverflow.com/comment/89385487
has comment: http://stackoverflow.com/comment/89383905

http://stackoverflow.com/q/51208937
has comment: http://stackoverflow.com/comment/89398651
has comment: http://stackoverflow.com/comment/89398699
type: Question
has answer: http://stackoverflow.com/a/51209014
has body: My question is pretty similar to this question Python: split line by comma, then by space But what I need is one step ahead. My list actually looks like this name,phone,monthlysalary,age Peter,1234567,100000,28 John,22345,200000,30 Mary,32345,300000,40 If I break the list using:- Source="""name,phone,monthlysalary,age Peter,1234567,100000,28 John,22345,200000,30 Mary,32345,300000,40""" x = [elem.split(",") for elem in Source.split("\n")] Then I can get the result as:- [['name', 'phone', 'monthlysalary', 'age'], ['Peter', '1234567', '100000', '28'], ['John', '22345', '200000', '30'], ['Mary', '32345', '300000', '40']] But what I need is:- {'Peter': ['1234567', '100000', '28'], 'John': ['22345', '200000', '30'], 'Mary': ['32345', '300000', '40']} Instead of a list of list, I would like to: ignore the header line (name, phone, monthlysalary, age) get the result as a dict of list so that I can use the key name to locate their details It would be great if I can do it in a single line of statement but this is kind of cosmetic Of coz I can easily write a simple code as below to achieve this:- Source="""name,phone,monthlysalary,age Peter,1234567,100000,28 John,22345,200000,30 Mary,32345,300000,40""" x = dict() _, *lines = Source.split("\n") for line in lines: head, *tail = line.split(',') x[head] = tail But instead I would like to know is it possible to achieve this using one liner?
has comment: http://stackoverflow.com/comment/89463318
answer count: 2
has comment: http://stackoverflow.com/comment/89463439
has answer: http://stackoverflow.com/a/51242667
linked to: http://stackoverflow.com/q/30112951
has comment: http://stackoverflow.com/comment/89463430
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89463423
tagged with: python
downvote count: 4
has comment: http://stackoverflow.com/comment/89399332
upvote count: 0
has title: Python Split by line by comma into maps of list
score: -4
has comment: http://stackoverflow.com/comment/89398667

http://stackoverflow.com/a/51229477
upvote count: 2
has comment: http://stackoverflow.com/comment/89438752
has comment: http://stackoverflow.com/comment/89438880
downvote count: 0
answers question: http://stackoverflow.com/q/51229422
type: Answer
has body: From the docs, we see int() does not modify the item passed to it (like, for instance, list.insert) because a new integer object is returned. Return an integer object constructed from a number or string x, or return 0 if no arguments are given. The reason for this is that integers, strings, tuples and other types are immutable so cannot be modified - instead a new instance must be made. On the other hand lists, sets and other types are mutable so their values can be changed which is why they have methods which don't return the modified list, but instead modify it in place.
score: 2

http://stackoverflow.com/comment/89531330
score: 1
comment on: http://stackoverflow.com/q/51276796
type: QuestionComment
type: Comment
has text: Your code is invalid python syntax

http://stackoverflow.com/comment/89343129
type: AnswerComment
score: 0
has text: if you really want list comprehension, you have to add square brackets. Otherwise you can't make a list comprehension. @MohammedKashif
type: Comment
comment on: http://stackoverflow.com/a/51180341

http://stackoverflow.com/a/51264761
score: 1
has comment: http://stackoverflow.com/comment/89566381
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89566715
has body: The canvas vanishes because that's the behavior of pack -- it will cause a widget to grow or shrink to fit its children. The button is a child of the canvas, so the canvas tries to shrink to fit the canvas. This solution is wrong in many ways, For example, to add a widget to a canvas you shouldn't use pack, place, or grid. Instead, you should use the canvas method create_window. However, you don't need a button inside the oval at all. You can create a binding that will call a function whenever the user clicks directly on the oval. For example, the following will cause the function showInfo to be called whenever the oval is clicked: def showInfo(event): print("you clicked on the oval") main_canvas.tag_bind(oval, "&lt;1&gt;", showInfo) HOWEVER, this won't work very well because of how you're doing your animation loop. Your code is sleeping more than anything else, which makes it very hard for tkinter to process events. Tkinter cannot process events while sleep is sleeping. Instead of using a for loop, you need to write a function that does everything that you are doing inside the loop (ie: it draws one frame of animation). This function can use after to call itself again in the future, setting up a perpetual loop. For example: def doOneIteration(): newx = random.randint(10, 190) newy = random.randint(10, 190) main_canvas.coords(oval, newx, newy, newx+20, newy+20) now = str(time.ctime()) label_f2_2.configure(text=now[10:]) label_f2_1.configure(text=now[0:10]) main.after(1000, doOneIteration) doOneIteration() The first time you call doOneIteration, it will do everything that was in the body of loop. Then, when it's finished it will cause itself to be called again in one second. The next time it's called, it will do the work and then again cause itself to be called in one second. It will do this for as long as the program runs. The advantage here is that at no time are you causing the program to go to sleep. This insures that tkinter is able to process a steady stream of…
type: Answer
answers question: http://stackoverflow.com/q/51251675
accepted answer of: http://stackoverflow.com/q/51251675
downvote count: 0
has comment: http://stackoverflow.com/comment/89566416

http://stackoverflow.com/q/51191158
tagged with: mergesort
tagged with: sorting
tagged with: data-structures
has title: Merge Sort in Python - RuntimeError: maximum recursion depth exceeded
answer count: 3
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/51193510
type: UnansweredQuestion
tagged with: python
score: 1
has answer: http://stackoverflow.com/a/51191382
upvote count: 1
has body: I am working on merge sort in Python. I have checked merge function. The arrays are merging fine. But in the mergeSort Function an error is coming :--- RuntimeError: maximum recursion depth exceeded. RuntimeError Traceback (most recent call last) in () 63 print(arr[i]), 64 ---> 65 mergeSort(arr,0,n-1) 66 print(" ") 67 print("Sorted Array is") in mergeSort(arr, l, r) 53 m = l+(r-1)/2 54 mergeSort(arr,l,m) ---> 55 mergeSort(arr,m+1,r) 56 merge(arr,l,m,r) 57 What can be the possible cause of this? def merge(arr,l,m,r): n1 = m-l+1 n2 = r-m L = [0] * n1 R = [0] * n2 print("First List") for i in range(0,n1): L[i] = arr[i+l] print(L[i]), print("") print("Second List") for j in range(0,n2): R[j] = arr[j+m+1] print(R[j]), #Merging the temp arrays i = 0 j = 0 k = 0 print("") print("Merged List ----------&gt;") while i &lt; n1 and j &lt; n2: if L[i] &lt;= R[j]: arr[k] = L[i] print(arr[k]), i+=1 else: arr[k] = R[j] print(arr[k]), j+=1 k+=1 while i&lt;n1: arr[k] = L[i] i+=1 k+=1 while j&lt;n2: arr[k] = R[j] print(arr[k]) j+=1 k+=1 def mergeSort(arr,l,r): if l&lt;r: m = l+(r-1)/2 mergeSort(arr,l,m) mergeSort(arr,m+1,r) merge(arr,l,m,r) arr = [0,12,13,0,1,22] n = len(arr) mergeSort(arr,0,n-1) print(" ") print("Sorted Array is") for i in range(0,n-1): print(arr[i])
has answer: http://stackoverflow.com/a/51191371
type: Question
tagged with: algorithm

http://stackoverflow.com/q/51241604
type: UnansweredQuestion
score: 0
has body: i just built an android app using python kivy/buildozer. The app crashes after i input my latitude and longitude and click the 'get conditions' button. here is the python/kivy code... the app works as intended on my laptop. just fyi... if your going to test this use latitude 37 and longitude 122.5 as i know the weather.gov api works for these. from kivy.app import App from kivy.uix.scatter import Scatter from kivy.uix.label import Label from kivy.uix.floatlayout import FloatLayout from kivy.uix.textinput import TextInput from kivy.uix.boxlayout import BoxLayout from kivy.uix.gridlayout import GridLayout from kivy.uix.button import Button import requests class BasicApp(App): def build(self): self.title = 'SurfsApp!' layout = BoxLayout(orientation = 'vertical') label1 = Label(text = 'SURFS APP!',size_hint = (1,.3), color = (0,0,1,1)) btn1 = Button(text = 'Todays Conditions', size_hint = (1,.3)) label2 = Label(text = 'Enter your latitude below',size_hint=(1,.1)) label3 = Label(text = 'Enter your longitude below',size_hint=(1,.1)) self.lon1 = str(122.5) self.lat1 = str(37) layout.add_widget(label1) layout.add_widget(label2) layout.add_widget(label3) layout.add_widget(btn1) def getconditions(*args,**kwargs): i = 0 north = self.lat1 west = self.lon1 gps= str(north) +','+ '-' + str(west) url = 'https://api.weather.gov/points/'+ str(gps) headers = {'Token': 'tArcrKZYxRTCWPvhTcdBqyydHZnxLCJB'} response = requests.get(url) data = response.json() # print(data['properties']['forecastGridData']) url = data['properties']['forecastGridData'] response = requests.get(url, headers = headers) data = response.json() forecast = {'windSpeed': "{0:.1f}".format(data['properties']['windSpeed']['values'][i]['value'] * 1.94384), 'windDirection': data['properties']['windDirection']['values'][i]['value'], 'primarySwellDirection': data['properties']['primarySwellDirection']['values'][i]['value'], 'primarySwellHeight': int(data['properties']['primarySwellHeight']['values'][i]['value'] * 3.28084),…
upvote count: 1
has title: python kivy android app crashes after api request
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/51247449
tagged with: buildozer
answer count: 1
has comment: http://stackoverflow.com/comment/89462810
favorite count: 0
tagged with: android
tagged with: python
tagged with: kivy
has comment: http://stackoverflow.com/comment/89461986
has comment: http://stackoverflow.com/comment/89525060
has comment: http://stackoverflow.com/comment/89487983

http://stackoverflow.com/a/51206116
score: 0
has body: You can use PIL package to manage images. Here's example how it can be done. from PIL import Image image = Image.open('sample.png') width, height = image.size pixels = image.load() # Check if has alpha, to avoid "too many values to unpack" error has_alpha = len(pixels[0,0]) == 4 # Create empty 2D list fill = 1 array = [[fill for x in range(width)] for y in range(height)] for y in range(height): for x in range(width): if has_alpha: r, g, b, a = pixels[x,y] else: r, g, b = pixels[x,y] lum = 255-((r+g+b)/3) # Reversed luminosity array[y][x] = lum/255 # Map values from range 0-255 to 0-1 I think it works but please note that the only test I did was if values are in desired range: # Test max and min values h, l = 0,1 for row in array: h = max([max(row), h]) l = min([min(row), l]) print(h, l)
has comment: http://stackoverflow.com/comment/89400726
type: Answer
answers question: http://stackoverflow.com/q/51205502

http://stackoverflow.com/comment/89389688
has text: Thanks, your answer makes a lot of sense! Is it correct to assume that when an exception is raised, everything that comes after the continue statement (line 6 - 9) are "skipped" for this loop and it directly jumps into the next one? I don't want the lists to be filled for this instance. Also, I get a `undefined name 'Invalid Argument'` warning for the code. How do I get around this?
type: AnswerComment
comment on: http://stackoverflow.com/a/51199723
score: 0
type: Comment

http://stackoverflow.com/comment/89448159
comment on: http://stackoverflow.com/q/51234440
has text: Without knowing the structure of plot_data, there is little one can say, I guess. Basically, you have to create [a Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve).
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51289337
score: 0
type: Question
has comment: http://stackoverflow.com/comment/89556661
accepted answer: http://stackoverflow.com/a/51291746
has title: Django url parameter error
has comment: http://stackoverflow.com/comment/89556566
answer count: 1
has body: Here is my problem : Using the URLconf defined in Rase.urls, Django tried these URL patterns, in this order: admin/ [name='index'] bio/&lt;slug:username&gt;/$ [name='bio'] The current path, bio/bussiere/, didn't match any of these. the url is : http://localhost:8000/bio/bussiere/ here is my url file : from django.urls import include, path from . import views urlpatterns = [ path('', views.index, name='index'), path("bio/&lt;slug:username&gt;/$", views.bio, name='bio'), ] If you have any idea ? Thanks and regards
has answer: http://stackoverflow.com/a/51291746
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/89556701
has comment: http://stackoverflow.com/comment/89556688
type: AnsweredQuestion

http://stackoverflow.com/comment/89368044
comment on: http://stackoverflow.com/q/51185555
type: Comment
score: 1
type: QuestionComment
has text: To avoid needing tkinter, choose the Qt5 backend for Matplotlib before you import `matplotlib.pyplot`. More info here: https://matplotlib.org/faq/usage_faq.html#what-is-a-backend

http://stackoverflow.com/a/51185182
type: Answer
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/51185045
upvote count: 1
has body: A possible solution: while True: age_input = input("Please enter your age in years: ") # Check both if the string is an integer, and if the age is below 200. if age_input.isdigit() and int(age_input) &lt; 200: print("Your age is {}".format(age_input)) break # If reach here, it means that the above if statement evaluated to False. print ("That's not a valid Number.\nPlease try Again.") You don't need to do exception handling in this case. isdigit() is a method of a String object that tells you if the given String contains only digits.

http://stackoverflow.com/comment/89603511
type: AnswerComment
score: 0
type: Comment
has text: @LucasCioffi your `alert` may look like a new window but in fact is just another new element created in the same page.
comment on: http://stackoverflow.com/a/51313296

http://stackoverflow.com/a/51180406
answers question: http://stackoverflow.com/q/51180348
has comment: http://stackoverflow.com/comment/89382898
score: 4
type: Answer
has body: Let's try: df.set_index(['year','julian','hour']).rolling(5, axis=1).sum().max(1)
upvote count: 4
has comment: http://stackoverflow.com/comment/89382203
downvote count: 0
has comment: http://stackoverflow.com/comment/89383797

http://stackoverflow.com/q/51174655
type: UnansweredQuestion
has title: Easy_install or pip install error : [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:579)]
tagged with: pip
score: 1
type: Question
upvote count: 1
answer count: 1
has body: On my centos server, all of sudden I received SSL verify failed message whenever trying to install the new package. Can someone help me on this ? On New Machine: easy_install-2.7 pip Searching for pip Reading https://pypi.python.org/simple/pip/ Best match: pip 10.0.1 Downloading https://files.pythonhosted.org/packages/ae/e8/2340d46ecadb1692a1e455f13f75e596d4eab3d11a57446f08259dee8f02/pip-10.0.1.tar.gz#sha256=f2bd08e0cd1b06e10218feaf6fef299f473ba706582eb3bd9d52203fdbd7ee68 error: Download error for https://files.pythonhosted.org/packages/ae/e8/2340d46ecadb1692a1e455f13f75e596d4eab3d11a57446f08259dee8f02/pip-10.0.1.tar.gz#sha256=f2bd08e0cd1b06e10218feaf6fef299f473ba706582eb3bd9d52203fdbd7ee68: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:579) Existing server where I installed lots of python modules using pip earlier, but now I receiving ssl verification error # pip install certifi Collecting certifi Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLError(1, u'[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:579)'),)': /packages/7c/e6/92ad559b7192d846975fc916b65f667c7b8c3a32bea7372340bfe9a15fa5/certifi-2018.4.16-py2.py3-none-any.whl Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLError(1, u'[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:579)'),)': /packages/7c/e6/92ad559b7192d846975fc916b65f667c7b8c3a32bea7372340bfe9a15fa5/certifi-2018.4.16-py2.py3-none-any.whl Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLError(1, u'[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:579)'),)': /packages/7c/e6/92ad559b7192d846975fc916b65f667c7b8c3a32bea7372340bfe9a15fa5/certifi-2018.4.16-py2.py3-none-any.whl Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection…
favorite count: 0
has answer: http://stackoverflow.com/a/54099357
tagged with: python
tagged with: easy-install
downvote count: 0

http://stackoverflow.com/comment/89479977
comment on: http://stackoverflow.com/a/51250362
type: Comment
has text: if we want to iter the content we have to use a loop
type: AnswerComment
score: 0

http://stackoverflow.com/comment/89490986
comment on: http://stackoverflow.com/a/51255720
score: 0
type: AnswerComment
has text: because i just tried this and unfortunately it's still not working : /
type: Comment

http://stackoverflow.com/q/51204017
has answer: http://stackoverflow.com/a/51204131
tagged with: python
tagged with: list
has title: Sorting list based on Search Query
type: Question
has body: I have a list of strings and I have to sort it based on some search string. My Search String is Home Depot MyList = ['Depot Home','Rollins Home Furniture','HomeDepot 1346','Home Depot'] Expected Output: Sorted list: ['HomeDepot 1346','Home Depot','Depot Home','Rollins Home Furniture'] In the sorted list first element is exact match of search string removing spaces, Second is also exact Match with space and 3rd element is partial Match of Depot(in alphabetical order) and 4th element is also a partial match for Home (alphabetical order so placed after Depot) What I did so far: searchquery_startswith=[w for w in Mylist if w.startswith('HOME DEPOT'.strip())] searchquery_substring= [w for w in Mylist if ('HOME DEPOT' in w and w not in searchquery_startswith)] I know I can do something like this but I'm looking for more pythonic way to achieve this. All help appreciated
tagged with: sorting
score: 0
answer count: 1
tagged with: python-3.x
type: UnansweredQuestion

http://stackoverflow.com/q/51272746
has title: How to install and use mmlspark on a local machine with Conda Python?
has comment: http://stackoverflow.com/comment/89528932
favorite count: 0
downvote count: 2
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51277035
has body: How to install and use MMLSpark on a local machine with Intel Python 3.6? import numpy as np import pandas as pd import pyspark spark = pyspark.sql.SparkSession.builder.appName("MyApp") \ .config("spark.jars.packages", "Azure:mmlspark:0.13") \ .getOrCreate() import mmlspark from mmlspark import TrainClassifier from pyspark.ml.classification import LogisticRegression from mmlspark import ComputeModelStatistics, TrainedClassifierModel dataFilePath = "AdultCensusIncome.csv" import os, urllib if not os.path.isfile(dataFilePath): urllib.request.urlretrieve("https://mmlspark.azureedge.net/datasets/" + dataFilePath, dataFilePath) data = spark.createDataFrame(pd.read_csv(dataFilePath, dtype={" hours-per-week": np.float64})) data = data.select([" education", " marital-status", " hours-per-week", " income"]) train, test = data.randomSplit([0.75, 0.25], seed=123) train.limit(10).toPandas() model = TrainClassifier(model=LogisticRegression(), labelCol=" income", numFeatures=256).fit(train) prediction = model.transform(test) metrics = ComputeModelStatistics().transform(prediction) metrics.limit(10).toPandas() MMLSpark does not work. Could someone help with this issue?
type: Question
answer count: 2
upvote count: 0
score: -2
tagged with: pyspark
tagged with: azure-machine-learning-service
possible better answer: http://stackoverflow.com/a/66186556
tagged with: conda
accepted answer: http://stackoverflow.com/a/51277035
has answer: http://stackoverflow.com/a/66186556

http://stackoverflow.com/q/51232692
tagged with: python
score: 1
favorite count: 0
type: UnansweredQuestion
upvote count: 1
has body: I have recently started learning programming and I'm trying to use what I am learning. What I am trying to do: I am trying to write a program that will pick positive numbers from a list and add them to an empty list. The code I wrote: lst = [5, 4, 3, 1, -2, -3, -5] lst2 = [] for i in lst: if i &gt; 0: lst2=lst2.append[i] if i &lt;= 0: break print(lst2) This is my first piece of code, and I would appreciate any form of response. Thank you!
has answer: http://stackoverflow.com/a/51232787
type: Question
has title: Adding to a list in a loop
downvote count: 0
has comment: http://stackoverflow.com/comment/89444498
has comment: http://stackoverflow.com/comment/89444542
answer count: 1

http://stackoverflow.com/a/51177328
score: 0
has body: your xpath looks almost fine, maybe you forgot a dot? bucket_names = tree.xpath(".//span[@class='price']/text()")
answers question: http://stackoverflow.com/q/51177166
type: Answer
has comment: http://stackoverflow.com/comment/89337417
has comment: http://stackoverflow.com/comment/89337291

http://stackoverflow.com/comment/89401327
has text: what is your optimizers and learnig rate? Have you tried lowering your learning rate?
comment on: http://stackoverflow.com/q/51210210
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89553969
score: 0
has text: Take a look at [this question](https://stackoverflow.com/questions/2837214/python-popen-command-wait-until-the-command-is-finished), the problem is not in the multiprocessing, but that you use `Popen` which does not wait for completion by default
type: QuestionComment
comment on: http://stackoverflow.com/q/51287943
type: Comment

http://stackoverflow.com/q/51240287
tagged with: python
score: 2
type: AnsweredQuestion
upvote count: 3
has comment: http://stackoverflow.com/comment/89460104
has body: I need to create a system where the user have to change his password every "x" number of days. I managed to achieve this by saving a UTC timestamp representing the time when the user has created/modified his password. My question is, instead of saving the timestamp in the database, is it possible to get a timestamp representing the time when the field has been changed through some of django's built-in functions? This way I could access when was the last time the user has updated his password without having to add a dedicated field in the model to save the timestamp in it.
downvote count: 1
type: Question
has title: Accessing the time where a field has been updated (Django models)
has answer: http://stackoverflow.com/a/51242471
tagged with: django-models
has comment: http://stackoverflow.com/comment/89459453
answer count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/51242471
tagged with: django

macos
tags question: http://stackoverflow.com/q/51322536
tags question: http://stackoverflow.com/q/51284472
tags question: http://stackoverflow.com/q/51255533
tags question: http://stackoverflow.com/q/51249423
tags question: http://stackoverflow.com/q/51217030
tags question: http://stackoverflow.com/q/51182470
tags question: http://stackoverflow.com/q/51235637
tags question: http://stackoverflow.com/q/51275323
tags question: http://stackoverflow.com/q/51299321
tags question: http://stackoverflow.com/q/51183022
tags question: http://stackoverflow.com/q/51201519
tags question: http://stackoverflow.com/q/51319551
tags question: http://stackoverflow.com/q/51225153
type: Tag
tag name: macos
tags question: http://stackoverflow.com/q/51219293

http://stackoverflow.com/a/51213767
has body: The problem was that I was using relative imports in the test module (from ..utils import guards). I just changed it to absolute import (from app.utils import guards) and it all worked again.
has comment: http://stackoverflow.com/comment/112013293
type: Answer
has comment: http://stackoverflow.com/comment/139737931
upvote count: 14
has comment: http://stackoverflow.com/comment/101174828
score: 13
downvote count: 1
accepted answer of: http://stackoverflow.com/q/51198860
has comment: http://stackoverflow.com/comment/95217455
has comment: http://stackoverflow.com/comment/95611185
answers question: http://stackoverflow.com/q/51198860
has comment: http://stackoverflow.com/comment/117299650
has comment: http://stackoverflow.com/comment/113612730
type: AcceptedAnswer

http://stackoverflow.com/q/51239527
has body: first I define a function c1() in a file called CT.py as below def c1(): result = 1 return result so now if I type the following code in python console from CT import c1 then run c1(), it will give a value of 1 however, if now I change CT.py as below (change declaration of c1) and save it def c1(): result = 100 return result now if I type the following code in python console from CT import c1 and run c1(), why do I still get a value of 1? Why won't it import the new c1 function whose resulting value should be 100? To get the new c1 function, it seems that I have to close the python console (or pycharm) and run the code again. Is there a way to reload the function without rerun the python console in pycharm? Thank you in advance!
upvote count: 2
has comment: http://stackoverflow.com/comment/89458230
answer count: 1
tagged with: console
favorite count: 0
linked to: http://stackoverflow.com/q/48038180
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51239647
tagged with: python
score: 2
tagged with: pycharm
downvote count: 0
type: Question
has title: how to reload updated function in python console in pycharm

http://stackoverflow.com/comment/89486002
score: 0
has text: What is os.getenv doing here ?
type: Comment
comment on: http://stackoverflow.com/a/51253193
type: AnswerComment

http://stackoverflow.com/comment/89981973
type: Comment
type: QuestionComment
has text: This is far from being perfect or "ready-to-use", but in my [codegen project](https://github.com/axkr/java_codegen) you can create a preprocessor, which can use [Symja](https://github.com/axkr/symja_android_library) to parse the math expressions. For converters search for `JavaForm`, `TeXForm` or `MathMLForm` in the [doc/functions](https://github.com/axkr/symja_android_library/tree/master/symja_android_library/doc/functions) folder.
comment on: http://stackoverflow.com/q/51285909
score: 0

http://stackoverflow.com/a/51170956
answers question: http://stackoverflow.com/q/51170871
has body: Try wrapping your r = requests.get("https://www.scoopwhoop.com/subreddit-nature/#.lce3tjfci") in a try: or while: statement to make sure that the website you are scraping is returning a 200 response, it could be that the website is timing out or not serving your request.
type: Answer
score: 0

arrays
tags question: http://stackoverflow.com/q/51231925
tags question: http://stackoverflow.com/q/51271225
tags question: http://stackoverflow.com/q/51208733
tags question: http://stackoverflow.com/q/51245909
tags question: http://stackoverflow.com/q/51302673
type: Tag
tags question: http://stackoverflow.com/q/51313328
tags question: http://stackoverflow.com/q/51286071
tags question: http://stackoverflow.com/q/51323682
tags question: http://stackoverflow.com/q/51219117
tags question: http://stackoverflow.com/q/51187122
tags question: http://stackoverflow.com/q/51264102
tags question: http://stackoverflow.com/q/51255828
tags question: http://stackoverflow.com/q/51236891
tags question: http://stackoverflow.com/q/51190740
tags question: http://stackoverflow.com/q/51250169
tags question: http://stackoverflow.com/q/51256637
tags question: http://stackoverflow.com/q/51293795
tags question: http://stackoverflow.com/q/51227943
tags question: http://stackoverflow.com/q/51293905
tags question: http://stackoverflow.com/q/51268802
tags question: http://stackoverflow.com/q/51294880
tags question: http://stackoverflow.com/q/51177843
tags question: http://stackoverflow.com/q/51300281
tags question: http://stackoverflow.com/q/51272270
tags question: http://stackoverflow.com/q/51188406
tags question: http://stackoverflow.com/q/51324166
tags question: http://stackoverflow.com/q/51316115
tags question: http://stackoverflow.com/q/51175427
tags question: http://stackoverflow.com/q/51292589
tags question: http://stackoverflow.com/q/51253586
tags question: http://stackoverflow.com/q/51252009
tags question: http://stackoverflow.com/q/51248527
tags question: http://stackoverflow.com/q/51191731
tags question: http://stackoverflow.com/q/51200369
tags question: http://stackoverflow.com/q/51195958
tags question: http://stackoverflow.com/q/51299478
tags question: http://stackoverflow.com/q/51292553
tags question: http://stackoverflow.com/q/51190182
tags question: http://stackoverflow.com/q/51223268
tags question: http://stackoverflow.com/q/51252962
tags question: http://stackoverflow.com/q/51213923
tags question: http://stackoverflow.com/q/51276108
tags question: http://stackoverflow.com/q/51319692
tags question: http://stackoverflow.com/q/51284192
tags question: http://stackoverflow.com/q/51235622
tags question: http://stackoverflow.com/q/51176843
tags question: http://stackoverflow.com/q/51207005
tags question: http://stackoverflow.com/q/51316220
tag name: arrays
tags question: http://stackoverflow.com/q/51279973
tags question: http://stackoverflow.com/q/51204370
tags question: http://stackoverflow.com/q/51198333
tags question: http://stackoverflow.com/q/51251308
tags question: http://stackoverflow.com/q/51192207
tags question: http://stackoverflow.com/q/51237710
tags question: http://stackoverflow.com/q/51285593
tags question: http://stackoverflow.com/q/51229817
tags question: http://stackoverflow.com/q/51170561
tags question: http://stackoverflow.com/q/51170737
tags question: http://stackoverflow.com/q/51225136
tags question: http://stackoverflow.com/q/51289268
tags question: http://stackoverflow.com/q/51205824
tags question: http://stackoverflow.com/q/51236510
tags question: http://stackoverflow.com/q/51290791
tags question: http://stackoverflow.com/q/51318839
tags question: http://stackoverflow.com/q/51294386
tags question: http://stackoverflow.com/q/51269242
tags question: http://stackoverflow.com/q/51272894
tags question: http://stackoverflow.com/q/51314628
tags question: http://stackoverflow.com/q/51181193
tags question: http://stackoverflow.com/q/51191502
tags question: http://stackoverflow.com/q/51242638
tags question: http://stackoverflow.com/q/51240812
tags question: http://stackoverflow.com/q/51226866
tags question: http://stackoverflow.com/q/51310903
tags question: http://stackoverflow.com/q/51251851
tags question: http://stackoverflow.com/q/51229187
tags question: http://stackoverflow.com/q/51226334
tags question: http://stackoverflow.com/q/51213451

http://stackoverflow.com/comment/89519053
type: QuestionComment
has text: what is `calendar` that you're importing? if this is in fact another file, please post the contents in your question.
score: 2
comment on: http://stackoverflow.com/q/51270441
type: Comment

http://stackoverflow.com/q/51246704
type: Question
has answer: http://stackoverflow.com/a/51249858
upvote count: 2
tagged with: numpy
has body: I'm trying to figure out, why the following code does not work: import numpy as np failList = [[[1], [2]], [[3, 4, 5, 6], [7]], [[8], [9]], [[10], [11, 12]], [[13], [14, 15, 16]]] goodList = [[[1], [2], [3, 4, 5, 6], [7], [8]], [[9], [10], [11, 12], [13], [14, 15, 16]]] goodList2 = [[[1], [2], [3, 4, 5, 6], [7], [8]], [[9], [10], [11, 12], [13], [14, 15, 16]], [[9], [10], [11, 12], [13], [14, 15, 16]]] myLists = [failList, goodList, goodList] for l in myLists: print([len(l[i]) for i in range(len(l))]) print([len(l[i][j]) for i in range(len(l)) for j in range(len(l[i]))]) try: np.concatenate(l) print("worked") except: print("failed") The output is: [2, 2, 2, 2, 2] [1, 1, 4, 1, 1, 1, 1, 2, 1, 3] failed [5, 5] [1, 1, 4, 1, 1, 1, 1, 2, 1, 3] worked [5, 5, 5] [1, 1, 4, 1, 1, 1, 1, 2, 1, 3, 1, 1, 2, 1, 3] worked Can someone explain, why the first list can't be concatenated but the others can?
has title: How does numpy.concatenate work on lists
answer count: 3
tagged with: concatenation
favorite count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51246806
tagged with: python
has answer: http://stackoverflow.com/a/51247760
has comment: http://stackoverflow.com/comment/89474050
score: 2
tagged with: list
downvote count: 0

http://stackoverflow.com/comment/89386336
has text: Thanks for your comment. Are you saying I need to implement a GET function in the Flask file?
type: AnswerComment
comment on: http://stackoverflow.com/a/51202448
score: 0
type: Comment

http://stackoverflow.com/comment/89782147
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/51325816
has text: Did this meet your needs?
score: 0

http://stackoverflow.com/q/51210090
has title: How to return same data frame in 'for loop' after passing some function on it, without appending etc.?
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/1373164
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/89400745
score: 3
tagged with: list
has answer: http://stackoverflow.com/a/51210559
type: Question
answer count: 2
downvote count: 0
tagged with: dataframe
upvote count: 3
has body: I have three dataframes that I would like to crop, I have defined a function; def croping(data, start_date='2017-04-10 00:00:00', end_date='2018-05-31 21:55:00' ): return data.loc[start_date:end_date] I know this is a bit extra but I am trying to learn how to use user-defined functions. I then want to use this function on the list of dataframes; df_list = [df1, df2, df3] where df1= Timestamp A B C D E 2017-04-01 00:00:00 106.46451 98.94002 118.59085 100.83779 108.89098 2017-04-01 00:05:00 105.74346 98.93000 113.47805 86.77218 105.37943 2017-04-01 00:10:00 105.99000 99.15727 115.48461 96.76406 106.55555 2017-04-01 00:15:00 105.04311 98.93000 112.15814 88.38959 104.71931 ... ... ... ... ... etc. I am then trying to run a for loop to crop each dataframe for name in df_list: holding = croping(name) if I do it this way I need to then append the holding dataframes together, is there a way that I can call the cropped dataframe a different thing in each iteration? Something like this; for name in df_list: name_cropped = croping(name) where name changes in each iteration, so I am left with df1_cropped, df2_cropped etc. Maybe the best way to do this is not with a for loop, I am still very much learning
tagged with: pandas
has answer: http://stackoverflow.com/a/51210353
duplicate of: http://stackoverflow.com/q/1373164
favorite count: 0

http://stackoverflow.com/comment/89562504
type: Comment
score: 0
comment on: http://stackoverflow.com/q/51292195
has text: I suspect you want to use sendAll vs send, but I'm shaky on python sockets. See https://stackoverflow.com/questions/34252273/what-is-the-difference-between-socket-send-and-socket-sendall
type: QuestionComment

http://stackoverflow.com/q/51190678
has body: How to import file from parent directory in python? My project tree is as follows: From __main__.py file which is in vehiclesListCrawler I want to import common.py which is in a parent directory. Now I do it as follows: from common import get_init_url, create_urls_to_fetch, MILEAGE_RANGES, notify_on_error But I'm getting an error: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/runpy.py", line 193, in _run_module_as_main "__main__", mod_spec) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/runpy.py", line 85, in _run_code exec(code, run_globals) File "./__main__.py", line 11, in &lt;module&gt; from common import get_init_url, create_urls_to_fetch, MILEAGE_RANGES, notify_on_error ModuleNotFoundError: No module named 'common' Any idea? UPDATE Nothing from here didn't help. That is why I've posted the new question. Inside __main__.pyI have main function as follows: def main(params): try: process.crawl(AutoscoutListSpider, params) process.start() return {"Success ": main_result} except Exception as e: return {"Error ": e, "params ": params} And I run it as follows: main({"make":"Audi", "model":"A3", "mileage":"2500"})
has comment: http://stackoverflow.com/comment/89363097
has title: How to import file from parent directory in python?
type: Question
linked to: http://stackoverflow.com/q/714063
has comment: http://stackoverflow.com/comment/89363037
has comment: http://stackoverflow.com/comment/89366040
has answer: http://stackoverflow.com/a/51190721
has comment: http://stackoverflow.com/comment/89363656
answer count: 1
tagged with: python
linked to: http://stackoverflow.com/q/16981921
has comment: http://stackoverflow.com/comment/89362945
tagged with: python-3.x
linked to: http://stackoverflow.com/q/30669474
type: UnansweredQuestion
score: 0

http://stackoverflow.com/a/51319238
type: Answer
accepted answer of: http://stackoverflow.com/q/51319210
upvote count: 1
answers question: http://stackoverflow.com/q/51319210
has comment: http://stackoverflow.com/comment/89614419
has comment: http://stackoverflow.com/comment/89614594
has comment: http://stackoverflow.com/comment/89614441
has body: You need copy: df_amounts = df.loc[df.text.str.contains(r"(EUR|€)?\d+(EUR|€)?")].copy() df_amounts['text'] = df_amounts.text.str.strip("EUR€") print (df_amounts) text x 1 10 2.2 2 5 3.3 If you modify values in df_amounts later you will find that the modifications do not propagate back to the original data (df), and that Pandas does warning.
type: AcceptedAnswer
downvote count: 0
score: 1

http://stackoverflow.com/a/51182244
type: Answer
has body: You can convert to frozenset and use pd.DataFrame.duplicated. res = df[~df'Name1', 'Name2'.apply(frozenset, axis=1).duplicated()] print(res) Name1 Name2 Value 0 Juan Ale 1 frozenset is necessary instead of set since duplicated uses hashing to check for duplicates. Scales better with columns than rows. For a large number of rows, use @Wen's sort-based algorithm.
upvote count: 23
score: 23
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51182228
answers question: http://stackoverflow.com/q/51182228

http://stackoverflow.com/a/51292836
type: Answer
has body: Use raw string and set file encoding to utf-8 in normal (non-binary mode) mode when opening. For Python 3.6 it will be enough. On Python 2.7 you should use codecs.open('example.csv', 'w', encoding='utf-8') instead of regular open() when dealing with unicode content. Also, csv module on Python 2.7 does not support unicode out of the box, so I suggest switching to unicodecsv or following the guidelines in this answer.
upvote count: 1
answers question: http://stackoverflow.com/q/51216219
score: 1
downvote count: 0

http://stackoverflow.com/q/51235730
tagged with: python
tagged with: xpath
has comment: http://stackoverflow.com/comment/89451102
type: UnansweredQuestion
tagged with: web-scraping
downvote count: 1
has answer: http://stackoverflow.com/a/51242367
score: -1
has title: Why is xpath not scraping certain html (html that appears all green and is at the end of the page)?
type: Question
upvote count: 0
answer count: 1
has body: I am a beginner and I am trying to scrape hockey statistics of players on hockey-reference.com. An example of a player page I am scraping from is https://www.hockey-reference.com/players/a/abdelju01.html. At the very bottom of this page is html that appears in all green, and xpath won't scrape any of it. Specifically, I need the text contained in the fourth tbody tag, because I want to scrape Corsi and Fenwick scores. However, that tbody tag html is in green, and this xpath code: list = player.xpath("//tbody[3]//tr//text()") returns an empty list. This code: player.xpath("//tbody[1]//tr//text()") returns exactly what I need from the second tbody tag, which is html that appears in the normal color coded fashion. What is up with this green html? Is it blocked somehow? Is there any way I can scrape it?
favorite count: 0
tagged with: http://stackoverflow.com/tag/html

slice
tags question: http://stackoverflow.com/q/51273726
tags question: http://stackoverflow.com/q/51253061
tags question: http://stackoverflow.com/q/51250210
tags question: http://stackoverflow.com/q/51186450
tags question: http://stackoverflow.com/q/51208399
tags question: http://stackoverflow.com/q/51186586
tags question: http://stackoverflow.com/q/51202238
tags question: http://stackoverflow.com/q/51229187
tags question: http://stackoverflow.com/q/51178925
type: Tag
tags question: http://stackoverflow.com/q/51213428
tags question: http://stackoverflow.com/q/51209749
tags question: http://stackoverflow.com/q/51190480
tag name: slice
tags question: http://stackoverflow.com/q/51301206
tags question: http://stackoverflow.com/q/51295864
tags question: http://stackoverflow.com/q/51243609
tags question: http://stackoverflow.com/q/51178629

http://stackoverflow.com/comment/89657417
comment on: http://stackoverflow.com/a/51331729
type: Comment
score: 1
has text: I've edited my answer on #2. Should remove points that are on the edges as long as both lines it is a part of follow the edge of the image. Working on #1.
type: AnswerComment

http://stackoverflow.com/q/51293352
type: Question
upvote count: 1
has comment: http://stackoverflow.com/comment/89564922
favorite count: 0
tagged with: elasticsearch
tagged with: python
has comment: http://stackoverflow.com/comment/89569660
answer count: 0
downvote count: 0
type: UnansweredQuestion
score: 1
has body: s = Search(using = client, index = . set_index).source(['metadata.Filename'])\ .query('match', Filename=(date)) total = s.count() return total I want to find the total number of instances where '20180511' appears in metadata.Filename in a particular index. This query is returning a higher number of hits than I would have expected. The data format in metadata.Filename is GEOSCATCAT20180507_12+20180511_0900.V01.nc4. My date variable is in the format '20180511'. I think the problem is match queries do the thing with scores, where they might return a hit even if it's not an exact match. I was wondering if you had any insight regarding this issue.
has title: How to return only exact matches in Elasticsearch Python API
tagged with: elasticsearch-dsl

http://stackoverflow.com/comment/89546721
has text: Just two thoughts about your dataframe: I would disadvise to use such a column like your `Calcgroup` as index; an index should provide a unique access to a single row in your dataframe. And then - IMO - `csv_reader` is not a proper name for a pandas dataframe; it would be a good description for the `pd.read_csv` function, but not for its return vale
comment on: http://stackoverflow.com/q/51282465
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51203177
score: 0
answer count: 2
accepted answer: http://stackoverflow.com/a/51203218
has body: I have a file xyz.txt which has some values assigned to different variables like below. abc.def = "Hi how are you" abc.def.ghi = "Hi I am fine" abc.def.ghi.jkl = "What are you doing" abc.def.ghi.Mno = "I am working" I want to write a python generic function which reads the line abc.def.ghi.Mno and changes the string from "I am working" to "I am playing" This function should also be used for other files also. I tried with line.startswith(abc.def.ghi.Mno) but its not working. Below is what I tried. Thanks in advance. def find_replace(new_value, start_str, filename): result = "" with open(filename) as f: for line in f: if line.lower().startswith( start_str ): list = line.split('=') list[1] = new_value + '\n' line = "=".join( list ) result += line f = open(filename, 'wt') f.write(result) f.close() find_replace(new_value = "I am playing", start_str = "abc.def.ghi.Mno", filename=xyz.txt)
has answer: http://stackoverflow.com/a/51203277
tagged with: python
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/51203277
type: Question
has title: python: line.startswith(str) will not work if the file contains the same string in every line
has answer: http://stackoverflow.com/a/51203218

http://stackoverflow.com/q/51319079
tagged with: scrapy
has answer: http://stackoverflow.com/a/53946085
has body: I want to extract organization names and basic details about them from this website .I am using scrapy to extract information.I tried scrapy shell to extract first organization name TENCENT HOLDINGS and have written scrapy command in scrapy shell as response.css('div.flex-no-grow.cb-overflow-ellipsis.identifier-label::text').extract_first() and this command returns nothing.I am a novice in web scrapping.Can anyone please help me in writing the command for it or rectify me where I am getting it wrong ?
type: Question
has comment: http://stackoverflow.com/comment/89615597
has comment: http://stackoverflow.com/comment/89618399
answer count: 1
has comment: http://stackoverflow.com/comment/89618884
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/html
tagged with: python
tagged with: css
has comment: http://stackoverflow.com/comment/89618534
score: 0
has title: Scrapy shell does not return anything
tagged with: web-scraping

http://stackoverflow.com/comment/89583886
comment on: http://stackoverflow.com/q/51303380
has text: Ok, should be a verifiable example right now. :)
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89557069
type: Comment
comment on: http://stackoverflow.com/a/51250399
score: 0
type: AnswerComment
has text: @Scotty1- that's a good point, 30% is a big change in calculation time, I'll have to give that a try and see if it will give me a faster run as my data set is fairly large.

http://stackoverflow.com/comment/89682064
score: 0
has text: @Shash I think you got your answer
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51321730

http://stackoverflow.com/comment/89494623
has text: final_data.to_json('filename.json') this one is working fine. thank you
score: 1
comment on: http://stackoverflow.com/a/51258004
type: AnswerComment
type: Comment

http://stackoverflow.com/q/51312684
score: 3
tagged with: python
upvote count: 3
has title: Pandas dataframe to Redshift psql table
has comment: http://stackoverflow.com/comment/96785489
type: UnansweredQuestion
downvote count: 0
answer count: 0
favorite count: 0
has body: I'm trying to keep inserting data into Redshift table. This method often worked for me: test_df.to_sql('MY_table', engine, index=False, if_exists ='append') As you can see, I have already used 'append' for new insertion. But today redshift kept giving me error saying: ProgrammingError: (psycopg2.ProgrammingError) Relation "MY_table" already exists Do you know why?
type: Question
tagged with: amazon-redshift
tagged with: pandas

http://stackoverflow.com/a/51218618
score: 1
accepted answer of: http://stackoverflow.com/q/51218073
answers question: http://stackoverflow.com/q/51218073
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: keep_aspect_ratio_resizer function resizes the images if any of the two dimensions of those images are out of this min_dimension and max_dimension ranges and it will keep the same aspect ratio what the input image had. If any input image has a dimension, let's say 400 pixel and the other dimension let's say 600, this function will resize the dimensions so that the image's smaller dimension is 600 (according to your mentioned code) and accordingly the larger dimension will be such a value so that the aspect ratio (400/600) of input image is maintained. You can find a nice discussion regarding this here
upvote count: 1

http://stackoverflow.com/q/51295327
linked to: http://stackoverflow.com/q/48268390
accepted answer: http://stackoverflow.com/a/51295531
has comment: http://stackoverflow.com/comment/89595039
has title: Python With Maya Selecting Object and Rotating It
score: 0
answer count: 1
tagged with: maya
tagged with: python-3.x
tagged with: python
has body: So I am working on a very small project, and I need to have an object rotated one or two times per minute, and I need to do it using Python. Does anyone have any suggestions? Thanks so much.
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51295531
linked to: http://stackoverflow.com/q/29446321
type: Question

http://stackoverflow.com/a/51323613
has body: First point, as a general rule, globals are evils - or, more exactly, mutating or worse rebinding globals from within a function should be avoided as much as possible. Second point: in Python, 'global' really means 'module-level' - there's no 'process-level' globals (note that this is a designed choice, based on first point above) Third point: for your general use case (application settings), the 'less evil' ways would be to have all your modules using a settings system so instead of "passing the param to a function that sets it as global so you don't need to pass it around", your modules just import the settings and read the param's value from there (cf django settings for an example). The drawbacks are that 1/ only your own code can use those settings and 2/ it makes your code dependant on those settings (which can sometimes be a PITA). And finally, given the "verbose" name, I assume you want to configure the verbosity level of your program's debugging / error outputs. The proper way to do that in a standard, portable and well decoupled way (which will fix both drawbacks above for this feature) is to use the stdlib's logging package. This package is designed to decouple logger's use (in the 'library' code, using logger.log(level, msg, ...) or one of it's shortcuts) from logging configuration (which is application/installation specific). It requires a bit of learning at first but from experience it's time well spent and actually very quickly saves time.
answers question: http://stackoverflow.com/q/51323272
upvote count: 1
has comment: http://stackoverflow.com/comment/89623736
type: Answer
downvote count: 0
score: 1

http://stackoverflow.com/a/51254924
has comment: http://stackoverflow.com/comment/89489051
score: 1
has comment: http://stackoverflow.com/comment/89489540
upvote count: 1
has comment: http://stackoverflow.com/comment/89493408
has body: DyZ already summarized the issue. You callwd networkx to make you a random graph with 127 nodes, with about 90% of the possible edges drawn in. An average node of this graph will have about 114 edges. Finding a single node that is disconnected enough to be separable is a chance that is astronomically small; finding a cluster of such nodes is even harder. Yes, you can construct graphs with (relatively) thin connections, but at this proportion, any scc algorithm worth its vectorizations will keep the entire graph in one large component. Perhaps some spectral clustering algorithm could identify density and gaps that would get you the sort of division you seem to seek.
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51254686
has comment: http://stackoverflow.com/comment/89489528
answers question: http://stackoverflow.com/q/51254686
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89541407
type: Answer

http://stackoverflow.com/q/51277748
has comment: http://stackoverflow.com/comment/89533800
answer count: 2
downvote count: 0
score: 1
tagged with: keras
has comment: http://stackoverflow.com/comment/89533672
favorite count: 0
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/51278921
has comment: http://stackoverflow.com/comment/89533280
has comment: http://stackoverflow.com/comment/89533834
tagged with: python
has answer: http://stackoverflow.com/a/51278184
has body: I am having an error - 'Tensor' object has no attribute 'log' that I code in Keras to build a network while apply custom loss function to Keras. I think somehow I need to get rid of np.log but not sure how. import Numpy import numpy as np Custom Function def rmsle(y_pred,y_test): return np.sqrt(np.mean((np.log(1+y_pred) - np.log(1+y_test))**2)) My network def base_model(): model = Sequential() model.add(Dense(50, input_dim=X_train.shape[1], init='normal', activation='sigmoid')) model.add(Dropout(0.5)) model.add(Dense(1, init='normal')) sgd = SGD(lr=0.01, momentum=0.8, decay=0.1, nesterov=False) model.compile(loss=rmsle, optimizer = sgd)# )'adam') # return model keras = KerasRegressor(build_fn=base_model, nb_epoch=80, batch_size=1,verbose=1) keras.fit(X_train ,y_train) When i check the error msg in detail, it shows that 424 """ 425 # score_array has ndim &gt;= 2 --&gt; 426 score_array = fn(y_true, y_pred) 427 if mask is not None: 428 # Cast the mask to floatX to avoid float64 upcasting in theano 2 #return np.sqrt(np.mean(np.square( np.log( (np.exp(a)) + 1 ) - np.log((np.exp(b))+1) ))) ----&gt; 4 return np.sqrt(np.mean((np.log(1+y_pred) - np.log(1+y_test))**2)) 2 #return np.sqrt(np.mean(np.square( np.log( (np.exp(a)) + 1 ) - np.log((np.exp(b))+1) )))
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/51278184
tagged with: machine-learning
upvote count: 1
tagged with: tensorflow
type: Question
has title: Keras AttributeError: 'Tensor' object has no attribute 'log'
has answer: http://stackoverflow.com/a/51278921

http://stackoverflow.com/comment/89594159
type: Comment
type: QuestionComment
has text: As I remarked in the question, it is not the only case where there's only one row for a user_id (or a group), and I'm able to group over that row in a smaller dataframe. (Indeed, if I chunk up the dataframe and group over the pieces separately, I can work around the issue entirely).
comment on: http://stackoverflow.com/q/51293520
score: 0

http://stackoverflow.com/q/51218643
has body: I have a promise-based class similar to this: class Promise(): def res(self, returned): #set the value of the instance to the returned value promise = Promise() promise.res("Returned Value") print(promise) &gt;&gt;&gt;"Returned Value" type(promise) &gt;&gt;&gt;str When I resolve the promise, I want the instance of the class to be the resolved value (str, dict, Class...). How can I do this?
linked to: http://stackoverflow.com/q/51218536
answer count: 0
has comment: http://stackoverflow.com/comment/89418907
has comment: http://stackoverflow.com/comment/89418898
downvote count: 1
has comment: http://stackoverflow.com/comment/89418781
has comment: http://stackoverflow.com/comment/89418865
type: Question
has title: Python promise class turn to the resolved value
has comment: http://stackoverflow.com/comment/89419089
score: 1
has comment: http://stackoverflow.com/comment/89418381
has comment: http://stackoverflow.com/comment/89418414
has comment: http://stackoverflow.com/comment/89418486
upvote count: 2
duplicate of: http://stackoverflow.com/q/51218536
has comment: http://stackoverflow.com/comment/89418495
has comment: http://stackoverflow.com/comment/89418436
favorite count: 0
has comment: http://stackoverflow.com/comment/89418696
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/51283416
tagged with: iterable
has answer: http://stackoverflow.com/a/51283476
answer count: 3
has comment: http://stackoverflow.com/comment/89544096
tagged with: datetime
favorite count: 0
has answer: http://stackoverflow.com/a/51283527
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89544238
tagged with: list
score: 1
has answer: http://stackoverflow.com/a/51283431
has title: date time not iterable - error creating a list
upvote count: 1
type: Question
downvote count: 0
has body: I get the following error when I run this code import datetime today = datetime.datetime.now() print(today) lst = [] lst = lst.extend(today) lst = lst.extend(first_ok) lst = lst.extend(second_ok) lst = lst.extend(all_payments) where first_ok and second_ok are numeric variable TypeError: 'datetime.datetime' object is not iterable Why a datetime is not iterable and cannot be placed in list? What to do about it?

http://stackoverflow.com/q/51259521
downvote count: 0
score: 1
has body: In Python, I have a first sting A, I do some replace command for A which changes the length of the string. After all replaces I search for a special pattern in the string I find the place of it. I want to have the index of this substring in my first string A. It is the first index of characters that changed of not and form the final found substring: This is simple example of my work: A = ' abc ' B = A B = B.replace("a", "b") B = B.replace("c", "bb") print(B.find('bbbb')) #my answer is but i don't know the first string that is changed: print(A.find('abc'))
type: Question
has comment: http://stackoverflow.com/comment/89497875
tagged with: string
has comment: http://stackoverflow.com/comment/89497943
upvote count: 1
tagged with: python
has title: Finding the index place of substring in source string of replaced string
favorite count: 0
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89498076
has comment: http://stackoverflow.com/comment/89497502

http://stackoverflow.com/comment/131586452
type: Comment
comment on: http://stackoverflow.com/a/59276490
type: AnswerComment
score: 0
has text: Perfect! Plug and play to control circle size, overlap, colours of venn diagram. It could almost be a package itself. Even the link is still functional. Yet somehow, three years later not accepted, and not a single upvote!!! Thank you Mr Christy!

http://stackoverflow.com/a/51215834
has body: with open("wordDict.txt") as wordFile: for line in wordFile: line = line.strip() + 'a' print(line) You need to get rid of the line break at the end of the line. .strip() gets rid of whitespace at either end of the line.
score: 3
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/51215813
upvote count: 3
answers question: http://stackoverflow.com/q/51215813

http://stackoverflow.com/a/51248995
answers question: http://stackoverflow.com/q/51248911
score: 1
has body: You could use math.isclose to test for closeness to zero, and set the values accordingly: import math value = 0 if math.isclose(value, 0) else value more details in python docs
downvote count: 0
type: AcceptedAnswer
type: Answer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/51248911

http://stackoverflow.com/comment/89575562
comment on: http://stackoverflow.com/q/51299087
has text: @Amadan The docs don't call ranges containers because they call them _sequences_, and all sequences are containers. See [Sequence Types — list, tuple, range](https://docs.python.org/3/library/stdtypes.html#sequence-types-list-tuple-range). `range` is also used as the paradigm example of a "lazy" or "virtual" sequence, which contains all of its elements without having to store them.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89344601
has text: It prints `False`.
type: AnswerComment
comment on: http://stackoverflow.com/a/51180953
score: 0
type: Comment

http://stackoverflow.com/comment/90282813
type: AnswerComment
comment on: http://stackoverflow.com/a/51632205
score: 0
type: Comment
has text: Yes I installed through PyCharm. Did doing that solve it for you and allow and PyCharm to index the modules? It might be due to the new version, since when I posted the answer I was still on 2017. I should note that I have since found an alternative to opencv for what I needed.

http://stackoverflow.com/comment/89607936
comment on: http://stackoverflow.com/a/51315465
has text: ohhhh thank you very much! Ill mess around with the code some more to get it how i would like it. Have an awesome day!!
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/89607005
type: QuestionComment
has text: Done. Also made some minor changes to the column naming.
score: 0
comment on: http://stackoverflow.com/q/51314650
type: Comment

http://stackoverflow.com/a/51197297
type: Answer
answers question: http://stackoverflow.com/q/51197241
has body: You need a exit condition: def is_power(a,b): if a == b: return True elif a % b == 0: a = a/b return is_power(a,b) return False
score: 0

http://stackoverflow.com/q/51253105
answer count: 0
has comment: http://stackoverflow.com/comment/89487167
has body: I want to use Google Calendar API in my Django web app. I successfully got the access token using python social auth. Using that token, I tried calling list calendar API with python requests. Below is my code: import requests token = ... endpoint = "https://content.googleapis.com/calendar/v3/users/me/calendarList" headers = { "Authorization":"Bearer " + token, } requests.get(endpoint,headers=headers).json() However, I got the following response: u'error': u'code': 403, u'message': u'Insufficient Permission', u'errors': u'domain': u'global', u'message': u'Insufficient Permission', u'reason': u'insufficientPermissions' How can this be solved? I really want to solve this problem without using any other libraries including API Client Library.
has comment: http://stackoverflow.com/comment/89485824
type: Question
has comment: http://stackoverflow.com/comment/89486243
has comment: http://stackoverflow.com/comment/89486696
has comment: http://stackoverflow.com/comment/89489686
upvote count: 2
has comment: http://stackoverflow.com/comment/89492529
has comment: http://stackoverflow.com/comment/89486080
favorite count: 0
tagged with: google-api
type: UnansweredQuestion
tagged with: google-calendar-api
tagged with: django
tagged with: python
tagged with: python-social-auth
score: 2
has title: Google Calendar API 403 error
has comment: http://stackoverflow.com/comment/89489639
downvote count: 0

http://stackoverflow.com/comment/89522724
has text: the program itself is hanging. what version of cuda do you have. In my experience, cuda 8 with titan X (pascal) may need to build the cuda hooks for python JIT on the fly resulting in it taking a very long time... minutes... to load the first tensor on the gpu.
type: Comment
score: 1
comment on: http://stackoverflow.com/q/51271817
type: QuestionComment

http://stackoverflow.com/a/51242251
score: 16
has body: Here is a simple solution, to my knowledge there is no built-in function for this in RDKit. def MolFromGraphs(node_list, adjacency_matrix): # create empty editable mol object mol = Chem.RWMol() # add atoms to mol and keep track of index node_to_idx = {} for i in range(len(node_list)): a = Chem.Atom(node_list[i]) molIdx = mol.AddAtom(a) node_to_idx[i] = molIdx # add bonds between adjacent atoms for ix, row in enumerate(adjacency_matrix): for iy, bond in enumerate(row): # only traverse half the matrix if iy &lt;= ix: continue # add relevant bond type (there are many more of these) if bond == 0: continue elif bond == 1: bond_type = Chem.rdchem.BondType.SINGLE mol.AddBond(node_to_idx[ix], node_to_idx[iy], bond_type) elif bond == 2: bond_type = Chem.rdchem.BondType.DOUBLE mol.AddBond(node_to_idx[ix], node_to_idx[iy], bond_type) # Convert RWMol to Mol object mol = mol.GetMol() return mol Chem.MolToSmiles(MolFromGraphs(nodes, a)) Out: 'CC1=NCCC(C)O1' This solution is a simplified version of https://github.com/dakoner/keras-molecules/blob/dbbb790e74e406faa70b13e8be8104d9e938eba2/convert_rdkit_to_networkx.py There are many other atom properties (such as Chirality or Protonation state) and bond types (Triple, Dative...) that may need to be set. It is better to keep track of these explicitly in your graph if possible (as in the link above), but this function can also be extended to incorporate these if required.
downvote count: 0
type: Answer
upvote count: 16
answers question: http://stackoverflow.com/q/51195392

http://stackoverflow.com/q/51320716
tagged with: python-3.x
tagged with: python
tagged with: cmd
has comment: http://stackoverflow.com/comment/89617434
tagged with: subprocess
has comment: http://stackoverflow.com/comment/89617363
upvote count: 1
has comment: http://stackoverflow.com/comment/89617059
has answer: http://stackoverflow.com/a/51321090
type: AnsweredQuestion
has body: I prepared .py script, which i run from command line. ('python test.py') The last task of my script is to launch external application. I use below function to launch independent process (.exe file) subprocess.Popen(["C:/Program Files/Agisoft/PhotoScan Pro/photoscan.exe", (folder_z_nazwa+".psx")], shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE) I would like to close cmd without terminating this subprocess. At this moment Agisoft is launched with cmd in background. When i click exit button on cmd window, agisoft is terminated immediately. I don't expect closing cmd automatically. I just want to avoid situation that user close cmd window accidentally and Agisoft will be closed too.
score: 1
has title: os.subproccess how to avoid closing process after closing cmd
linked to: http://stackoverflow.com/q/1813872
has comment: http://stackoverflow.com/comment/89617466
type: Question
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/51321090
favorite count: 0

http://stackoverflow.com/comment/89548382
type: Comment
has text: That's it! I can't believe I missed the difference on 2.X's signature ^^'. 3.X's `sorted(iterable[, key][, reverse])` is definitely the first thing that comes to mind when thinking of that function...
comment on: http://stackoverflow.com/a/51282318
type: AnswerComment
score: 0

svd
type: Tag
tag name: svd
tags question: http://stackoverflow.com/q/51307345
tags question: http://stackoverflow.com/q/51273038

http://stackoverflow.com/q/51232381
type: UnansweredQuestion
downvote count: 2
has body: I have a directory containing multiple file extensions, and I'd like to grep into a list the paths to all the files with 2 different extensions. So far I've tried: my_files = list(Path(my_dir).glob('**/*.txt' and '**/*.txt.gz')) But with the above script, I get only the paths of the .txt.gz files: [PosixPath('/home/myproject/cd_4/M_1and2.txt.gz')] How can I fix it?
type: Question
score: -2
has answer: http://stackoverflow.com/a/51235810
has comment: http://stackoverflow.com/comment/89443961
answer count: 1
has title: How to grep specific extensions into list python3
favorite count: 0
tagged with: glob
tagged with: python
tagged with: python-3.x
upvote count: 0

http://stackoverflow.com/a/51248782
score: 4
has body: Use json.loads import json s = "[{'id': '439142775754326018', 'channel': '444494690855944212'}, {'id': '426885538918694932', 'channel': '430361953530281984'}, {'id': '430855255383605248', 'channel': '451853323398807552'}, {'id': '368643310203568130', 'channel': '452139548579987476'}, {'id': '440856369944330250', 'channel': '449625381213831188'}, {'id': '434339851446517760', 'channel': '445133299262816266'}, {'id': '428930205793648640', 'channel': '450776641107656715'}, {'id': '316060885229633577', 'channel': '448767987743457290'}, {'id': '437114495027118080', 'channel': '437390161375133696'}, {'id': '451995821257261056', 'channel': '452223587697426442'}, {'id': '359926863885369349', 'channel': '431056330028220416'}, {'id': '422559965312581642', 'channel': '452282513940021261'}, {'id': '437966207782748161', 'channel': '452618004388249601'}, {'id': '451696650080223233', 'channel': '452692771120349206'}, {'id': '369960568913788929', 'channel': '428272365885980673'}, {'id': '151217785807175680', 'channel': '453190112725958656'}, {'id': '389781926661062656', 'channel': '442695145633349648'}, {'id': '451784996789682186', 'channel': '453267557692997642'}, {'id': '441654887043039252', 'channel': '449313164342067201'}, {'id': '420883942993035275', 'channel': '448390553701187585'}, {'id': '453545075524501505', 'channel': '453556398408728596'}, {'id': '364044379813576706', 'channel': '430710266221690890'}, {'id': '436969950167433216', 'channel': '453877346227847172'}, {'id': '452444381157523457', 'channel': '454402297586515998'}, {'id': '429083181963280386', 'channel': '454976869058609163'}, {'id': '341650496244809728', 'channel': '455008952065720320'}, {'id': '366282628707516418', 'channel': '455010915138666526'}, {'id': '455268589768015872', 'channel': '455332655853076480'}, {'id': '412158198586408971', 'channel': '454116567614095360'}, {'id': '284531985207001090', 'channel': '455656462090502145'}, {'id': '447166404626612234', 'channel': '455738112715522048'}]" json.loads(s.…
type: Answer
answers question: http://stackoverflow.com/q/51248718
accepted answer of: http://stackoverflow.com/q/51248718
has comment: http://stackoverflow.com/comment/89476521
upvote count: 4
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/51183773
answers question: http://stackoverflow.com/q/51179649
type: Answer
has comment: http://stackoverflow.com/comment/89352656
has comment: http://stackoverflow.com/comment/89354947
score: 0
has body: Since boxplot is also using the same theory 'inter-quartile range' to detect outliers, you can use it directly to find outliers on your dataframe. import pandas as pd _, bp = pd.DataFrame.boxplot(df2, return_type='both') outliers = [flier.get_ydata() for flier in bp["fliers"]] out_liers = [i.tolist() for i in outliers]

http://stackoverflow.com/q/51211937
score: 1
downvote count: 1
type: Question
has title: Twilio/Flask - store caller's speech to string variable
tagged with: flask
has body: My goal is to pay a simple message on Twilio that can capture the caller's reply. Base on the reply send the caller to next option. My challenge: how do I convert the callers speech into text? Following the examples here's the code to demonstrate this will work: from flask import Flask, request, redirect from twilio.twiml.voice_response import VoiceResponse, Gather, Say from datetime import datetime import time app = Flask(__name__) @app.route("/test1", methods=['GET', 'POST']) def test1(): response = VoiceResponse() gather = Gather(input='speech',timeout=3,hints='cat, numbers, chuck') gather.say('Welcome to the fact hotline. Say cat numbers or chuck') response.append(gather) resp = VoiceResponse() resp.say('you said' + str(response)) print(str(response)) return str(response) if __name__ == "__main__": app.run(debug=True) The result is: <?xml version="1.0" encoding="UTF-8"?> Welcome to the fact hotline. Say cat numbers or chuck If I said "chuck" I would like a variable = "chuck". Can someone offer guidance?
favorite count: 0
has comment: http://stackoverflow.com/comment/89407320
tagged with: twilio
upvote count: 2
type: UnansweredQuestion
tagged with: python
answer count: 0
linked to: http://stackoverflow.com/q/44748229

http://stackoverflow.com/q/51255230
has comment: http://stackoverflow.com/comment/89489541
has comment: http://stackoverflow.com/comment/89489596
has comment: http://stackoverflow.com/comment/89489694
has body: I'm trying to use preg_split to split this text Yes, it was great. [I have no ideas how great it was.] into this array: ['Yes', 'it', 'was', great', '[I have no ideas how great it was.]' But I don't know how...
has comment: http://stackoverflow.com/comment/89490102
answer count: 1
has comment: http://stackoverflow.com/comment/89489623
duplicate of: http://stackoverflow.com/q/19414193
has comment: http://stackoverflow.com/comment/89489478
favorite count: 0
linked to: http://stackoverflow.com/q/19414193
type: UnansweredQuestion
downvote count: 2
tagged with: python
tagged with: php
tagged with: regex
has comment: http://stackoverflow.com/comment/89489397
has comment: http://stackoverflow.com/comment/89489506
has title: Split string with square bracket
has comment: http://stackoverflow.com/comment/89489629
type: Question
has answer: http://stackoverflow.com/a/51255330
has comment: http://stackoverflow.com/comment/89489567
upvote count: 0
score: -2

http://stackoverflow.com/q/51182059
has comment: http://stackoverflow.com/comment/89346657
favorite count: 0
has comment: http://stackoverflow.com/comment/89346762
has comment: http://stackoverflow.com/comment/89346535
answer count: 3
tagged with: python
has answer: http://stackoverflow.com/a/51182114
downvote count: 1
has answer: http://stackoverflow.com/a/51185400
upvote count: 4
has comment: http://stackoverflow.com/comment/89351943
has body: I want to create a child class from a parent class. This is to reduce redundancy in code. For instance, class Parent(): def __init__(self, a, b, c, d, e, f, g): self.a = a self.b = b ... self.g = g class Child1(Parent): def __init__(self, a, b, c, d, e, f, g, h, i, j, k): super().__init__(a, b, c d, e, f, g) self.i = i self.j = j self.k = k class Child2(Parent): def __init__(self, a, b, c, d, e, f, g, h, x, y, z): super().__init__(a, b, c d, e, f, g) self.x = x self.y = y self.z = z I don't want to pass parameters again and again for all child classes. Is there a way I could make Child1 and Child2 from Parent class? I have 30+ parameters and many child classes. It seems very redundant to write out all parameters. Plus, they all share the same parameters as parents.
has answer: http://stackoverflow.com/a/51182772
has comment: http://stackoverflow.com/comment/89346460
has title: How to instantiate a child class from parent class
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89346567
tagged with: inheritance
tagged with: class
type: Question
has comment: http://stackoverflow.com/comment/89346602
score: 3
linked to: http://stackoverflow.com/q/6381590
has comment: http://stackoverflow.com/comment/89346708
has comment: http://stackoverflow.com/comment/89346684

pyspark
tags question: http://stackoverflow.com/q/51230726
tags question: http://stackoverflow.com/q/51226469
tags question: http://stackoverflow.com/q/51172066
tags question: http://stackoverflow.com/q/51213774
tags question: http://stackoverflow.com/q/51313968
tags question: http://stackoverflow.com/q/51182152
tags question: http://stackoverflow.com/q/51193950
tags question: http://stackoverflow.com/q/51310952
tags question: http://stackoverflow.com/q/51236970
tags question: http://stackoverflow.com/q/51241445
tags question: http://stackoverflow.com/q/51317473
tags question: http://stackoverflow.com/q/51268571
tags question: http://stackoverflow.com/q/51268803
tags question: http://stackoverflow.com/q/51181384
tags question: http://stackoverflow.com/q/51272746
tags question: http://stackoverflow.com/q/51314144
tags question: http://stackoverflow.com/q/51281327
tags question: http://stackoverflow.com/q/51269463
tags question: http://stackoverflow.com/q/51226799
type: Tag
tags question: http://stackoverflow.com/q/51275558
tags question: http://stackoverflow.com/q/51291226
tags question: http://stackoverflow.com/q/51309693
tags question: http://stackoverflow.com/q/51206730
tags question: http://stackoverflow.com/q/51188301
tags question: http://stackoverflow.com/q/51282400
tags question: http://stackoverflow.com/q/51204227
tags question: http://stackoverflow.com/q/51302042
tags question: http://stackoverflow.com/q/51178469
tags question: http://stackoverflow.com/q/51322445
tags question: http://stackoverflow.com/q/51200217
tags question: http://stackoverflow.com/q/51306666
tags question: http://stackoverflow.com/q/51232624
tags question: http://stackoverflow.com/q/51223026
tags question: http://stackoverflow.com/q/51247247
tags question: http://stackoverflow.com/q/51236909
tags question: http://stackoverflow.com/q/51276541
tags question: http://stackoverflow.com/q/51253271
tags question: http://stackoverflow.com/q/51211191
tags question: http://stackoverflow.com/q/51263477
tags question: http://stackoverflow.com/q/51294386
tags question: http://stackoverflow.com/q/51194183
tags question: http://stackoverflow.com/q/51171328
tags question: http://stackoverflow.com/q/51286487
tag name: pyspark
tags question: http://stackoverflow.com/q/51185303

http://stackoverflow.com/comment/96776124
type: Comment
has text: Not that I'm saying that you don't understand it :)
comment on: http://stackoverflow.com/a/54946522
type: AnswerComment
score: 0

http://stackoverflow.com/comment/89533433
type: Comment
comment on: http://stackoverflow.com/q/51277848
score: 0
has text: The variable `line` in `__str__` is not defined. You should be getting an error. Also, `self.wörter` is always an empty list. You never change it. There are many other errors in your code. You should not start learning Python by attempting to write complex programs.
type: QuestionComment

http://stackoverflow.com/comment/89621993
type: AnswerComment
comment on: http://stackoverflow.com/a/51322446
score: 0
type: Comment
has text: Yes, that makes sense, thank you so much! I am still learning python and Django, so sometimes the most easy approach eludes me :)

http://stackoverflow.com/q/51220338
answer count: 0
tagged with: angularjs
type: UnansweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/89421538
tagged with: http://stackoverflow.com/tag/json
type: Question
has comment: http://stackoverflow.com/comment/89430426
has title: Dynamically generate AngularJS form with dynamic textboxes generation
has body: I want to create textboxes as per the user entered values for each block and get the saved information posted as JSON in the following format: [ { "Student1": { "college_name": "abc", "age": 20, "total_courses": 2, "course_1_name": "angularjs", "course_2_name": "nodejs" } }, { "Student2": { "college_name": "xyz", "age": 22, "total_courses": 3, "course_1_name": "angularjs", "course_2_name": "nodejs", "course_3_name": "python" } } ] The angular code will have html code displaying the form as below: Now if I click on add more button, this should bring another blank form for user as below just below the above form that is already filled: Now when I fill the form and if I enter total courses as 3, it should dynamically display 3 textboxes as below: Now when I fill 3 courses name it would appear as below: Now form would appear as below: Now when user clicks on submit button it should save the information in the JSON format as mentioned below: [ { "Student1": { "college_name": "abc", "age": 20, "total_courses": 2, "course_1_name": "angularjs", "course_2_name": "nodejs" } }, { "Student2": { "college_name": "xyz", "age": 22, "total_courses": 3, "course_1_name": "angularjs", "course_2_name": "nodejs", "course_3_name": "python" } } ]
has comment: http://stackoverflow.com/comment/89421802
tagged with: python
tagged with: angularjs-ng-repeat

python-webbrowser
tags question: http://stackoverflow.com/q/51177900
tags question: http://stackoverflow.com/q/51206588
tag name: python-webbrowser
type: Tag

multi-index
tags question: http://stackoverflow.com/q/51256352
tags question: http://stackoverflow.com/q/51240826
tags question: http://stackoverflow.com/q/51242015
type: Tag
tags question: http://stackoverflow.com/q/51226318
tag name: multi-index
tags question: http://stackoverflow.com/q/51267876
tags question: http://stackoverflow.com/q/51269850
tags question: http://stackoverflow.com/q/51236768
tags question: http://stackoverflow.com/q/51276024

http://stackoverflow.com/comment/89624003
score: 1
type: Comment
type: QuestionComment
has text: What is `temp_df`.? I can't see it in your code
comment on: http://stackoverflow.com/q/51324402

http://stackoverflow.com/comment/89516247
score: 0
comment on: http://stackoverflow.com/q/51267483
type: Comment
type: QuestionComment
has text: I have edited the data in the appropriate format :)

http://stackoverflow.com/q/51209233
tagged with: python
tagged with: regex
has title: Find string not preceded by other string
type: AnsweredQuestion
score: 2
has comment: http://stackoverflow.com/comment/89399112
has comment: http://stackoverflow.com/comment/89399161
accepted answer: http://stackoverflow.com/a/51209380
type: Question
has comment: http://stackoverflow.com/comment/89399115
downvote count: 0
has body: I want to get only ['bar'] here: &gt;&gt;&gt; re.findall(r"(?&lt;!\bdef )([a-zA-Z0-9.]+?)\(", "def foo(): bar()") ['oo', 'bar'] Is that possible in a single regex? If not, i'll use this first: re.sub(r"\bdef [a-zA-Z0-9.]+", "", "def foo(): bar()")
answer count: 1
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51209380
upvote count: 2

http://stackoverflow.com/a/51275181
type: Answer
accepted answer of: http://stackoverflow.com/q/51274194
has body: It sounds like you're asking for two things here: How to run tasks in parallel, and How to share (mutable) values between those tasks. For the first one, the answer is, as you suspected, threads. For some programs, that isn't the answer, because they're spending most of their time doing heavy CPU computation in Python, or because you need thousands of tasks rather than a handful. But here, just run each one as a thread. Instead of this: my_Class().get_data("path/to/file") #call 1 my_Class().get_data("path/to/another/file") #call 2 … you create your threads: t1 = threading.Thread(target=my_Class().get_data, args= ("path/to/file",)) t2 = threading.Thread(target=my_Class().get_data, args= ("path/to/another/file",)) … then start them: t1.start() t2.start() … then wait for them all to finish (which, in this case, will obviously take forever, so you could simplify things here…): t1.join() t2.join() Now, how do you share mutable data between threads? To start with, you can just access and mutate the same values from the different threads. But in general, you'll want to put a lock around each value, unless you know that you don't need one. If you only care about CPython on Windows, macOS, Linux, and BSD, inserting a string value with a string key into a dict object is one of those things that doesn't need a lock. And printing to stdout is another one. And those are the only things you're sharing. So, you actually don't need any locks here; things will just work. But, since you probably didn't know that dicts were safe in this way, let's see how you'd use a lock. data = {} data_lock = threading.Lock() # etc. def get_data(self, filepath): """I'm trying to import the data from several files""" for line in tail("-f", "-n 1", filepath, _iter=True): with data_lock: data[filepath] = line print(data) That's all there is to it. Things can get a bit more complicated. For example, you don't really need to hold the lock for as long as you're doing here. If you had 30 threads, there'd b…
score: 0
answers question: http://stackoverflow.com/q/51274194
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89530416
has comment: http://stackoverflow.com/comment/89529824

http://stackoverflow.com/a/51255648
score: 5
downvote count: 0
has comment: http://stackoverflow.com/comment/89490575
has comment: http://stackoverflow.com/comment/89491232
has comment: http://stackoverflow.com/comment/89490426
type: Answer
has comment: http://stackoverflow.com/comment/89490663
answers question: http://stackoverflow.com/q/51255592
has comment: http://stackoverflow.com/comment/89490327
has comment: http://stackoverflow.com/comment/89490295
has comment: http://stackoverflow.com/comment/89490743
has body: Am I doing something wrong, is is this calculation just so simple that it isn't a good test for NumPy? It's not really that the calculation is simple, but that you're not taking any advantage of NumPy. The main benefit of NumPy is vectorization: you can apply an operation to every element of an array in one go, and whatever looping is needed happens inside some tightly-optimized C (or Fortran or C++ or whatever) loop inside NumPy, rather than in a slow generic Python iteration. But you're only accessing a single value, so there's no looping to be done in C. On top of that, because the values in an array are stored as "native" values, NumPy functions don't need to unbox them, pulling the raw C double out of a Python float, and then re-box them in a new Python float, the way any Python math functions have to. But you're not doing that either. In fact, you're doubling that work: You're pulling the value out o the array as a float (boxing it), then passing it to a function (which has to unbox it, and then rebox it to return a result), then storing it back in an array (unboxing it again). And meanwhile, because np.sqrt is designed to work on arrays, it has to first check the type of what you're passing it and decide whether it needs to loop over an array or unbox and rebox a single value or whatever, while math.sqrt just takes a single value. When you call np.sqrt on an array of 200000 elements, the added cost of that type switch is negligible, but when you're doing it every time through the inner loop, that's a different story. So, it's not an unfair test. You've demonstrated that using NumPy to pull out values one at a time, act on them one at a time, and store them back in the array one at a time is slower than just not using NumPy. But, if you compare it to actually taking advantage of NumPy—e.g., by creating an array of 200000 floats and then calling np.sqrt on that array vs. looping over it and calling math.sqrt on each one—you'll demonstrate that using NumPy the w…
upvote count: 5

http://stackoverflow.com/comment/89356412
has text: Happy to hear it worked.
type: QuestionComment
comment on: http://stackoverflow.com/q/51185079
score: 0
type: Comment

memory-leaks
tags question: http://stackoverflow.com/q/51258363
tags question: http://stackoverflow.com/q/51229157
type: Tag
tag name: memory-leaks
tags question: http://stackoverflow.com/q/51175837
tags question: http://stackoverflow.com/q/51272951
tags question: http://stackoverflow.com/q/51177679
tags question: http://stackoverflow.com/q/51292006

http://stackoverflow.com/a/51220215
score: 1
has comment: http://stackoverflow.com/comment/89427625
has comment: http://stackoverflow.com/comment/89427742
accepted answer of: http://stackoverflow.com/q/51214599
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89430264
answers question: http://stackoverflow.com/q/51214599
has comment: http://stackoverflow.com/comment/89430373
type: Answer
has comment: http://stackoverflow.com/comment/89428774
has body: To start - your dataframes above do not match your dataframe construction. It took me forever to figure out why 9362 != 9362 :-) Here so something to consider: numbers = df5['Dept_Nbr'].tolist() df5['Dept_Nbr'] = [int(i) for i in df5['Dept_Nbr']] df5 = df5.set_index('Dept_Nbr') #&lt;-- need to actually set df5 to the new index for n in numbers: for i in range(len(df5.index)): #&lt;-- you want to iterate through the number of elements not the elements themselves if str(n) == df2.loc[i, 'Department'][-4:]: #&lt;-- convert n to str and slice df2 string for the last 4 chars if df5.loc[n, 'Dept_Desc_better'] != "Empty": #&lt;-- you're actually checking against a string, not a NaN df2.loc[i, 'TrueDepartment'] = df5.loc[n, 'Dept_Desc_better'] #&lt;-- use .loc not .at else: df2.loc[i, 'TrueDepartment'] = df5.loc[n, 'Dept_Desc_good'] df2 = df2.replace(to_replace="Empty", value="") #&lt;-- your desired output has '' rather than 'Empty' - so replaced. The assumption is that the df2 description under Department always has the Dept_Nbr at the end and it is always 4 characters long. And here's the output: df2 JobTitle Department TrueDepartment Dept_Function 0 CMI-General Liability | 05-9632 1 Central Operations 2 Alarm Central 05-8642 Security &amp; Compliance 3 Market 466 4 Talent, Experience 5 Food Division 6 Quality WMCC 7 Modular Execution Team | 01-9700 Execution Team 8 US Central Operations 9 CE - Engineering - US 10 Fresh, Freezer &amp; Cooler - 18-8110 Fresh Dept 11 9701 Produce TN 12 Contact Center 13 Central Operations 14 US Central Operations 15 Private Brands GM - 01-8683 General Merchandise By the way - the code does work, there isn't an error in index line 0 - this is where your dataframes are different. I also kept as much of your code as possible, but I would guess that there is a better way to iterate.
has comment: http://stackoverflow.com/comment/89430186
has comment: http://stackoverflow.com/comment/89426109
has comment: http://stackoverflow.com/comment/89427726
downvote count: 0
has comment: http://stackoverflow.com/comment/89430335

http://stackoverflow.com/comment/89420000
type: QuestionComment
has text: @ellanesc: I have uploaded the matrix to a drive, and I have put a shareable link in the original post now.
comment on: http://stackoverflow.com/q/51219068
score: 0
type: Comment

http://stackoverflow.com/a/51253080
type: Answer
has body: first, you need to use string.split() so you can get array consist of each world in your string then you can use for and concatenate the additional letters
upvote count: 0
score: -2
downvote count: 2
answers question: http://stackoverflow.com/q/51253012

http://stackoverflow.com/q/51248929
has comment: http://stackoverflow.com/comment/89476882
type: UnansweredQuestion
tagged with: python
tagged with: excel
score: -1
has comment: http://stackoverflow.com/comment/89477359
tagged with: xlwings
tagged with: openpyxl
has title: Excel formulas in python
has body: I have been searching all day for a solution to this problem, and I can't seem to find any solution.My original goal was to find a way to use excel autofill through a python library but that seemed impossible. So far I have tried xlwings and openpyxl to do the following : write an extremely simple excel formula to a sheet. I know I can do the same as what the formula does inside python, but I want people who open the excel to see the formula, so I don't want it to disappear. =IF(AB41&lt;&gt;"";CONCATENATE(AB41;".";AC41);"") Using openpyxl the file always gets corrupted, and excel repairs it by deleting the formulas. Using xlwings I get a special error (see below). I don't understand why this has to be so difficult. The libraries just have to print the formula to the cell, and let excel do the interpreting afterwards. Traceback (most recent call last): File "C:/Users/David/Google Drive/Jobs/1.Efe/Transporte/0.MODEL/rungams7.py", line 109, in &lt;module&gt; FLOWNREL("AD48","AD109",ws10) File "C:/Users/David/Google Drive/Jobs/1.Efe/Transporte/0.MODEL/rungams7.py", line 65, in FLOWNREL ws.range((i,col)).value = '=IF('+cell2.get_address(False, False) + '&lt;&gt;"";0;"")' File "C:\Users\David\Anaconda3\lib\site-packages\xlwings\main.py", line 1495, in value conversion.write(data, self, self._options) File "C:\Users\David\Anaconda3\lib\site-packages\xlwings\conversion\__init__.py", line 35, in write pipeline(ctx) File "C:\Users\David\Anaconda3\lib\site-packages\xlwings\conversion\framework.py", line 66, in __call__ stage(*args, **kwargs) File "C:\Users\David\Anaconda3\lib\site-packages\xlwings\conversion\standard.py", line 91, in __call__ self._write_value(ctx.range, ctx.value, scalar) File "C:\Users\David\Anaconda3\lib\site-packages\xlwings\conversion\standard.py", line 71, in _write_value rng.raw_value = value File "C:\Users\David\Anaconda3\lib\site-packages\xlwings\main.py", line 1116, in raw_value self.impl.raw_value = data File "C:\Users\David\Anaconda3\lib\site-packa…
downvote count: 1
type: Question
upvote count: 0
answer count: 1
tagged with: vba
favorite count: 0
has answer: http://stackoverflow.com/a/51249368

http://stackoverflow.com/a/51247685
downvote count: 0
type: Answer
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/51243902
accepted answer of: http://stackoverflow.com/q/51243902
has comment: http://stackoverflow.com/comment/89502627
has body: This works: import pandas as pd import matplotlib.pyplot as plt i = pd.to_datetime(['2000-01-01','2000-04-01','2000-07-01','2000-10-01','2001-01-01','2001-04-01','2001-07-01','2001-10-01']) d = [0,54957.84767,0,0,0,56285.54879,0,0] df = pd.DataFrame({'Values': d}, index=i) df_resampled = df.resample('M').first().interpolate(method='cubic') # Display the fit df['Values'].plot(linestyle='none', marker='D', color='red') df_resampled['Values'].plot(label='fit') plt.xlabel('Date') plt.ylabel('Values, a.u.') plt.legend()
has comment: http://stackoverflow.com/comment/89504509
type: AcceptedAnswer

http://stackoverflow.com/comment/89424889
has text: so maybe you just need `soap.find("div",{"class" :"SOMETHING"})` to get ONE result
comment on: http://stackoverflow.com/q/51221190
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51174506
linked to: http://stackoverflow.com/q/16476924
has answer: http://stackoverflow.com/a/51174640
type: Question
linked to: http://stackoverflow.com/q/20548628
type: AnsweredQuestion
tagged with: duplicates
tagged with: dataframe
upvote count: 4
has comment: http://stackoverflow.com/comment/89334410
has body: I have a dataframe contains millions data. Suppose this is the dataframe named mydataframe: filename | #insert-1 | #insert-2 | #delete-1 | #delete-2 --------------------------------------------------------- A | 4 | 4 | 3 | 3 B | 3 | 5 | 2 | 2 C | 5 | 5 | 6 | 7 D | 2 | 2 | 3 | 3 E | 4 | 5 | 5 | 3 --------------------------------------------------------- I need to separate the file based on the different number of insert or delete, then save them into new CSV file, named different.csv. And also save the rest of the data having the same number of insert and delete in the separate CSV file called same.csv. In the other words, if the file has a different number between #insert-1 and #insert-2, or #delete-1 and #delete-2 then save it in different.csv, otherwise, save it in same.csv. The expected result: different.csv: filename | #insert-1 | #insert-2 | #delete-1 | #delete-2 --------------------------------------------------------- B | 3 | 5 | 2 | 2 C | 5 | 5 | 6 | 7 E | 4 | 5 | 5 | 3 --------------------------------------------------------- same.csv filename | #insert-1 | #insert-2 | #delete-1 | #delete-2 --------------------------------------------------------- A | 4 | 4 | 3 | 3 D | 2 | 2 | 3 | 3 --------------------------------------------------------- This is my code so far: df_different = [] df_same = [] for row in range(0, len(mydataframe)): ins_1 = mydataframe.iloc[row][1] ins_2 = mydataframe.iloc[row][2] del_1 = mydataframe.iloc[row][3] del_2 = mydataframe.iloc[row][4] if (ins_1 != ins_2) or (del_1 != del_2): df_different.append(mydataframe.iloc[row]) else: df_same.append(mydataframe.iloc[row]) with open('different.csv','w') as diffcsv: writers = csv.writer(diffcsv, delimiter=',') writers.writerow(fields) for item in df_different: writers.writerow(item) with open('same.csv','w') as diffcsv: writers = csv.writer(diffcsv, delimiter=',') writers.writerow(fields) for item in df_same: writers.writerow(item) Actually, the code works well but when the dataset is very larg…
downvote count: 0
score: 4
possible better answer: http://stackoverflow.com/a/51174640
favorite count: 0
has answer: http://stackoverflow.com/a/51174730
accepted answer: http://stackoverflow.com/a/51174730
answer count: 3
has answer: http://stackoverflow.com/a/51174777
tagged with: pandas
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/89332156
tagged with: python
has title: Is there a faster way to separate duplicate and different data from CSV using python?

http://stackoverflow.com/a/51246761
score: 1
has body: You need to use writerow Ex: x=['1468853914','2016-07-18 12:04:56.2 UTC', '0','970.157'] import csv myFile = open(filename, 'w') writer = csv.writer(myFile, delimiter=',') writer.writerow(x) MoreInfo
upvote count: 2
type: AcceptedAnswer
downvote count: 1
answers question: http://stackoverflow.com/q/51246724
type: Answer
accepted answer of: http://stackoverflow.com/q/51246724

permissions
tag name: permissions
tags question: http://stackoverflow.com/q/51216070
type: Tag

http://stackoverflow.com/q/51256176
score: 0
has body: Hello StackOverflow Community! I have found a very interesting issue with my code (whether it's a bug or not I have no idea) that severely confuses me, and I'm wondering if the helpful people reading this question can help me out. So currently, I have the simple code below (with the 3 X's representing my keys on my Twitter app): import tweepy consumer_key = 'XXX' consumer_secret = 'XXX' access_token = 'XXX' access_token_secret = 'XXX' auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) api = tweepy.API(auth) user = api.me() print('Launching application with user id: ' + user.name) for follower in tweepy.Cursor(api.followers).items(): follower.follow() search = "#kittens AND #cute #puppy -#grumpy -#ugly" tnumber = 800 for tweet in tweepy.Cursor(api.search, search).items(tnumber): try: tweet.retweet() print('Found a tweet - Retweeted') tweet.favorite() print('Favorited tweet') except tweepy.TweepError as e: print(e.reason) except StopIteration: break If I run this code, naturally it will print the launching application with... message. But everything else returns exactly nothing. To put it into further perspective, if I was to run it in a terminal with py main.py the console would simply go down a line. Now obviously this accomplishes the exact opposite of what I want my code to do. So my overall question is (what most people post on Stack Overflow), why doesn't this work? But what I'm mainly looking for is, why does it return absolutely nothing? Many thanks for your help
has comment: http://stackoverflow.com/comment/89493099
type: UnansweredQuestion
tagged with: python
tagged with: tweepy
answer count: 0
type: Question
has title: Why is Tweepy returning absolutely nothing when retweeting?
has comment: http://stackoverflow.com/comment/89491362
has comment: http://stackoverflow.com/comment/89491321

http://stackoverflow.com/comment/89397308
has text: Yes, I think this is **neat** way to do it.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/51207765
type: Comment

http://stackoverflow.com/a/51180569
has body: arr = [[0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0], [0, 0, 1, 1, 0, 0], [0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 0]] # Find all positions where arr value is 1 pos_list = [(i,j) for i,r in enumerate(arr) for j,e in enumerate(r) if e] # [(1, 3), (2, 2), (2, 3), (3, 1), (4, 4)] # Get min of all (x, y) values as start_pos and max of all (x, y) values as end_pos x_pos, y_pos = zip(*[(i,j) for i,r in enumerate(arr) for j,e in enumerate(r) if e]) start_pos, end_pos = (min(x_pos), min(y_pos)), (max(x_pos), max(y_pos)) print (start_pos, end_pos) # (1, 1), (4, 4) Eliminate all blank rows, transpose array (by zipping it), again eliminate all rows, transpose it back again, to get the smallest sub array for original array that fits all 1's sub_arr = list(zip(*[r for r in zip(*[r for r in arr if any(r)]) if any(r)])) print (sub_arr) # [(0, 0, 1, 0), (0, 1, 1, 0), (1, 0, 0, 0), (0, 0, 0, 1)]
answers question: http://stackoverflow.com/q/51180268
type: Answer
score: 0

http://stackoverflow.com/comment/139708974
comment on: http://stackoverflow.com/q/51296584
score: 0
type: Comment
type: QuestionComment
has text: So you actually wanted a list? Please [edit] the question to explain that. Otherwise this is an [XY problem](https://meta.stackexchange.com/q/66377/343832).

http://stackoverflow.com/q/51197261
answer count: 0
has comment: http://stackoverflow.com/comment/89376305
type: UnansweredQuestion
tagged with: multithreading
has body: I'm trying to thread multiple read_sql_query commands using Pandas. However, threading in one notebook is drastically slower than simply running each read_sql command in separate notebooks at once. My threaded code is: SQL_Queries = ["Query 1" , "Query 2" , "Query 3"] SQL_Results = [] def myfunct(i): SQL_Results.append(pd.read_sql_query(SQL_Queries[i])) for i in range(3): t = Thread(target=myfunct, args=(i,)) t.start() This runs in about 2 minutes. However, if I open up 3 IPython notebooks like the following: NOTEBOOK 1: pd.read_sql_query("Query 1") NOTEBOOK 2: pd.read_sql_query("Query 2") NOTEBOOK 3: pd.read_sql_query("Query 3") and hit run on each at the same time, they'll all be finished within 1 minute. Any ideas on how I can achieve this performance in one notebook?
tagged with: python
has comment: http://stackoverflow.com/comment/89379213
type: Question
has title: Threading Slower than Multiple Notebooks
score: 0
tagged with: pandas
tagged with: jupyter-notebook
has comment: http://stackoverflow.com/comment/89376248

http://stackoverflow.com/q/51262309
answer count: 2
has answer: http://stackoverflow.com/a/51262460
has body: I'm trying to convert m4a audio file with artwork (cover) to mp3. I'm using ffmpeg to convert the audio. Once it copies, the artwork is lost. I'm quite not sure, how to retain the cover. I found some reference about mutagen library but not sure again how to use to copy the artwork. Any help would be great. ffmpeg -i source/file -acodec libmp3lame -ab 128k destination.mp3 Update: I'm reading the artwork and m4a to be able to attache it back. I can get the artwork by using artwork = audio.tags['covr'] Now my problem is how do I save the artwork as image in a new file? I tried the Following: with open(path/to/write, 'wb') as img: img.write(artwork) This gives me an error 'list' does not support the buffer interface line Any suggestion, how I can save the artwork extracted covr data?
tagged with: audio-converter
tagged with: python
type: UnansweredQuestion
score: 0
has title: Lost artwork while converting .m4a to .mp3 (Python)
tagged with: m4a
has answer: http://stackoverflow.com/a/51386699
tagged with: http://stackoverflow.com/tag/mp3
type: Question

http://stackoverflow.com/a/79032320
has body: For matplotlib versions greater than ~3.6, to avoid the "ValueError: Unable to determine Axes to steal space for Colorbar" error, you need to specify the axes for the colorbar, which can be done via plt.gca(): import matplotlib.pyplot as plt from matplotlib.cm import ScalarMappable data_x = [0,1,2,3] data_hight = [60,60,80,100] data_color = [1000.,500.,1000.,900.] data_color = [x / max(data_color) for x in data_color] fig, ax = plt.subplots(figsize=(15, 4)) my_cmap = plt.get_cmap('GnBu') # plt.cm.get_cmap is deprecated as of v3.7 colors = my_cmap(data_color) rects = ax.bar(data_x, data_hight, color=colors) sm = ScalarMappable(cmap=my_cmap, norm=plt.Normalize(0,max(data_color))) sm.set_array([]) cbar = plt.colorbar(sm, ax = plt.gca()) # Supply the current axes to the colorbar cbar.set_label('Color', rotation=270,labelpad=25) plt.xticks(data_x) plt.ylabel("Y") plt.show()
score: 0
answers question: http://stackoverflow.com/q/51204505
type: Answer

http://stackoverflow.com/a/51250981
type: Answer
has body: Stop using pyreadline. It's been abandoned. What you're seeing is a known issue, but unless someone takes over pyreadline development, it's unlikely to ever be fixed.
has comment: http://stackoverflow.com/comment/109019257
score: 5
has comment: http://stackoverflow.com/comment/89480900
downvote count: 0
has comment: http://stackoverflow.com/comment/89481028
upvote count: 5
has comment: http://stackoverflow.com/comment/104586230
answers question: http://stackoverflow.com/q/51250796
has comment: http://stackoverflow.com/comment/115805362

http://stackoverflow.com/a/51251547
has body: If you want to extend your solution to make sure the leading digit isn't 0, there's probably no super-concise way to write it; just be explicit: first = random.choice(range(1, 10)) leftover = set(range(10)) - {first} rest = random.sample(leftover, 3) digits = [first] + rest Notice that I'm taking advantage of the fact that sample takes a sequence or set. In older versions of Python, it required a sequence. According to the 2.7 docs, this includes 2.7—but CPython and PyPy 2.7 both take a set anyway. Anyway, if this is a problem, you can just do leftover = [val for val in range(10) if val != first]. One more thing to consider, if performance matters. A nondeterminstic solution like noskio's answer obviously has unbounded worst-case time, but it could be significantly faster in almost every case. There's a 90% chance you'll get your answer the first time, and a 99.9999999% within the first ten loops, and it's at least plausible that a single call to sample could be about an order of magnitude faster than multiple set operations, etc.
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/51251479
accepted answer of: http://stackoverflow.com/q/51251479
score: 2
downvote count: 0
upvote count: 2

http://stackoverflow.com/comment/106913003
type: AnswerComment
score: 3
type: Comment
comment on: http://stackoverflow.com/a/51847744
has text: Worth noting is that the `setup.py` file is in the same directory where you run your final `python` command, then you must preppend `./` to it: `--setup_file ./setup.py`

pivot-table
tag name: pivot-table
tags question: http://stackoverflow.com/q/51179886
tags question: http://stackoverflow.com/q/51308575
tags question: http://stackoverflow.com/q/51202055
tags question: http://stackoverflow.com/q/51211232
tags question: http://stackoverflow.com/q/51201122
tags question: http://stackoverflow.com/q/51273743
type: Tag

http://stackoverflow.com/a/51260369
accepted answer of: http://stackoverflow.com/q/51260270
downvote count: 0
answers question: http://stackoverflow.com/q/51260270
score: 4
type: AcceptedAnswer
has body: You are right. Ignore JetBrains IDE's suggestion. Calling foo twice is unnecessary. The feature you are using is known as sequence unpacking and requires foo to be run once. Setting dictionary values, on the other hand, has O(1) complexity and is unlikely to be your bottleneck. In my opinion, your solution is also clearer than JetBrains IDE's alternative.
type: Answer
upvote count: 4

http://stackoverflow.com/comment/89699145
has text: Got it! I'll try my best. Thanks a lot for your help! :)
type: Comment
comment on: http://stackoverflow.com/a/51319254
score: 0
type: AnswerComment

qsqlquerymodel
tags question: http://stackoverflow.com/q/51284338
type: Tag
tag name: qsqlquerymodel

http://stackoverflow.com/q/51279570
favorite count: 0
tagged with: tkinter
has title: Python Tkinter Lambda Multiple Variable
possible better answer: http://stackoverflow.com/a/51295671
has answer: http://stackoverflow.com/a/74470318
has answer: http://stackoverflow.com/a/51295671
tagged with: python
has comment: http://stackoverflow.com/comment/89547075
accepted answer: http://stackoverflow.com/a/51286688
type: AnsweredQuestion
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/89617779
type: Question
has body: Quick question. I have created a button like this: LABEL = tkinter.Button(top, text ="GO 1", command = lambda *args: go('1'), width = 13, height=2) So, I was wondering. How can I pass multiple values to definition using lambda in the button above? def go(value): Thanks!
has comment: http://stackoverflow.com/comment/89623542
has comment: http://stackoverflow.com/comment/89685726
has comment: http://stackoverflow.com/comment/89536980
has answer: http://stackoverflow.com/a/51286688
has comment: http://stackoverflow.com/comment/89538618
answer count: 3
downvote count: 0

http://stackoverflow.com/a/51282354
type: Answer
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/89546107
has comment: http://stackoverflow.com/comment/89570193
accepted answer of: http://stackoverflow.com/q/51281208
upvote count: 1
answers question: http://stackoverflow.com/q/51281208
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89570219
has body: you can try use conditional-expressions before count: from django.db.models import Case, When, F, Count Profile.objects.annotate( reg=Case( When(region__isnull=True, then=F('country__region')), default=F('region')) ).values('reg').annotate(region_count=Count('reg'))

http://stackoverflow.com/q/51314078
upvote count: 1
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/51314406
downvote count: 0
has comment: http://stackoverflow.com/comment/89612904
has title: Add property in Django many to many relation
has comment: http://stackoverflow.com/comment/89610565
has comment: http://stackoverflow.com/comment/89605038
tagged with: django-rest-framework
has answer: http://stackoverflow.com/a/51314429
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
has body: I have the following Django models: class Lesson(models.Model): title = models.TextField() class Course(models.Model): lessons = models.ManyToManyField(Lesson) class User(AbstractUser): favorites = models.ManyToManyField(Lesson) I have a route /courses/course_id that returns a course details including an array of lessons (using Django Rest Framework) How can i return in the lessons object an additional attribute favorite based on my users favorites. I attempted the following: course = self.get_object(course_id) favorites = request.user.favorites for lesson in course.lessons.all(): if lesson in favorites.all(): lesson.favorite = True serializer = CourseDetailSerializer(course, context=serializer_context) return Response(serializer.data) But when returning it doesn't work: (django.core.exceptions.ImproperlyConfigured: Field name favorite is not valid for model Lesson. My serializers: class CourseDetailSerializer(serializers.HyperlinkedModelSerializer): lessons = LessonListSerializer(many=True, read_only=True) class Meta: model = Course fields = ('id', 'lessons', 'name', 'title') class LessonSerializer(serializers.ModelSerializer): class Meta: model = Lesson fields = ('id', 'title', 'duration', 'favorite')
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/89605492
score: 1

http://stackoverflow.com/comment/90024288
type: Comment
comment on: http://stackoverflow.com/a/51233132
has text: It was an error on my side. I forgot to use 'metaclass='. The problem is solved now. Thanks!
type: AnswerComment
score: 0

http://stackoverflow.com/a/51274752
has body: I have found something, that seems to be a viable workaround. The dictionary with atributes of the LogRecord object created in the client is converted to JSON before passing to the server. The server then decodes it and recreates the original LogRecord. The server part: from flask import Flask from flask import Response from flask import request import logging import logging.handlers import json app = Flask(__name__) @app.route('/') def hello_world(): return 'logging server' @app.route('/log', methods=['POST']) def handle_log(): if request.method == 'POST': rd=request.form.to_dict() rec=json.loads(rd['record']) record = logging.makeLogRecord(rec) log1.handle(record) return "OK" class myflt(logging.Filter): def filter(self,rec): print(rec.__dict__) return 1 mfl=myflt() log1=logging.getLogger('MTEST') log1.setLevel(logging.DEBUG) rfh=logging.handlers.RotatingFileHandler('logs','a',maxBytes=10000000,backupCount=10) formatter = logging.Formatter('%(asctime)s %(name)-15s %(levelname)-8s %(message)s') rfh.setFormatter(formatter) log1.addHandler(rfh) log1.addFilter(mfl) log1.error("First error generated locally") app.run() The client part: import logging, logging.handlers import json class myHTTPHandler(logging.handlers.HTTPHandler): def mapLogRecord(self,record): trec={'record':json.dumps(record.__dict__)} return trec myLogger = logging.getLogger('MTEST') myLogger.setLevel(logging.DEBUG) httpHandler = myHTTPHandler('localhost:5000',url='/log',method="POST") myLogger.addHandler(httpHandler) myLogger.info('Small info message') myLogger.debug('Small debug message') myLogger.error('Small error message') The above implementation works correctly, however it seems to be unnecessarily complicated. Is there any simpler way to use HTTPHandler to communicate with the remote RotatingFileHandler via HTTP protocol?
upvote count: 2
type: Answer
score: 2
answers question: http://stackoverflow.com/q/51274534
accepted answer of: http://stackoverflow.com/q/51274534
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/51253975
has comment: http://stackoverflow.com/comment/89498334
score: 0
has body: This is the error: rrdtool.OperationalError: invalid x-grid format From the RRDTool Manual: X-Axis [-x|--x-grid GTM:GST:MTM:MST:LTM:LST:LPR:LFM] The x-axis label is quite complex to configure. If you don't have very special needs it is probably best to rely on the auto configuration to get this right. You can specify the string none to suppress the grid and labels altogether. The grid is defined by specifying a certain amount of time in the ?TM positions. You can choose from SECOND, MINUTE, HOUR, DAY, WEEK, MONTH or YEAR. Then you define how many of these should pass between each line or label. This pair (?TM:?ST) needs to be specified for the base grid (G??), the major grid (M??) and the labels (L??). For the labels you also must define a precision in LPR and a strftime format string in LFM. LPR defines where each label will be placed. If it is zero, the label will be placed right under the corresponding line (useful for hours, dates etcetera). If you specify a number of seconds here the label is centered on this interval (useful for Monday, January etcetera). As you can see, your x-grid option is too short as you have omitted the labelling intervals: "--x-grid", "MINUTE:12:HOUR:1:0:%H", Try this instead, which labels every 4h: "--x-grid", "MINUTE:12:HOUR:1:HOUR:4:0:%H
answers question: http://stackoverflow.com/q/51242665
has comment: http://stackoverflow.com/comment/89539939
type: Answer

http://stackoverflow.com/q/51208401
downvote count: 0
tagged with: websocket
favorite count: 0
has comment: http://stackoverflow.com/comment/89403727
has comment: http://stackoverflow.com/comment/89399989
type: Question
has comment: http://stackoverflow.com/comment/89403708
has title: Using multiple WebSocket clients inside automated Selenium tests with unittest
has comment: http://stackoverflow.com/comment/89399344
tagged with: python
has comment: http://stackoverflow.com/comment/89398114
upvote count: 3
tagged with: selenium
has comment: http://stackoverflow.com/comment/89398341
answer count: 1
tagged with: unit-testing
has comment: http://stackoverflow.com/comment/89398659
has answer: http://stackoverflow.com/a/59299438
type: AnsweredQuestion
score: 3
accepted answer: http://stackoverflow.com/a/59299438
has body: I am writing automated UI tests for a specific device, where the UI configurations are transferred to the device from a back-end server as multiple JSON files over websocket connections. At first, I wrote a small separate script that receives websocket messages, saves them to JSON files and closes the websocket connection. Then when I ran my test in another file, I could access the JSON files and process the configuration info in my test. What I want to do however is to integrate this websocket connection inside the tests, so I will only run a test and it will handle everything. I tried to do this but the test gets stuck listening to the websocket and it cannot navigate in the UI, a next step in the test which would trigger the message transfer. I am running the tests on Windows 10 in an Anaconda virtual environment with Python 2.7.14 and using ChromeDriver for Selenium 3.11.0. The websocket library is the 0.2.1 version. Here is the code I used: #!/usr/bin/python #-*- encoding: utf-8 -*- import json from lib import * import sys import unittest import websocket import xmlrunner class TestCases(TestObject): def test_service_recharge(self): # Step 1: Login and initialize websocket client credential = self.get_data()["credentials"][0] login_page = LoginPage(self.get_driver(), url=self.get_url()) login_page.load_page() login_page.try_login(credential["username"], credential["password"]) ws = websocket.WebSocket() ws.connect("ws://192.168.1.105:8888/gui/services/menudata") print "Receiving websocket messages..." menu_data = ws.recv() # Step 2: Check successful login services_page = ServicesPage(self.get_driver()) services_page.check_opened() # Step 3: Save websocket message to a .json file menu_data_json = json.loads(menu_data) with open('PATH_TO_FILE\\Services_Menu_Recharge_JSON.json', 'w') as outfile: json.dump(menu_data_json, outfile) ws.close() # Step 4: Start a new websocket client to get a second, different message ws = websocket.WebSocket() ws.connect("ws://192.168…

http://stackoverflow.com/q/51289747
has title: How to separate data that don't form a sine function from those that do?
has comment: http://stackoverflow.com/comment/89574703
answer count: 0
type: Question
score: 0
tagged with: filter
has comment: http://stackoverflow.com/comment/89557731
tagged with: trigonometry
has body: I am trying to write a python code that helps me to determine where my real (recorded data in shape of sine function) data start. I have an array with values that are not equal to zero prior to data acquisition and I need to filter these. I attached an image for better understanding of a problem. I need to define where exactly the first cycle starts. plot of raw data A small (critical) part of my data looks like this: [0.001 0.000 0.000 0.000 0.000 -0.000 -0.000 -0.000 0.000 0.000 0.001 0.001 0.001 0.001 -0.000 -0.000 -0.000 -0.000 0.000 0.000 0.001 0.000 0.000 -0.000 -0.000 -0.000 -0.000 -0.000 0.000 0.000 0.001 0.001 0.001 0.001 0.000 -0.000 -0.000 -0.000 0.000 0.000 0.001 0.001 0.001 0.001 -0.000 -0.002 -0.002 -0.002 -0.053 -0.053 -0.155 -0.234 -0.234 -0.255 -0.307 -0.431 -0.431 -0.488 -0.566 -0.566 -0.641 -0.785 -0.785 -0.856 -0.932 -1.003 -1.003 -1.149 -1.220 -1.220 -1.298 -1.372 -1.372 -1.523 -1.577 -1.652 -1.652 -1.716 -1.836 -1.836 -1.894 -1.935 -1.935 -1.997 -2.084 -2.134 -2.134 -2.181 -2.216 -2.216 -2.274 -2.298 -2.298 -2.307 -2.318 -2.321 -2.321 -2.318 -2.313 -2.313 -2.300 -2.263 -2.263 -2.240 -2.205 -2.172 -2.172 -2.084 -2.036 -2.036 -1.983]
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89574298

http://stackoverflow.com/comment/89548067
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51282696
type: Comment
has text: `(r"((.*?))")` will not get content inside the parenthesis. Is that ok?

http://stackoverflow.com/a/51181186
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51181034
has comment: http://stackoverflow.com/comment/89345579
upvote count: 5
type: Answer
has comment: http://stackoverflow.com/comment/89345321
has body: As I understand from the book, if Sub inherits Super then one need not call superclass' (Super's) __init__() method. This is misleading. It's true that you aren't required to call the superclass's __init__ method—but if you don't, whatever it does in __init__ never happens. And for normal classes, all of that needs to be done. It is occasionally useful, usually when a class wasn't designed to be inherited from, like this: class Rot13Reader: def __init__(self, filename): self.file = open(filename): def close(self): self.file.close() def dostuff(self): line = next(file) return codecs.encode(line, 'rot13') Imagine that you want all the behavior of this class, but with a string rather than a file. The only way to do that is to skip the open: class LocalRot13Reader(Rot13Reader): def __init__(self, s): # don't call super().__init__, because we don't have a filename to open # instead, set up self.file with something else self.file = io.StringIO(s) Here, we wanted to avoid the self.file assignment in the superclass. In your case—as with almost all classes you're ever going to write—you don't want to avoid the self.name assignment in the superclass. That's why, even though Python allows you to not call the superclass's __init__, you almost always call it. Notice that there's nothing special about __init__ here. For example, we can override dostuff to call the base class's version and then do extra stuff: def dostuff(self): result = super().dostuff() return result.upper() … or we can override close and intentionally not call the base class: def close(self): # do nothing, including no super, because we borrowed our file The only difference is that good reasons to avoid calling the base class tend to be much more common in normal methods than in __init__. Question: Why do I need to call Super's __init__ using Super.__init__(self, name) OR super(Sub, self).__init__(name) instead of a direct call Super(name)? Because these do very different things. Super(name) constructs a new Su…
downvote count: 0
score: 5
accepted answer of: http://stackoverflow.com/q/51181034

http://stackoverflow.com/q/51321723
has title: Append rows for each value of dictionary with duplicated key in next column
type: AnsweredQuestion
downvote count: 0
score: 1
has body: Unfortunately I'm struggling with following plan: I scraped a large dictionary with usernames as keys and the keys' Instagram followers as their values. That looks like this e.g.: dict = { "User1": ['Follower_A', 'Follower_B', 'Follower_C', 'Follower_D', 'Follower_E', 'Follower_F', 'Follower_G'], "User2": ['Follower_Z', 'Follower_D', 'Follower_V', 'Follower_E' 'Follower_O'], "User3": ['Follower_P', 'Follower_Q'], "User4": ['Follower_M', 'Follower_A', 'Follower_Z', 'Follower_P' 'Follower_L'], . . ., "UserX": ['Follower_Z', 'Follower_D', 'Follower_V', 'Follower_E' 'Follower_O','Follower_Q']} In order to create a network I need to have a data frame that looks like this: User Follower 0 User1 Follower_A 1 User1 Follower_B 2 User1 Follower_C 3 User1 Follower_D 4 User1 Follower_E 5 User1 Follower_F 6 User1 Follower_G 7 User2 Follower_Z 8 User2 Follower_D 9 User2 Follower_V 10 User2 Follower_E 11 User2 Follower_O 12 User3 Follower_P 13 User3 Follower_Q Does anybody have an idea to create this in an efficient way? All my tries didn't work out... Thanks in advance!
type: Question
tagged with: dataframe
has answer: http://stackoverflow.com/a/51321825
accepted answer: http://stackoverflow.com/a/51321825
tagged with: pandas
upvote count: 1
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/89618914
tagged with: python
tagged with: dictionary

http://stackoverflow.com/comment/89516544
score: 0
has text: Thank you that got rid of that error message and created a new one: ProgrammingError: ('42S02', "[42S02] [Microsoft][ODBC SQL Server Driver][SQL Server]Invalid object name 'orders'. (208) (SQLExecDirectW)"). What can I do about that?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51268991

traitsui
tag name: traitsui
tags question: http://stackoverflow.com/q/51191921
type: Tag

http://stackoverflow.com/comment/89604775
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51312650
has text: (There is the precedent of `__new__` methods typically doing `self = object.__new__(cls)`, but I think that idiom is pretty closely tied to the specialness of `__new__`, and what it’s for.)

http://stackoverflow.com/a/51279150
upvote count: 2
has comment: http://stackoverflow.com/comment/89535968
type: Answer
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/89535817
has comment: http://stackoverflow.com/comment/89535798
answers question: http://stackoverflow.com/q/51279028
has comment: http://stackoverflow.com/comment/89536282
has body: You can extract the contents of the .exe file using PyInstaller Extractor. Run it like this: python pyinstxtractor.py executable.exe You will get your python file.
has comment: http://stackoverflow.com/comment/89535854

http://stackoverflow.com/comment/89467356
score: 0
type: Comment
type: AnswerComment
has text: Ohhh that's close. Until I ran into PO Box 10376 for the address. Is it possible to explicitly state 4 digits?
comment on: http://stackoverflow.com/a/51244162

http://stackoverflow.com/comment/89381423
has text: Regex definitely isn't prettier.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51196478
type: Comment

http://stackoverflow.com/a/51208252
upvote count: 3
has comment: http://stackoverflow.com/comment/89406936
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89406836
accepted answer of: http://stackoverflow.com/q/51208000
type: Answer
has comment: http://stackoverflow.com/comment/89401292
answers question: http://stackoverflow.com/q/51208000
has comment: http://stackoverflow.com/comment/89397646
has comment: http://stackoverflow.com/comment/89401343
downvote count: 0
has comment: http://stackoverflow.com/comment/89405441
score: 3
has comment: http://stackoverflow.com/comment/89406798
has comment: http://stackoverflow.com/comment/89397631
has body: There are a few points to note: You need to use return in your function. It's good practice to make such functions generic. For example, your input and output column names can be arguments with default values set. Pandas offers pd.DataFrame.pipe to facilitate method chaining. You should not name your function the same as the Pandas method. This will only lead to confusion. Putting these elements together: def rename_col(data, col_in='interval_time', col_out='Timestamp'): return data.rename(index=str, columns={col_in: col_out}) df = df.pipe(rename_col) This is a trivial example, which probably doesn't require a user-defined function. However, the above advice may help when you write more complex functions.

http://stackoverflow.com/q/51294499
has comment: http://stackoverflow.com/comment/89567213
has answer: http://stackoverflow.com/a/51995619
has title: Spyder anaconda crashes on Linux with segmentation fault
favorite count: 0
has comment: http://stackoverflow.com/comment/90866263
has answer: http://stackoverflow.com/a/52031135
tagged with: spyder
tagged with: python
has comment: http://stackoverflow.com/comment/89567072
has answer: http://stackoverflow.com/a/51306671
accepted answer: http://stackoverflow.com/a/51306671
possible better answer: http://stackoverflow.com/a/51995619
answer count: 4
type: AnsweredQuestion
has body: I just installed Anaconda on Linux. When trying to open spyder (either from navigator or terminal), it does not work. I get the following error when I try to open it in terminal: Segmentation fault (core dumped) I updated Conda completely but can't solve the problem. I am using Conda version 4.5.5 and Ubuntu 18.04. Any idea?
has answer: http://stackoverflow.com/a/52800838
has comment: http://stackoverflow.com/comment/89567145
downvote count: 1
type: Question
score: 5
tagged with: anaconda
upvote count: 6

http://stackoverflow.com/q/51182988
has comment: http://stackoverflow.com/comment/89348141
has comment: http://stackoverflow.com/comment/89350049
tagged with: python
has answer: http://stackoverflow.com/a/51184157
answer count: 4
has title: Python/Pandas: Identify Duplicates across Columns
tagged with: duplicates
has body: In the following code I would like to identify and report values in Col1 that appear in Col2, values in Col2 that appear in Col1 and overall values that appear more than once. In the example below values AAPL and GOOG appear in Col1 and Col2. These are expected to be identified and reported in next 2 columns, and in the column after that expecting to identify and report whether "any" of Col1 or Col2 values are DUP. import pandas as pd import numpy as np data={'Col1':['AAPL', np.nan, 'GOOG', 'MMM', np.nan, 'INTC', 'FB'],'Col2':['GOOG', 'IBM', 'MSFT', np.nan, 'GOOG', 'AAPL', 'VZ']} df=pd.DataFrame(data,columns=['Col1','Col2']) print (df) # How to code after this to produce expected result? # Appreciate any hint/help provided
type: Question
has answer: http://stackoverflow.com/a/51183310
has comment: http://stackoverflow.com/comment/89348690
has comment: http://stackoverflow.com/comment/89348293
has comment: http://stackoverflow.com/comment/89348199
score: 0
has answer: http://stackoverflow.com/a/51191737
tagged with: pandas
has answer: http://stackoverflow.com/a/51183546
type: UnansweredQuestion

http://stackoverflow.com/q/51205540
has comment: http://stackoverflow.com/comment/89392532
has comment: http://stackoverflow.com/comment/89392291
score: 0
has comment: http://stackoverflow.com/comment/89392586
has body: I am just trying to Migrate on of my Django project from version 1.4.22 to 1.5.1. Actually I am working on a package which is actually built in Django 1.4.10 and client needs to get it migrated to the latest version. It works fine upto 1.4.22 but not for 1.5.1 here is the package info: https://github.com/prikhi/AcornAccounting It all goes well, but when I tried to run the server it started throwing the following error: from django.http import HttpResponseRedirectBase, HttpResponse ImportError: cannot import name HttpResponseRedirectBase But the thing is this line is not being used anywhere in my code. Note: I am running the project on a virtual environment. and here is the complete error message: from django_ajax.encoder import serialize_to_json File "/home/dev31/.virtualenvs/AcornAccounting/local/lib/python2.7/site-packages/django_ajax/encoder.py", line 8, in from django.http import HttpResponseRedirectBase, HttpResponse ImportError: cannot import name HttpResponseRedirectBase I tried to resolve this error but nothing helped. Please help me to sort out this issue. Thanks.
has comment: http://stackoverflow.com/comment/89392371
type: UnansweredQuestion
tagged with: django
tagged with: python
has title: Unexpected Django Error [Django 1.5.1]
answer count: 0
has comment: http://stackoverflow.com/comment/89392660
type: Question
has comment: http://stackoverflow.com/comment/89392480

http://stackoverflow.com/comment/89584500
type: QuestionComment
type: Comment
has text: I think the misconception you have here is that these types are *static*, but you are thinking of the actual concrete values you're returning at runtime. That's not how static type systems work.
score: 0
comment on: http://stackoverflow.com/q/51303546

http://stackoverflow.com/q/51312964
has body: This exception: ValueError: invalid literal for int() with base 10: '17.1' keeps popping up but I can't figure out how to fix it. I have to be able to use decimals in this not just whole numbers but without the int(n1) and int(n2) it won't run at all. n1 = input("Enter the first number: ") n2 = input("Enter the second number: ") n1 = int(n1) n2 = int(n2) if n1 and n2 &gt; 10: print("Both are above 10.") elif n1 and n2 &lt;= 10: print("Both are below 10.") avg = (n1 + n2) / 2 print("Average is {:.2f}".format(avg))
favorite count: 0
tagged with: python-3.x
type: Question
tagged with: input
tagged with: python
has answer: http://stackoverflow.com/a/51313191
upvote count: 3
has title: Converting input to int throws "invalid literal for int() base 10" when passing in decimal numbers
answer count: 2
downvote count: 2
has comment: http://stackoverflow.com/comment/89602717
has answer: http://stackoverflow.com/a/51313131
type: UnansweredQuestion
tagged with: int
tagged with: decimal
score: 1

http://stackoverflow.com/a/51296815
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/89591308
has comment: http://stackoverflow.com/comment/89590782
type: Answer
has comment: http://stackoverflow.com/comment/89591871
has comment: http://stackoverflow.com/comment/89594504
has comment: http://stackoverflow.com/comment/89628736
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/89597944
has comment: http://stackoverflow.com/comment/89608757
answers question: http://stackoverflow.com/q/51289547
has comment: http://stackoverflow.com/comment/89640398
has comment: http://stackoverflow.com/comment/89593051
accepted answer of: http://stackoverflow.com/q/51289547
has body: First, you need a function that takes a string, splits it by commas and then by colons, and converts to a pandas Series through a dictionary: def str2series(s): pieces = [x.split(': ') for x in s.split(',')] return pd.Series({k.strip(): v.strip() for k,v in pieces}) Next, apply the function to the column: new_df = df.SourceTechAttributes.apply(str2series) The result is a dataframe that you are looking for. You can merge it with the original dataframe, if you want: they have the same index: df = df.join(new_df)

http://stackoverflow.com/comment/89537590
has text: But it seems OP wants `without replacement`.
type: Comment
comment on: http://stackoverflow.com/a/51279590
type: AnswerComment
score: 0

http://stackoverflow.com/comment/95415831
type: Comment
comment on: http://stackoverflow.com/a/54277645
type: AnswerComment
score: 0
has text: It did turn out too late, but since you at least answered the question, you do deserve getting the accepted answer.

http://stackoverflow.com/comment/89370626
has text: this runs in a few seconds with 1 core, try reducing the n and num variables? No not the average distance. I am after the average value of the array, as a function of distance from the center. Not the distance, but the average value of the array at varying distances.
comment on: http://stackoverflow.com/q/51193320
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51249496
has comment: http://stackoverflow.com/comment/89477936
type: Answer
has comment: http://stackoverflow.com/comment/90274913
upvote count: 1
score: 1
has body: ok so national is a list of length 1. To get the object we care about, all you need to do is national_dict = national[0]. I called it this since national_dict is a dictionary, not a string. To print out a nicely formatted dictionary, one option is to pretty print from pprint import pprint pprint(national_dict, width=100) # width defaults to 79 which outputs {'attributes': {'member': ['CN=gji9847,OU=U02562,OU=02562,DC=google,DC=corpad,DC=net', 'CN=exx8092,OU=U06032,OU=06032,DC=google,DC=corpad,DC=net', 'CN=EWR8386,OU=U09373,OU=09373,DC=google,DC=corpad,DC=net', 'CN=HXU9279,OU=U00704,OU=00704,DC=google,DC=corpad,DC=net', 'CN=KVG6693,OU=U25692,OU=25692,DC=google,DC=corpad,DC=net', 'CN=JCL6495,OU=U01246,OU=01246,DC=google,DC=corpad,DC=net', 'CN=RNE9520,OU=U01673,OU=01673,DC=google,DC=corpad,DC=net', 'CN=PCN5400,OU=U01673,OU=01673,DC=google,DC=corpad,DC=net', 'CN=WPM9271,OU=U01673,OU=01673,DC=google,DC=corpad,DC=net', 'CN=JKJ2421,OU=U01692,OU=01692,DC=google,DC=corpad,DC=net']}, 'dn': 'CN=All.DL Div Controllers - National Group,OU=Distribution ' 'Lists,OU=Exchange,DC=google,DC=corpad,DC=net', 'raw_attributes': {'member': [b'CN=gji9847,OU=U02562,OU=02562,DC=google,DC=corpad,DC=net', b'CN=exx8092,OU=U06032,OU=06032,DC=google,DC=corpad,DC=net', b'CN=EWR8386,OU=U09373,OU=09373,DC=google,DC=corpad,DC=net', b'CN=HXU9279,OU=U00704,OU=00704,DC=google,DC=corpad,DC=net', b'CN=KVG6693,OU=U25692,OU=25692,DC=google,DC=corpad,DC=net', b'CN=JCL6495,OU=U01246,OU=01246,DC=google,DC=corpad,DC=net', b'CN=RNE9520,OU=U01673,OU=01673,DC=google,DC=corpad,DC=net', b'CN=PCN5400,OU=U01673,OU=01673,DC=google,DC=corpad,DC=net', b'CN=WPM9271,OU=U01673,OU=01673,DC=google,DC=corpad,DC=net', b'CN=JKJ2421,OU=U01692,OU=01692,DC=google,DC=corpad,DC=net']}, 'raw_dn': b'CN=All.DL Div Controllers - National Group,OU=Distribution Lists,OU=Exchange,DC=goog' b'le,DC=corpad,DC=net', 'type': 'searchResEntry'} Is this sort of what you're looking for? In order to pretty print to a file import pprint formatted = ppr…
answers question: http://stackoverflow.com/q/51249360
downvote count: 0

http://stackoverflow.com/q/51290599
accepted answer: http://stackoverflow.com/a/51303428
has title: Google Adwords - CUSTOMER_ID_IS_REQUIRED ERROR (Python)
score: 0
answer count: 1
tagged with: google-ads-api
has body: I'm trying to use the Google Adwords Test API. I'm trying to connect to the Google Adwords API, but I keep getting the following error: googleads.errors.GoogleAdsServerFault: [AuthenticationError.CLIENT_CUSTOMER_ID_IS_REQUIRED @ ; trigger:'&lt;null&gt;'] I've made a Google Adwords Production Account in order to get the developer API key. I've then made a Google Adwords Manager Test account and managed to get a Oauth Client id, and Secret Id. I then used the Google Oauth 2.0 playground to get the refresh token. My google_adwords.yaml file now looks something like this: # AdWordsClient configurations adwords: ############################################################################# # Required Fields # ############################################################################# developer_token: **DEVELOPER TOKEN FROM PRODUCTION ACCOUNT PASTED HERE** ############################################################################# # Optional Fields # ############################################################################# # client_customer_id: **CLIENT CUSTOMER ID FROM MANAGER TEST ACCOUNT PASTED HERE** # user_agent: INSERT_USER_AGENT_HERE # partial_failure: True # validate_only: True ############################################################################# # OAuth2 Configuration # # Below you may provide credentials for either the installed application or # # service account flows. Remove or comment the lines for the flow you're # # not using. # ############################################################################# # The following values configure the client for the installed application # flow. client_id: **CLIENT ID FROM MANAGER TEST ACCOUNT PASTED HERE** client_secret: **CLIENT CUSTOMER SECRET FROM MANAGER TEST ACCOUNT PASTED HERE** refresh_token: **REFRESH TOKEN FROM OAUTH PLAYGROUND ON BEHALF OF MANAGER TEST ACCOUNT PASTED HERE** # The following values configure the client for the service account flow. # path_to_private_key_file: INSERT_PATH_TO_JS…
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51303428
type: Question

http://stackoverflow.com/q/51215644
answer count: 0
score: 0
has comment: http://stackoverflow.com/comment/89412472
upvote count: 1
downvote count: 1
has title: Python Unexpected behaviour..while appending to a list class attributes
type: Question
linked to: http://stackoverflow.com/q/2612802
favorite count: 0
duplicate of: http://stackoverflow.com/q/2612802
has comment: http://stackoverflow.com/comment/89420547
has body: I am trying to write recursive code to get all permutations of an array. While appending answer to a list it gives an unexpected answer. Can someone help.. def permute(A): p = [] def permute_util(a,l,r): if l==r: p.append(a) print (a) else: for i in range(l,r+1): a[l],a[i] = a[i],a[l] permute_util(a,l+1,r) a[l],a[i] = a[i],a[l] permute_util(A,0,len(A)-1) print (p) OUTPUT - [1, 2, 3] [1, 3, 2] [2, 1, 3] [2, 3, 1] [3, 2, 1] [3, 1, 2] [[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]] Last line of output is not what i expected.. what am i missing?
type: UnansweredQuestion
tagged with: python
duplicate of: http://stackoverflow.com/q/19354175

http://stackoverflow.com/q/51250759
has comment: http://stackoverflow.com/comment/89483450
answer count: 0
has title: Django - Teplatetag "readmore" wants to be "readless"
type: Question
has comment: http://stackoverflow.com/comment/89675366
has comment: http://stackoverflow.com/comment/89483210
has comment: http://stackoverflow.com/comment/89480546
score: 0
has body: i have written a template tag some time ago which has the feature to collapse a textblock after 15 words. Now i want the exact opposite thing. i want that the user is able to get back to the original 15 words collapsed text after opening the collapsed textblock... i know sounds a bit wired. readmore.py from django import template from django.utils.html import escape from django.utils.safestring import mark_safe register = template.Library() import re readmore_showscript = ''.join([ "this.parentNode.style.display='none';", "this.parentNode.parentNode.getElementsByClassName('more')[0].style.display='inline';", "return false;", ]); @register.filter def readmore(txt, showwords=15): global readmore_showscript words = re.split(r' ', escape(txt)) if len(words) <= showwords: return txt # wrap the more part words.insert(showwords, '') words.append('') # insert the readmore part words.insert(showwords, '... more') words.insert(showwords+3, '') # Wrap with words.insert(0, ' ') words.append(' ') return mark_safe(' '.join(words)) readmore.is_safe = True
tagged with: templatetag
type: UnansweredQuestion
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/89483335

http://stackoverflow.com/q/51277247
has comment: http://stackoverflow.com/comment/89597850
tagged with: machine-learning
has comment: http://stackoverflow.com/comment/89533741
has title: Why do I get different results when training a Keras model when I multiply the loss by a scalar?
tagged with: tensorflow
type: Question
has comment: http://stackoverflow.com/comment/97718559
has comment: http://stackoverflow.com/comment/89532463
has comment: http://stackoverflow.com/comment/89535984
has comment: http://stackoverflow.com/comment/89533729
has comment: http://stackoverflow.com/comment/89538329
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/89533194
tagged with: keras
favorite count: 0
type: UnansweredQuestion
tagged with: python
tagged with: artificial-intelligence
has comment: http://stackoverflow.com/comment/89532282
downvote count: 0
has body: I'd present my model, but I've seen this result across the board. As en example, I'm training a model now where with use straight mse, the loss bottomed out at 0.0160. But when I used 100 * mse, the loss is now shooting down below 0.2, where I would have expected it to bottom out around 1.6. Does anybody have any idea why training Keras models might be sensitive to multiplying losses by scalars? EDIT: And just to clarify, when this has happened to me, the model does end up doing better so it's not just a numerical quirk. EDIT2: I've been asked to provide some example code, so I will. I'm working with using a convolutional variational autoencoder as a generative model. Here is my custom loss function: def vae_loss (input_image, decoder_output): mse_loss = mse(input_image, decoder_output) kl_loss = - 0.5 * (K.mean(1 + z_log_var - K.square(z_mean) - K.exp(z_log_var), axis=[-1,-2,-3])) return mse_loss # (A) #return 100 * mse_loss # (B) I realize that this doesn't use kl_loss, this is just meant as an experiment. I'm compiling the model with: vae.compile(optimizer='adadelta', loss=vae_loss) and fitting with: vae.fit_generator(random_crop(data[:500,:,:,:], 128, 128), validation_data=random_crop(data[500:,:,:,:], 128, 128), shuffle=True, steps_per_epoch=64, epochs=5, validation_steps=50) Using A as the loss function converges to a loss of 0.0160. If using B caused the model to converge to the identical solution (and I would expect it to since multiplying by a scalar doesn't change the location of local minima), I would expect it to converge to a loss of 1.60, 100 times A. But it doesn't. In fact, B does significantly better than A both in terms of loss and in terms of the qualitative products of the network.
has answer: http://stackoverflow.com/a/51278143
score: 1

http://stackoverflow.com/q/51171644
has title: How can I improve this Python 3 code that alternates iterators?
type: Question
has comment: http://stackoverflow.com/comment/89325805
tagged with: python
score: 0
tagged with: refactoring
has comment: http://stackoverflow.com/comment/89325893
answer count: 2
has comment: http://stackoverflow.com/comment/89326058
has comment: http://stackoverflow.com/comment/89325986
has comment: http://stackoverflow.com/comment/89325868
has body: I recently wrote this Python 3 code that is supposed to alternate among all iterables given to it. That is, if the function is given as arguments (first, second, third) then it yields first[0], second[0], third[0], first[1], .... If second runs out before the others, then it is skipped: second[15], third[16], first[16], third[16], ... until all iterables are exhausted. Here it is. It is functional, but it doesn't look very "pythonic". I especially don't like having to keep an array of flags that tell me if the generators are empty. def zipper(*many): iterators = [iter(x) for x in many] iHasItems = [True]*len(iterators) while any(iHasItems): for n, iterator in enumerate(iterators): if iHasItems[n]: try: yield next(iterator) except StopIteration: iHasItems[n] = False
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51175987
has answer: http://stackoverflow.com/a/51171773

http://stackoverflow.com/comment/89343963
score: 1
type: AnswerComment
has text: It would probably be cleaner (and less error prone) to use `.format()` in both cases- for the [Journal] part, and to glue those to the `( OR ` part.
type: Comment
comment on: http://stackoverflow.com/a/51180734

http://stackoverflow.com/q/51310952
has title: PySpark OutOfMemoryErrors when performing many dataframe joins
type: Question
has comment: http://stackoverflow.com/comment/89602033
downvote count: 0
tagged with: pyspark
has comment: http://stackoverflow.com/comment/89603667
has comment: http://stackoverflow.com/comment/89602070
has comment: http://stackoverflow.com/comment/89602621
has answer: http://stackoverflow.com/a/51313008
tagged with: apache-spark
answer count: 1
favorite count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/89599516
has comment: http://stackoverflow.com/comment/89602255
has comment: http://stackoverflow.com/comment/89600989
has comment: http://stackoverflow.com/comment/89600516
tagged with: python
has comment: http://stackoverflow.com/comment/89602840
accepted answer: http://stackoverflow.com/a/51313008
type: AnsweredQuestion
score: 2
has comment: http://stackoverflow.com/comment/89602106
has comment: http://stackoverflow.com/comment/89601823
has body: There's many posts about this issue, but none have answered my question. I'm running into OutOfMemoryErrors in PySpark while attempting to join many different dataframes together. My local machine has 16GB of memory, and I've set my Spark configurations as such: class SparkRawConsumer: def __init__(self, filename, reference_date, FILM_DATA): self.sparkContext = SparkContext(master='local[*]', appName='my_app') SparkContext.setSystemProperty('spark.executor.memory', '3g') SparkContext.setSystemProperty('spark.driver.memory', '15g') There are clearly many, many SO posts about OOM errors in Spark, but basically most of them say to increase your memory properties. I am essentially performing joins from 50-60 smaller dataframes, which have two columns uid, and data_in_the_form_of_lists (usually, it's a list of Python strings). My master dataframe that I am joining on has about 10 columns, but also contains a uid column (that I am joining on). I'm only attempting to join 1,500 rows of data. However, I'll encounter frequent OutOfMemory errors, when clearly all this data can fit into memory. I confirm this by looking in my SparkUI at my Storage: In code, my joins look like this: # lots of computations to read in my dataframe and produce metric1, metric2, metric3, .... metric 50 metrics_df = metrics_df.join( self.sqlContext.createDataFrame(metric1, schema=["uid", "metric1"]), on="uid") metrics_df.count() metrics_df.repartition("gid_value") metrics_df = metrics_df.join( self.sqlContext.createDataFrame(metric2, schema=["uid", "metric2"]), on="gid_value") metrics_df.repartition("gid_value") metrics_df = metrics_df.join( self.sqlContext.createDataFrame(metric3, schema=["uid", "metric3"]), on="uid") metrics_df.count() metrics_df.repartition("gid_value") Where metric1, metric2 and metric3 are RDDs that I convert into dataframes prior to the join (keep in mind there's actually 50 of these smaller metric dfs I am joining). I call metric.count() to force evaluation, since it seemed t…

http://stackoverflow.com/comment/106674080
score: 0
type: Comment
type: QuestionComment
has text: Not your question, but [qypi](https://github.com/jwodder/qypi) looks lke a reasonable alternative to `pip search`: a real query language, json output, well-written doc.
comment on: http://stackoverflow.com/q/51269053

http://stackoverflow.com/q/51288662
answer count: 0
has comment: http://stackoverflow.com/comment/89557855
downvote count: 0
type: UnansweredQuestion
tagged with: garbage-collection
type: Question
score: 3
has comment: http://stackoverflow.com/comment/112606517
has comment: http://stackoverflow.com/comment/89575334
has comment: http://stackoverflow.com/comment/89557266
has comment: http://stackoverflow.com/comment/89556705
has comment: http://stackoverflow.com/comment/89574567
has comment: http://stackoverflow.com/comment/89556436
has body: In Python, I do not understand the order in the garbage collection. Let's take an example with two objects: a context and a task. The task keeps a reference to the context. I thought the task would have been deleted first, but I was wrong. You can see this with the following code: import gc class Context: def __init__(self): self.ptr = 2 def __del__(self): print("remove context (ctx refs: %d)" % len(gc.get_referrers(self))) class Task: def __init__(self, ctx): self.ctx = ctx def __del__(self): print(self.ctx.ptr) print("remove task (ctx refs: %d)" % len(gc.get_referrers(self.ctx))) ctx = Context() t1 = Task(ctx) t2 = Task(ctx) print("ctx refs: %d" % len(gc.get_referrers(ctx))) that gives this output: ctx refs: 3 remove context (ctx refs: 2) 2 remove task (ctx refs: 0) 2 remove task (ctx refs: 0) Why does the reference not force garbage collection of the task first? How can I force garbage collection of the context first? How to explain the number of references?
favorite count: 0
upvote count: 3
has comment: http://stackoverflow.com/comment/89586810
has title: How to force order in garbage collection in Python?
has comment: http://stackoverflow.com/comment/89556249
tagged with: python
has comment: http://stackoverflow.com/comment/89556347
has comment: http://stackoverflow.com/comment/112257323
has comment: http://stackoverflow.com/comment/89559315

http://stackoverflow.com/comment/89633424
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51316418
has text: @ImportanceOfBeingErnest ya I figured out late last night that the problem was `tight_layout`. Thanks!

mfcc
type: Tag
tag name: mfcc
tags question: http://stackoverflow.com/q/51208792

http://stackoverflow.com/comment/89470225
type: QuestionComment
has text: But since this question is more about calculating the precision of a number in decimal points I don't know if I should leave this up.
score: 0
comment on: http://stackoverflow.com/q/51245547
type: Comment

http://stackoverflow.com/comment/89576584
type: QuestionComment
type: Comment
has text: Try importing and then `print(cv2.__file__)`. This will give an idea where cv2 is included from.
score: 0
comment on: http://stackoverflow.com/q/51299207

closures
tags question: http://stackoverflow.com/q/51193517
tag name: closures
type: Tag

http://stackoverflow.com/a/51169833
has comment: http://stackoverflow.com/comment/89333338
has comment: http://stackoverflow.com/comment/89326816
has comment: http://stackoverflow.com/comment/89327029
has comment: http://stackoverflow.com/comment/89327023
has comment: http://stackoverflow.com/comment/89333286
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51169517
has comment: http://stackoverflow.com/comment/89325570
score: 0
has comment: http://stackoverflow.com/comment/89323465
has comment: http://stackoverflow.com/comment/89341671
has comment: http://stackoverflow.com/comment/89327664
has body: I believe need: #aggregate sum by a, b columns df = df.groupby(['a','b'], as_index=False)['c'].sum() print (df) a b c 0 bar one 1 1 baz one 1 2 baz two 3 3 foo one 3 4 foo two 2 #create new column by position with transform sum per a column df.insert(1, 'sum', df.groupby('a')['c'].transform('sum')) #division of columns df['%'] = df['c'].div(df['sum']) print (df) a sum b c % 0 bar 1 one 1 1.00 1 baz 4 one 1 0.25 2 baz 4 two 3 0.75 3 foo 5 one 3 0.60 4 foo 5 two 2 0.40 #sorting by multiple columns and create MultiIndex df = df.sort_values(['sum','c'], ascending=False).set_index(['a','sum','b', 'c']) print (df) % a sum b c foo 5 one 3 0.60 two 2 0.40 baz 4 two 3 0.75 one 1 0.25 bar 1 one 1 1.00
has comment: http://stackoverflow.com/comment/89334039
answers question: http://stackoverflow.com/q/51169517
has comment: http://stackoverflow.com/comment/89326658
type: Answer
has comment: http://stackoverflow.com/comment/89327440
has comment: http://stackoverflow.com/comment/89333936
has comment: http://stackoverflow.com/comment/89323112
has comment: http://stackoverflow.com/comment/89323014
has comment: http://stackoverflow.com/comment/89327546
has comment: http://stackoverflow.com/comment/89328223

http://stackoverflow.com/q/51185254
tagged with: widget
type: UnansweredQuestion
has body: We would like to build a system where the user can compose Jupyter Notebook with whatever logic she needs, but provide additional functionality based on our existing system. To access that additional functionality user will need some help coming from our software. User will use the UI which facilitates composing statements which access our system. For example, to let the user retrieve a variable stored in our system, we need to display list of variables, once user selected a variable - list of keys variable has, so the user could provide values for those keys. We have been looking at NB Extensions in JavaScript and optionally Python backend. JavaScipt would request necessary information via REST, parse provided JSON and fill controls accordingly, no problem with that. However, the user would need to click a button on Toolbar to access that JavaScript dialogs. We came across Widgets which are even more convenient than NB extensions. However, to place a Widget into Jupyter Notebook, user has to provide a code which imports ipywidgets library, creates a widget, populates it with data (speaking about dropdown selector, user would need to call REST service, parse JSON and populate dropdown with items from JSON) and inserts it into the Notebook. Question - can we somehow combine power of NB extensions and Widgets? For example, provide template Jupyter Notebook with single widget saying "select command". Once user made a selection, set of widgets to help composing selected command appears, original "select command" widget disappears, and reappears as the last element in the notebook. No visible code in the notebook related to those widgets must present, all this "magic" must be delivered as some extension.
type: Question
score: 0
has title: Widget in Jupyter Notebook without a code
answer count: 1
tagged with: python
has answer: http://stackoverflow.com/a/51212176
tagged with: jupyter-notebook

http://stackoverflow.com/comment/89387927
type: Comment
comment on: http://stackoverflow.com/a/51189261
has text: sorry, i am new to using this. May I know how should i do that to choose your answer as Best answer
type: AnswerComment
score: 0

http://stackoverflow.com/q/51208570
type: AnsweredQuestion
score: 16
type: Question
has answer: http://stackoverflow.com/a/52806983
has answer: http://stackoverflow.com/a/51208759
has body: I have the following df : import pandas as pd from datetime import datetime, timedelta df = pd.DataFrame([ ["A", "2018-08-03"], ["B", "2018-08-20"] ]) df.columns = ["Item", "Date"] I want to get the first day of the week for every line of my df. I tried to do this : df['Date'] = pd.to_datetime(df['Date'], format='%Y-%m-%d') df["Day_of_Week"] = df.Date.dt.weekday df["First_day_of_the_week"] = df.Date - timedelta(days=df.Day_of_Week) But I got that error message : TypeError: unsupported type for timedelta days component: Series How can I get the first day of the week for a Series ? My expected result is that : "A", "2018-08-03", "2018-07-30" "B", "2018-08-20", "2018-08-20"
tagged with: series
has answer: http://stackoverflow.com/a/51209026
has answer: http://stackoverflow.com/a/73614544
tagged with: pandas
has answer: http://stackoverflow.com/a/51208832
downvote count: 0
answer count: 7
favorite count: 0
possible better answer: http://stackoverflow.com/a/51208832
has answer: http://stackoverflow.com/a/51208677
has answer: http://stackoverflow.com/a/73636959
tagged with: datetime
tagged with: python
upvote count: 16
accepted answer: http://stackoverflow.com/a/51208677
has title: Get the first day of the week for a Pandas series

http://stackoverflow.com/comment/89602208
type: Comment
comment on: http://stackoverflow.com/a/51312201
score: 0
type: AnswerComment
has text: I'm not sure, this sounds like an issue with either A or B. Check datatype maybe? ````for i in gasA['Coor']:print(type(i))````

http://stackoverflow.com/a/59613184
type: Answer
downvote count: 0
score: 1
upvote count: 1
has body: You can use Nanonets OCR api for create your own model that seperates headings and text or you can add different labels.
answers question: http://stackoverflow.com/q/51320121

http://stackoverflow.com/comment/89601708
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/51312300
has text: Your second w in ReleaseKey is lowercase.
type: Comment

http://stackoverflow.com/comment/89404288
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51211409
has text: Are you sure the failure is because the downloaded file doesnt exist, vs. not having permissions on that file or something? You didn't include the code where the deletion happens, not clear to me if you might have a similar try/except there swallowing an OSError or whatnot

http://stackoverflow.com/comment/97603410
comment on: http://stackoverflow.com/q/51313324
has text: yh go for the lower capital one!
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89679103
score: 0
comment on: http://stackoverflow.com/a/51322387
type: Comment
has text: I add sample data :). sorry, for so late.>
type: AnswerComment

http://stackoverflow.com/a/51169828
has body: n = max([len(row) for row in df.tod]) f = lambda l: sum(l, ()) + ('-', np.nan)*(n-len(l)) l = [list(f(row)) for row in df.tod] ndf = pd.DataFrame(l,columns='l1 n1 l2 n2 l3 n3 l4 n4'.split()) # l1 n1 l2 n2 l3 n3 l4 n4 #0 a 10 b 6.0 h 3.0 p 2.0 #1 x 11 e 2.0 l 2.0 - NaN #2 r 5 l 5.0 - NaN - NaN #3 n 15 - NaN - NaN - NaN df.join(ndf) # # tod l1 n1 l2 n2 l3 n3 l4 n4 #0 [(a, 10), (b, 6), (h, 3), (p, 2)] a 10 b 6.0 h 3.0 p 2.0 #1 [(x, 11), (e, 2), (l, 2)] x 11 e 2.0 l 2.0 - NaN #2 [(r, 5), (l, 5)] r 5 l 5.0 - NaN - NaN #3 [(n, 15)] n 15 - NaN - NaN - NaN
answers question: http://stackoverflow.com/q/51169322
score: 0
type: Answer

http://stackoverflow.com/a/51277762
downvote count: 0
answers question: http://stackoverflow.com/q/51277457
accepted answer of: http://stackoverflow.com/q/51277457
type: Answer
has body: You want to use a Union as the value for the dictionary: from typing import Dict, Union @dataclass class TestClass: my_dict: Dict[str, Union[str, bool, int]] The union informs the typechecker that values in the dictionary must be either strs, bools, or ints. When getting values, you'll want to use isinstance to determine what to do with a value: if isinstance(self.my_dict['a'], str): return self.my_dict['a'].encode('utf-8') else isinstance(self.my_dict['a'], bool): return not self.my_dict['a'] else: return self.my_dict['a'] / 10 If you know that a key will contain a specific type, you can avoid the typechecker's complaints by using cast: from typing import cast value = cast(bool, self.my_dict['some_bool'])
score: 4
upvote count: 4
type: AcceptedAnswer

http://stackoverflow.com/a/51328870
has body: The syntax for specifying which columns to use for select() and for drop() slightly different. When you have a period in your column name for select(): same.select('`label.X.L.`') # note the backticks However, when you are attempting to drop: same.drop('label.X.L.') # note the absence of the backticks
type: Answer
accepted answer of: http://stackoverflow.com/q/51253271
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/51253271
upvote count: 2
type: AcceptedAnswer

http://stackoverflow.com/a/51277020
has body: I want my user to make login (Using username and password) and then my application to return a token In this case, what you need is a grant_type=password flow, which can be found at https://docs.authlib.org/en/latest/flask/oauth2.html#resource-owner-password-credentials-grant Understand how it works at: https://www.rfc-editor.org/rfc/rfc6749#section-4.3
answers question: http://stackoverflow.com/q/51276878
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/89555218
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51276878
type: Answer

http://stackoverflow.com/comment/89435687
has text: Did that do the trick?
score: 0
comment on: http://stackoverflow.com/q/51227799
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51309650
has body: You can update in different ways. For example you can create a new ColumnDataSource and update the DataTable source like this: from bokeh.models import ColumnDataSource from bokeh.models.widgets.tables import DataTable, TableColumn from bokeh.models.widgets.buttons import Button from bokeh.layouts import column from bokeh.io import curdoc columns = [ TableColumn(field="x", title="X"), TableColumn(field="y", title="Y"), ] init_source = ColumnDataSource(data=dict(x=[''],y=[''])) table = DataTable( source=init_source, columns=columns, reorderable=False, ) def update_table(): new_source = ColumnDataSource(dict( x=[1, 2, 3, 4, 5, 6], y=[1, 2, 3, 4, 5, 6], )) table.source.data = new_source.data bt = Button( label="Update Table", button_type="success", width=50 ) bt.on_click(update_table) curdoc().add_root(column(children=[table, bt])) Launch this file with bokeh serve --show filepath/file.py. You can use a DataFrame as CDS argument like this: ColumnDataSource(df) in order to create the CDS.
upvote count: 1
has comment: http://stackoverflow.com/comment/124930296
answers question: http://stackoverflow.com/q/51309023
has comment: http://stackoverflow.com/comment/124957291
type: Answer
downvote count: 0
score: 1

http://stackoverflow.com/q/51304016
linked to: http://stackoverflow.com/q/16204076
has answer: http://stackoverflow.com/a/51316815
has body: I access a deeply nested dictionary and want to break very long lines properly. Let's assume I have this and want to break the line to conform with PEP8. (The actual line is of course longer, this is just an example.) some_dict['foo']['bar']['baz'] = 1 How would you break the line, assuming the whole some_dict['foo']['bar']['baz'] does not fit on one line anymore? There are a lot of examples for breaking long lines, but I couldn't find one for this dictionary access based question. Update: Please note that I want to assign something to that dictionary. The proposed duplicate only talks about getting a value from that kind of dictionary.
answer count: 2
has answer: http://stackoverflow.com/a/51320514
tagged with: pep8
has title: Break very long lines with access to deeply nested dictionaries
downvote count: 0
favorite count: 0
upvote count: 8
has comment: http://stackoverflow.com/comment/89599580
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/89584712
score: 8
accepted answer: http://stackoverflow.com/a/51320514
type: AnsweredQuestion
type: Question
has comment: http://stackoverflow.com/comment/89584702
possible better answer: http://stackoverflow.com/a/51316815

http://stackoverflow.com/comment/89348064
has text: df[df.home_team_Belgium==1]
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51182801
type: Comment

http://stackoverflow.com/q/51287258
has comment: http://stackoverflow.com/comment/89552332
tagged with: stanford-nlp
score: 10
tagged with: google-colaboratory
has body: I want to use Stanford CoreNLP in my Google Colab Notebook. For that I need Java. Is there a way to install Java on those machines? What I currently have is: !pip install StanfordCoreNLP from stanfordcorenlp import StanfordCoreNLP nlp = StanfordCoreNLP('stanford-corenlp', lang='de', memory='4g') ... nlp.close() and I get the error: FileNotFoundError: [Errno 2] No such file or directory: 'java': 'java'
has title: How can I use Java in Google Colab
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/51775653
favorite count: 0
accepted answer: http://stackoverflow.com/a/51775653
tagged with: python
type: AnsweredQuestion
tagged with: java
has comment: http://stackoverflow.com/comment/89556333
upvote count: 10
type: Question

http://stackoverflow.com/q/51170893
tagged with: numpy
has answer: http://stackoverflow.com/a/51173230
has comment: http://stackoverflow.com/comment/89335566
type: UnansweredQuestion
favorite count: 0
type: Question
has body: I have a question concerning the speed of loops in Python. I created the following loops to fill values in my array, but it is very slow. Is there a way to make it process faster ? winW = 1 winH = 200 runlength = np.zeros(shape=(img.shape[0], img.shape[1])) for y in range(0, img.shape[0] - winH, 1): for x in range(0, img.shape[1] - winW, 1): runlength[y, x] += np.sum(img[y:y + winH, x:x + winW]) / (winH * winW) runlength[y + winH, x] += np.sum(img[y:y + winH, x:x + winW]) / (winH * winW) Thanks for your help Edit : I precise that I can only use numpy but not scipy
has comment: http://stackoverflow.com/comment/89326642
has comment: http://stackoverflow.com/comment/89324506
answer count: 2
has answer: http://stackoverflow.com/a/51172397
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/89325930
downvote count: 1
has comment: http://stackoverflow.com/comment/89327155
tagged with: performance
score: 0
tagged with: loops
has title: python loops very slow

http://stackoverflow.com/comment/89630169
score: 0
type: AnswerComment
type: Comment
has text: Yes. The (potentially high) cost of building the trie is amortized across all the subsequent searches. Potentially, if your program will only ever search for the same large list of suffixes, you can generate a JSON of the trie and deploy it with your program, meaning there's no start up cost for the end user beyond reading a file.
comment on: http://stackoverflow.com/a/51296069

http://stackoverflow.com/comment/89435585
type: Comment
type: QuestionComment
score: 0
has text: @AntonvBR updated my question to include the entire script.
comment on: http://stackoverflow.com/q/51227784

http://stackoverflow.com/q/51246724
score: 0
has comment: http://stackoverflow.com/comment/89472220
upvote count: 1
has title: write csv to external file
has answer: http://stackoverflow.com/a/51246761
answer count: 1
downvote count: 1
favorite count: 0
tagged with: python
type: AnsweredQuestion
type: Question
accepted answer: http://stackoverflow.com/a/51246761
has body: It seemed that I do not understand how csv.write works. Any hint will be very helpful. When I write: x=['1468853914','2016-07-18 12:04:56.2 UTC', '0','970.157'] import csv myFile = open('csvexample4.csv', 'w') writer = csv.writer(myFile, delimiter=',') writer.writerows(x) I expect to get a comma delimited csv file with one line as follows '1468853914','2016-07-18 12:04:56.2 UTC', '0','970.157' but I get 1,4,6,8,8,5,3,9,1,4 2,0,1,6,-,0,7,-,1,8, ,1,2,:,0,4,:,5,6,.,2, ,U,T,C 0 9,7,0,.,1,5,7
has comment: http://stackoverflow.com/comment/89472356
tagged with: python-2.7

http://stackoverflow.com/comment/89569606
type: QuestionComment
type: Comment
has text: It's no use to pass in the casted tuple into the endswith because I need to retrieve the match when it exists. As for the short-circuit I might actually try that. About the tree I just couldn't make it look good in my head. And yes I can manipulate quite freely all the strings before processing them, reversing or sorting them inside the list is ok. Also cast the list back and forth from list to tuples and sets if needed.
comment on: http://stackoverflow.com/q/51295864
score: 0

http://stackoverflow.com/comment/89508582
type: Comment
type: QuestionComment
has text: Your code looks good. Can you show debug output?
comment on: http://stackoverflow.com/q/51264283
score: 0

http://stackoverflow.com/comment/89535014
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51267907
has text: "RX processed" looks pretty perfect to me?

http://stackoverflow.com/comment/98980681
has text: @MatthewMeeker one use case for this would be for continuous integration where multiple environments are created on the fly. In a similar vein to what tox is used for.
comment on: http://stackoverflow.com/a/51288126
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/89557541
type: AnswerComment
has text: This looks great. I will try it. Actually, this is a legacy project with existing database data (and some `Bar`s deleted), so changing the field to a foreign key may not be the best idea. Thanks, by the way.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51289680

http://stackoverflow.com/comment/89412097
type: AnswerComment
comment on: http://stackoverflow.com/a/51214754
type: Comment
has text: Looks like you can get libxml2 here http://www.xmlsoft.org/downloads.html and libxslt here http://xmlsoft.org/libxslt/downloads.html.
score: 0

http://stackoverflow.com/a/51292731
type: Answer
accepted answer of: http://stackoverflow.com/q/51292186
downvote count: 0
answers question: http://stackoverflow.com/q/51292186
score: 6
has comment: http://stackoverflow.com/comment/89563412
upvote count: 6
has comment: http://stackoverflow.com/comment/89563341
has body: Flask test client is a test client used to test what will happen in the user side when you do a request to the endpoint. The reason why pytest doesn't and should not catch the exception is that the error happens on server side, user should not have a server side exception. Instead, to test your QueryParseException is correctly raised in server side, you can assert the status code of client.post('/helper'). Meanwhile, in server side, you can give the error message and status code to let the client know what's wrong.
type: AcceptedAnswer

http://stackoverflow.com/comment/89611194
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51317225
score: 0
has text: Do you get any error in `console` for your browser?

http://stackoverflow.com/q/51301913
type: AnsweredQuestion
has title: How to pass exchange FileAttachments to pd.read_excel?
type: Question
accepted answer: http://stackoverflow.com/a/51594483
score: 0
tagged with: pandas
answer count: 1
tagged with: exchangelib
has answer: http://stackoverflow.com/a/51594483
tagged with: python
has body: I have created a filter with exchangelib to get multiple emails containing .xlsx-files. The next step should be to put into one pd.DataFrame. While I'm trying to pd.read_excel() when i'm iterating over the filter, i'm not able to pass the attachment.content into the pd.read_excel. I have tried with several combinations like pd.read_excel(attachment.content), pd.read_excel(open(attachment.content,'rb')). See below for my last try with io.BytesIO: import pandas as pd import exchangelib from exchangelib import EWSTimeZone,EWSDateTime,FileAttachment,HTMLBody import datetime from dateutil.parser import parse from ipywidgets import interact from ipywidgets import interact_manual import io def get_outages(filterstart,filterende,location): credentials = exchangelib.Credentials('my.user@provider.com', 'passwd') account = exchangelib.Account('my.user@provider.com', credentials=credentials, autodiscover=True) tz = EWSTimeZone.localzone() myfolder_delay = account.inbox/'Delay' outages=pd.DataFrame filterstart=datetime.datetime.strptime(filterstart,"%d.%m.%Y %H:%M") filterende=datetime.datetime.strptime(filterende,"%d.%m.%Y %H:%M") #filterstart=filterstart+datetime.timedelta(hours=1) filterende=filterende+datetime.timedelta(hours=1) filter = myfolder_delay.filter(datetime_received__range=tz.localize(EWSDateTime(filterstart.year, filterstart.month, filterstart.day, filterstart.hour, filterstart.minute)), tz.localize(EWSDateTime(filterende.year, filterende.month, filterende.day, filterende.hour, filterende.minute)))) for item in filter: print(item.subject) for attachment in item.attachments: stream_str = io.BytesIO(attachment.content) outages=pd.read_excel(stream_str.getvalue(),engine='xlrd') interact_manual(get_outages, filterstart='11.07.2018 00:00', filterende='11.07.2018 23:59',location='Location') **ValueError** . . . ~\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\io\excel.py in __init__(self, io, **kwds) 394 self.book = xlrd.open_workbook(self._io) 395 else: --…

http://stackoverflow.com/comment/89431376
type: QuestionComment
has text: @roganjosh numpy arrays do not print as `l = [ '1' '2' '3' ]` - do they? - also: the OP speaks of `list`, tagged [tag:list] and not numpy - I am happy to remove my DV if he adjusts his question to something that is solveable.
comment on: http://stackoverflow.com/q/51225456
score: 0
type: Comment

http://stackoverflow.com/comment/89509559
comment on: http://stackoverflow.com/a/51265755
score: 0
type: AnswerComment
type: Comment
has text: You might want to add that you can easily combine them: `list(string.ascii_lowercase + string.ascii_uppercase + string.digits)`

http://stackoverflow.com/comment/89530387
type: AnswerComment
has text: @lukayl You explicitly state in your question, in the screenshot details, that "each colour indicates one productId". Can you clarify how the output above is not your desired result?
type: Comment
comment on: http://stackoverflow.com/a/51273056
score: 0

http://stackoverflow.com/a/51200933
accepted answer of: http://stackoverflow.com/q/51200849
type: Answer
answers question: http://stackoverflow.com/q/51200849
has comment: http://stackoverflow.com/comment/89398671
has body: This can be done with the help of groupby and product: data = [["blue", 1], ["blue", 3], ["red", 6], ["green", 5]] groups = [] for k, g in itertools.groupby(data, key=lambda item: item[0]): groups.append(list(g)) print(list(itertools.product(*groups))) # [(['blue', 1], ['red', 6], ['green', 5]), (['blue', 3], ['red', 6], ['green', 5])] # just for understanding how it works: print(groups) # [[['blue', 1], ['blue', 3]], 'red', 6, 'green', 5]
score: 0
type: AcceptedAnswer

http://stackoverflow.com/comment/110607849
score: 1
type: AnswerComment
type: Comment
has text: Things have changed since 2018 :) I have updated the code (not the plot though). It's much simpler now.
comment on: http://stackoverflow.com/a/51439172

http://stackoverflow.com/comment/89348263
comment on: http://stackoverflow.com/a/51183108
has text: what is your desired result? `q q` matches for `(.+) \1` and your code would print the output `1` if you left it as `\1`
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/51195225
tagged with: python
favorite count: 0
has title: How count the frequency in categorical variables in python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89372075
upvote count: 0
score: -1
has body: I have a problem, I'm trying count the frequency of categorical data: If for example, I get: I want to get Any idea?
type: Question
has answer: http://stackoverflow.com/a/51195358
has comment: http://stackoverflow.com/comment/89372059
has comment: http://stackoverflow.com/comment/89372060
answer count: 1
downvote count: 1

signal-processing
tags question: http://stackoverflow.com/q/51267907
type: Tag
tags question: http://stackoverflow.com/q/51297531
tags question: http://stackoverflow.com/q/51194727
tags question: http://stackoverflow.com/q/51258394
tags question: http://stackoverflow.com/q/51182265
tags question: http://stackoverflow.com/q/51257961
tag name: signal-processing
tags question: http://stackoverflow.com/q/51312923
tags question: http://stackoverflow.com/q/51241499

http://stackoverflow.com/q/51248306
answer count: 2
has answer: http://stackoverflow.com/a/51248380
has body: Slightly new to Python here. I currently have a list of nested lists. I am trying to label each sublist starting from 0-25. However, if two sublists are the same, they should have the same label. For example: label_list = [['AH0'], ['AA1', 'K', 'S'], ['AH0', 'N', 'T'], ['AA1', 'K', 'S'], ['IH0', 'N'], ['AA1', 'K', 'S']] The output should be [0, 1, 2, 1, 4, 1] since the second, fourth, and sixth sublists are the same. The rest of the sublists should just be labelled in consecutive numeric order. I know i need to use a loop but I am quite stuck, anyone have any advice on how to approach this? Thank you.
has comment: http://stackoverflow.com/comment/89475659
has title: How to label matching items in a nested list in Python
score: 0
has comment: http://stackoverflow.com/comment/89477827
tagged with: nested
tagged with: python
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51250654
tagged with: list
tagged with: loops
has comment: http://stackoverflow.com/comment/89478007
type: Question

http://stackoverflow.com/a/57483325
has comment: http://stackoverflow.com/comment/101438801
has body: list=[1,2,3,4,5,6,7,8,9,10] print('Initial List with 10 Element:') print(list) for i in range(0, len(list), 2): list[i]=0 print('After replacing new element in the odd place:') print(list) list.append(16) list.append(17) list.append(18) print('List after adding three element at the end') print(list) list.insert(0,100) print('List after adding one element at the beginning:') print(list) list.extend([20,21,23,24,25]) print('List after adding new list to the existing one:') print(list)
score: -1
upvote count: 0
has comment: http://stackoverflow.com/comment/101438270
answers question: http://stackoverflow.com/q/51225456
type: Answer
downvote count: 1

http://stackoverflow.com/comment/89637137
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51319254
has text: Okay, So i have added those lowercase codes to my dictionary and it's working all fine! Btw, I have finished my whole code today and it's unbelievably 170-odd lines of script. This is quite shocking yet mesmerizing for someone who is just 2 months old in Python. If you are up for it, shall we look into it and try to optimize the code, because I feel this would be adding to much to the RAM. I am already trying it, but would be really glad if I have a mentor with me , cause I am trying my best at it.
score: 0

http://stackoverflow.com/a/51175021
has comment: http://stackoverflow.com/comment/89339304
type: AcceptedAnswer
type: Answer
upvote count: 12
downvote count: 0
has comment: http://stackoverflow.com/comment/89332917
accepted answer of: http://stackoverflow.com/q/51174718
has body: Just create migrations folder the folder again, then create __init__.py file. After that run manage.py makemigrations
answers question: http://stackoverflow.com/q/51174718
has comment: http://stackoverflow.com/comment/89361308
score: 12

http://stackoverflow.com/comment/89343087
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51180293
has text: `lambda x: (...)`. But it's not clear to me what output you were expecting.

http://stackoverflow.com/comment/89333812
has text: Mr python, if your problem is solved and you choose an answer as helpful, you can vote them up, however in order for you and the ansewrer to recieve reputation you should click the check mark in the answer you choose. I have seen lots of people wasting reputation for themselves and others by not checking answers
score: 0
comment on: http://stackoverflow.com/q/51175336
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51281765
has comment: http://stackoverflow.com/comment/89541070
has body: you can try this: import inspect current_frame = inspect.currentframe() current_frame.f_back.f_globals['__file__'] this will get the __file__ global from the function that called your function
has comment: http://stackoverflow.com/comment/89541091
type: Answer
has comment: http://stackoverflow.com/comment/89542491
answers question: http://stackoverflow.com/q/51281619
has comment: http://stackoverflow.com/comment/89542239
score: 0

http://stackoverflow.com/comment/89342596
score: 1
type: Comment
has text: @SuperMouette yup although be careful, one vertex in obj can have two VT in different face which isn't the case of an opengl vertex and it's attributes. You'd need to duplicate some vertices.
comment on: http://stackoverflow.com/a/51173723
type: AnswerComment

deserialization
type: Tag
tags question: http://stackoverflow.com/q/51194708
tag name: deserialization

http://stackoverflow.com/comment/115977082
has text: in settings.py you needed to replace 'oscar.apps.shipping.apps.ShippingConfig', with this 'apps.shipping.apps.ShippingConfig', after forking
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51265182

http://stackoverflow.com/comment/89474516
has text: Thanks a lot! Really helped.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51225928
type: Comment

http://stackoverflow.com/comment/89645921
comment on: http://stackoverflow.com/q/51317270
type: Comment
has text: Thank's @Marcus.Aurelianus for the link! As Mad Physicist mentioned i think we have only pointers to string objects in the list. Anyway the id function that you mentioned helped me grasp information i didn't know about python. I mentioned one them in my comment to Mad Physicist answer.
score: 0
type: QuestionComment

http://stackoverflow.com/comment/89477936
has text: You can also use `print(..., file=f)` and it will handle the newlines etc
type: AnswerComment
type: Comment
score: 2
comment on: http://stackoverflow.com/a/51249496

http://stackoverflow.com/q/51174653
type: Question
tagged with: python
favorite count: 0
score: -1
has answer: http://stackoverflow.com/a/51174909
answer count: 2
has comment: http://stackoverflow.com/comment/89332106
downvote count: 1
has title: Append in python with split
upvote count: 0
has comment: http://stackoverflow.com/comment/89332324
type: UnansweredQuestion
has body: What's wrong with this code? It displays the following error: EOFError : EOF when reading a line n,K = map(int,input().split()) arr = [] count = 0 for i in range(0,n): arr.append(input().split()) print(arr)
has answer: http://stackoverflow.com/a/51175613

http://stackoverflow.com/q/51219088
tagged with: data-extraction
has comment: http://stackoverflow.com/comment/89419255
has answer: http://stackoverflow.com/a/51219101
type: Question
has body: I would like to locate this data from a page source "location": {"latitude": 35.4677026, "longitude": -80.6093396} currently I am running this code floats = re.findall(r"[-+]?\d+\.\d+", str(soup)) for i in range(len(floats)): if len(floats[i]) &gt; 9: LatLong.append(floats[i]) The output has the data I am looking for, but it also has data I don't want with it mixed in
score: 0
answer count: 1
tagged with: string
tagged with: beautifulsoup
has comment: http://stackoverflow.com/comment/89419337
accepted answer: http://stackoverflow.com/a/51219101
has title: How do I locate string and integer data in python
tagged with: python
type: AnsweredQuestion

search-engine
type: Tag
tag name: search-engine
tags question: http://stackoverflow.com/q/51203408

http://stackoverflow.com/q/51275544
favorite count: 0
tagged with: upgrade
tagged with: python
has comment: http://stackoverflow.com/comment/89552345
has comment: http://stackoverflow.com/comment/89556092
tagged with: internationalization
accepted answer: http://stackoverflow.com/a/51289105
type: AnsweredQuestion
tagged with: python-3.x
has title: Django 2.0 Internationalization | i18n_patterns not working
upvote count: 2
tagged with: django
type: Question
has body: I have been working with i18n so that the URL included the prefix "/en/" or "/es/" depending on the users preferred language. So far it was working fine while using Django 1.9 it even placed automatically the prefix even when the user didn't submit it in the URL (i.e. mySite.com would redirect to mySite.com/en/). Now that I upgraded to 2.0 it is not working and it shows a 404 error: Using the URLconf defined in smce.urls, Django tried these URL patterns, in this order: en/ ^static/(?P.*)$ ^images/(?P.*)$ The empty path didn't match any of these. At my root urls.py i have: urlpatterns = i18n_patterns( path('admin/', admin.site.urls), path('login/', anonymous_required(views.login), {'template_name': 'login.html', 'authentication_form': LoginForm}, name='login'), path('', include('matrix.urls'), name='matrix'), ) Any help or guidance would be appreciated.
has comment: http://stackoverflow.com/comment/89542249
has answer: http://stackoverflow.com/a/51289105
score: 2
answer count: 1
downvote count: 0

http://stackoverflow.com/comment/89507713
type: Comment
type: QuestionComment
has text: I think need `ANSWER = groupby('Quarters').mean()`
comment on: http://stackoverflow.com/q/51262904
score: 0

http://stackoverflow.com/comment/89585051
score: 0
has text: Got it to work thx! But now I still have another issue: the original image in predominantly blue (as shown in the edited question). I tried putting the colormap to RGB but it says it doesn't exists and gives me a possible list of values, don't know which one to pick for the right correction though :/
type: AnswerComment
comment on: http://stackoverflow.com/a/51303980
type: Comment

http://stackoverflow.com/q/51273382
accepted answer: http://stackoverflow.com/a/51277622
favorite count: 0
tagged with: xpath
has body: I am scraping a table of meeting times. One of the columns holds a meeting status and a link to agenda, if any. I can pull the cells using the following: Scrapy Shell: things = response.xpath('//tbody/tr') for thing in things: ...: status_str = item.xpath('.//td[4]').extract() ...: print(status_str) Shell Results: [' Agenda '] [' Meeting postponed '] [' Agenda '] [' Postponed '] [' Agenda '] [' Agenda '] [' Agenda '] I can successfully choose the a/text() or the text(), but I'd like to choose both. How do I do this?
has comment: http://stackoverflow.com/comment/89531178
upvote count: 1
tagged with: scrapy
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/51273483
has title: Scrapy xpath choose both regular text and link text
has answer: http://stackoverflow.com/a/51277622
type: Question
possible better answer: http://stackoverflow.com/a/51273483
downvote count: 0
has answer: http://stackoverflow.com/a/51275705
answer count: 3
has comment: http://stackoverflow.com/comment/89525094
tagged with: python

http://stackoverflow.com/a/51236494
score: 3
upvote count: 3
has body: Your root problem seems to be that you think your drawBoard function is converting draw from a 1D array to a 2D array. But it's not. All it does is print out a 2D array representation of draw, not changing the values at all. At the end of it, you still have just a plain old flat list. And trying to zip(*…) to transpose a 1D array (a list of numbers) makes no sense. If you had a 2D array (a list of lists of numbers), it would make sense. And you think you have a 2D array, which is why you're confused by your code not working. So, the obvious solution is to make yourself a list of lists to work with. If you want a function that makes the board into a list of lists, you have to write one—but that's easy. See this question for a variety of ways to chunk or group a list's elements, and pick the one you like. Then: def makeSquare(lst): width = int(len(lst) ** .5) if width * width != len(lst): raise ValueError('List length must be a perfect square') return list(chunkifier_that_you_chose(lst, width)) Now, you can use it as a 2D array, making all of the rest of your code a whole lot simpler: board = makeSquare(data) def drawBoard(board): for row in board: for col in row: print(col, end = ' ') print() drawBoard(board) flippedBoard = zip(*board[::-1]) drawBoard(flippedBoard) If you really want to keep the list flat, but flip it with zip(*…), you can squarify it, flip it, then flatten it again: board = makeSquare(data) flippedBoard = zip(*board[::-1]) flat = [col for row in flippedBoard for col in row] As a side note, since you keep talking about arrays, and trying to use your lists as arrays, have you considered using NumPy? Even if you wanted to keep everything flat for some reason, NumPy lets you get a reshaped view of the same data (without copying anything around, just making a new "viewer" handle), which you can operate on a lot more easily: import numpy as np data = np.array(data) data.reshape(4, 4) # as a 2D array data.reshape(4, 4)[::-1] # reversed data.reshape(4, 4)[:…
has comment: http://stackoverflow.com/comment/89452114
has comment: http://stackoverflow.com/comment/89452033
downvote count: 0
answers question: http://stackoverflow.com/q/51236398
has comment: http://stackoverflow.com/comment/89452106
type: Answer

http://stackoverflow.com/a/51315953
accepted answer of: http://stackoverflow.com/q/51315809
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89645495
score: 0
has comment: http://stackoverflow.com/comment/89645637
has body: So the result of "print(imagePath) is: C:\Users\Sam\OneDrive\Desktop\RateData\1\'1.1.jpg Almost certainly, you don't have a file named '1.1.jpg in the RateData directory. While Windows does allow apostrophe/single-quote characters in filenames, I can't imagine you would have used one there intentionally. So, it's probably named 1.1.jpg? I'm also not sure how you got that string out of that code… but never mind that. You're making this all a lot harder than it has to be. There's no need to worry about getting path separators escaped and quoted properly, or whatever you were trying to do. Python comes with the os.path module for doing path-related operations. So just use it: for feature in features[0]: imagePath = os.path.join(one, str(feature)) img = cv2.imread(imagePath) print(imagePath) print(img) Or, since I'd bet feature is already a string, even simpler: imagePath = os.path.join(one, feature) Or, if you prefer a more object-oriented API, Python also comes with pathlib: one = pathlib.Path(one) for feature in features[0]: imagePath = one / feature img = cv2.imread(str(imagePath)) print(imagePath) print(img) I don't know if cv2 is pathlib-aware, but if it is, you can just do cv2.imread(imagePath). (If you want to use pathlib, definitely try that and see, because it's obviously more readable.)
has comment: http://stackoverflow.com/comment/89645602
type: Answer
has comment: http://stackoverflow.com/comment/89645836
has comment: http://stackoverflow.com/comment/89645557
answers question: http://stackoverflow.com/q/51315809
has comment: http://stackoverflow.com/comment/89645860
has comment: http://stackoverflow.com/comment/89646107
has comment: http://stackoverflow.com/comment/89645468

http://stackoverflow.com/a/51207101
upvote count: 2
has body: You can do the following: array = [1, 2, 3, 4, 5] new_array = [9] + array[:-1] Result: [9, 1, 2, 3, 4] array[:-1] means: take all items in array except the last one. By adding this to a list containing only the number 9, you get the result you want.
answers question: http://stackoverflow.com/q/51207005
type: Answer
score: 2
downvote count: 0

http://stackoverflow.com/comment/89580740
score: 2
comment on: http://stackoverflow.com/a/51301399
type: AnswerComment
type: Comment
has text: yes this is exactly what I mentioned in my answer. You can either select 2 or do PCA for example to reduce to 2 dimensions and then use the projected data (reduced dimemensions = 2) to feed them in the SVM and finally plot the decision surface. Do you want me to update my answer using PCA?

http://stackoverflow.com/a/51195036
score: 3
upvote count: 3
type: Answer
has body: To draw the picture of the car instead of a rectangle, just do the same thing that you are doing with the man. Under the line that is manImg = pygame.image.load('skater1.png'), put this line: carImg= pygame.image.load('taxi.png') This will load the picture of the car and it will be called carImg. Now, you need to draw that picture onto the screen. Replace your objects function: def objects(objectx, objecty, objectw, objecth, color): pygame.draw.rect(gameDisplay, color, [objectx, objecty, objectw, objecth]) with a function to draw a car. def drawCar(x,y): pygameDisplay.blit(carImg,(x,y)) Notice how it is very similar to the man function, the only difference is the image that is drawn. The last thing you need to do is actually call that drawCar function. Replace this line objects(object_startx, object_starty, object_width, object_height, cyan) with this one: drawCar(object_startx,object_starty) I would recommend doing these changes yourself, it will help you learn. But if you're in a hurry, the final code, with all of these changes made, should be: import pygame import time import random pygame.init() skate_sound = pygame.mixer.Sound("skateboard.wav") pygame.mixer.music.load("menu_audio.wav") ouch = pygame.mixer.Sound("ouch.wav") display_width = 800 display_height = 600 black = (0,0,0) white = (255,255,255) red = (255,0,0) cyan = (71, 148, 192) green = (0, 255, 0) dark_red = (200, 0 ,0) dark_green = (0, 180 ,0) grass_green = (39, 131, 51) man_width = 35 gameDisplay = pygame.display.set_mode((display_width,display_height)) pygame.display.set_caption('Skate or Die') clock = pygame.time.Clock() manImg = pygame.image.load('skater1.png') carImg= pygame.image.load('taxi.png') def objects_dodged(count): font = pygame.font.SysFont(None, 25) text = font.render("Dodged: "+str(count), True, black) gameDisplay.blit(text, (0,0)) def drawCar(x,y): pygameDisplay.blit(carImg,(x,y)) def man(x,y): gameDisplay.blit(manImg,(x,y)) def text_objects(text, font): textSurface = font.render(te…
downvote count: 0
answers question: http://stackoverflow.com/q/51190354
has comment: http://stackoverflow.com/comment/89383410

http://stackoverflow.com/comment/89439582
comment on: http://stackoverflow.com/a/51227106
type: AnswerComment
score: 0
type: Comment
has text: @S.Known Did you bother clicking on any of provided alternatives for decompiling? Did you read its documentation? Did you search for "decompiling a directory of pyc files"? Have you heard of using `*` as wildcard?

http://stackoverflow.com/comment/89556018
type: QuestionComment
has text: Got it. It was because I was using is instead of ==.
score: 1
comment on: http://stackoverflow.com/q/51288184
type: Comment

file-io
tags question: http://stackoverflow.com/q/51181505
tags question: http://stackoverflow.com/q/51198258
type: Tag
tags question: http://stackoverflow.com/q/51276848
tags question: http://stackoverflow.com/q/51260128
tag name: file-io
tags question: http://stackoverflow.com/q/51255950

http://stackoverflow.com/comment/89570606
type: Comment
has text: @SuperStew I suppose the reason for us starting/attempting to do this using python is because that is a potential solution that we found. Do you have an alternative? I am certainly open to it!
comment on: http://stackoverflow.com/q/51294646
score: 0
type: QuestionComment

http://stackoverflow.com/a/51266927
type: Answer
score: 0
answers question: http://stackoverflow.com/q/51266718
has body: Your method make_frame is actually returning None in two of the cases (which is the reason why you are getting None) if frame &lt; birthframe: return None if frame &gt; deathframe: return None If you don't want to see None just return something else in those cases (like an empty string '')

http://stackoverflow.com/a/51268652
has body: You can use pd.Series.dt.year followed by pd.Series.unique. Timings on Python 3.6 / Pandas 0.19 below using data from @Engineero. %timeit df['time'].dt.year.unique().tolist() # 739 µs per loop %timeit df['time'].apply(lambda x: x.year).unique().tolist() # 5.9 ms per loop %timeit list(set(df['time'].dt.year.values)) # 823 µs per loop
upvote count: 8
type: Answer
accepted answer of: http://stackoverflow.com/q/51268370
score: 7
downvote count: 1
answers question: http://stackoverflow.com/q/51268370
type: AcceptedAnswer

http://stackoverflow.com/comment/89578214
type: Comment
comment on: http://stackoverflow.com/a/51279994
has text: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/174864/discussion-between-qwww-and-jezrael).
type: AnswerComment
score: 0

http://stackoverflow.com/comment/89425756
type: AnswerComment
type: Comment
has text: Thank you for the link and for your comment. I am having a little trouble understanding why there is a problem or where it lives. The process seems somewhat straight forward....read from both files, break them into an array of arrays. Construct a new array of arrays. and delete. Perhaps you can pull out the relevant subset of your code and the "old" and "new" data files and share a github link? That way, we can look at the code and see the bug with the right context.
comment on: http://stackoverflow.com/a/51178676
score: 0

http://stackoverflow.com/q/51245394
has title: Setting values of a list to a list of dataframes
upvote count: 1
has body: Scenario: I have 2 lists, one is a list of strings with names, the other is a list of dataframes with varied content. I am trying to put the values from the first list into the second. Data Example: list1 = ['jan18', 'feb18', 'mar18', 'apr18', 'may18'] List two is a list of dataframes with the following structure: DF1_LIST2: row1 row2 row3 row4 5 55 12 3 51 11 3 52 11 9 59 11 DF2_LIST2: row1 row2 row3 row4 9 91 7 5 1 23 3 24 56 9 68 21 My objective is to add the first element of list1 to all cells in the first column of the first dataframe of list2; then the second element of list2 to all cells of the first column of the second dataframe of list 2, and so on. The output would be something like: DF1_LIST2: row1 row2 row3 row4 jan18 5 55 12 jan18 3 51 11 jan18 3 52 11 jan18 9 59 11 DF2_LIST2: row1 row2 row3 row4 feb18 9 91 7 feb18 5 1 23 feb18 3 24 56 feb18 9 68 21 What I got so far was trying to establish a triple for loop, the first iterates over items of list1, the second over dataframes of list2 and the third over rows of each dataframe: import pandas as pd import os from os import listdir from os.path import isfile, join import glob # Get File Names mypath = "//DGMS/Desktop/uploaded" onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))] # Get dates onlyfiles = [name.split("_")[0] for name in onlyfiles] df_of_names = pd.DataFrame(onlyfiles) # Get File Contents all_files = glob.glob(os.path.join(mypath, "*.xls*")) contentdataframes = [pd.read_excel(f) for f in all_files] for dfs in contentdataframes: dfs.insert(0,"date*","") dfs.insert(1,"apply*","") for date in onlyfiles: for dfs in contentdataframes: for row in dfs.itertuples(index=True): dfs.set_value(row,0,date) This gives me an error, I believe because of the header column, which still counts as a normal row, not an index. Question: Is there a proper way to do this?
has comment: http://stackoverflow.com/comment/89469418
favorite count: 0
has comment: http://stackoverflow.com/comment/89469395
tagged with: pandas
has comment: http://stackoverflow.com/comment/89469347
has answer: http://stackoverflow.com/a/51245557
has comment: http://stackoverflow.com/comment/89469463
tagged with: python
tagged with: filepath
type: AnsweredQuestion
downvote count: 0
score: 1
tagged with: dataframe
type: Question
has comment: http://stackoverflow.com/comment/89469530
has answer: http://stackoverflow.com/a/51245477
possible better answer: http://stackoverflow.com/a/51245557
accepted answer: http://stackoverflow.com/a/51245477
answer count: 2

http://stackoverflow.com/q/51186448
tagged with: python
score: 1
type: Question
upvote count: 2
has answer: http://stackoverflow.com/a/51187338
tagged with: keras
has comment: http://stackoverflow.com/comment/89355965
has answer: http://stackoverflow.com/a/55250831
answer count: 2
has body: I am trying to use google colab! But I keep running into the problem with keras where it says: AttributeError: module 'keras.engine' has no attribute 'input_layer' However, checking their github library, there is a input_layer.py within keras/engine. Also, this works locally, just not on google colab. Any ideas?
has title: AttributeError: module 'keras.engine' has no attribute 'input_layer'
downvote count: 1
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89355988

http://stackoverflow.com/a/51195404
has body: This is going to be lengthy and with the assumption that all the zip codes will have the same length after appending a 0 at the beginning. import pandas as pd import numpy as np t1 = pd.DataFrame({'id':[1,2,3,4], 'zip_code':['0234','0345','3456','4567']}) t2 = pd.DataFrame({'id2':[5,6,7,8], 'zip_code':['234','0345','3456','4567']}) t2['lens'] = t2.zip_code.apply(len) t2.loc[:,'zip_code'] = np.where(t2.lens&lt;4,'0'+t2['zip_code'].astype(str),t2['zip_code']) input t1: id zip_code 0 1 0234 1 2 0345 2 3 3456 3 4 4567 Input t2: id2 zip_code 0 5 234 1 6 0345 2 7 3456 3 8 4567 Output t2: id2 zip_code lens 0 5 0234 3 1 6 0345 4 2 7 3456 4 3 8 4567 4 you can delete the lens column if you don't need it afterwards. Now you can join the two dataframes t1 and t2 using zip_code.
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/51195001
downvote count: 0
score: 1

http://stackoverflow.com/q/51176688
answer count: 3
downvote count: 0
has title: Join 2 dataframes and create Parent Child Relationship?
has body: i have 2 dataframes parent and child, i want to concatenate both in groupby manner df_parent parent parent_value 0 Super Sun 0 1 Alpha Mars 4 2 Pluto 9 df_child child value 0 Planet Sun 100 1 one Sun direction 101 2 Ice Pluto Tune 101 3 Life on Mars 99 4 Mars Robot 105 5 Sun Twins 200 I want the ouput to be in order order = ['Sun', 'Pluto', 'Mars'] Sun -childs Pluto -childs Mards -childs I want to find the child with keyword wise, refer parent_dict parent_dict = {'Super Sun': 'Sun', 'Alpha Mars': 'Mars', 'Pluto': 'Pluto'} expected output child value 0 Super Sun 0 # parent 1 Planet Sun 100 # child 2 one Sun direction 101 # child 3 Sun Twins 200 # child 4 Pluto 9 # parent 5 Ice Pluto Tune 101 # child 6 Alpha Mars 4 # parent 7 Life on Mars 99 # child 8 Mars Robot 105 # child So far i have tried to iterate master list and both dfs, but expected output is not coming, here is my code output_df = pd.DataFrame() for o in order: key = o for j, row in df_parent.iterrows(): if key in row[0]: output_df.at[j, 'parent'] = key output_df.at[j, 'value'] = row[1] for k, row1 in df_child.iterrows(): if key in row1[0]: output_df.at[j, 'parent'] = key output_df.at[j, 'value'] = row[1] print(output_df) Output: parent value 0 Sun 0.0 2 Pluto 9.0 1 Mars 4.0
has answer: http://stackoverflow.com/a/51177011
has answer: http://stackoverflow.com/a/51178861
favorite count: 0
tagged with: pandas
tagged with: python
has comment: http://stackoverflow.com/comment/89336285
has answer: http://stackoverflow.com/a/51177602
has comment: http://stackoverflow.com/comment/89336299
type: UnansweredQuestion
upvote count: 1
type: Question
score: 1

google-fusion-tables
type: Tag
tags question: http://stackoverflow.com/q/51249981
tag name: google-fusion-tables

vertica
tag name: vertica
tags question: http://stackoverflow.com/q/51260504
type: Tag

http://stackoverflow.com/q/51223780
type: Question
accepted answer: http://stackoverflow.com/a/51223792
has comment: http://stackoverflow.com/comment/89428021
possible better answer: http://stackoverflow.com/a/51223847
upvote count: 3
answer count: 2
has answer: http://stackoverflow.com/a/51223792
has title: Python 3 Decimal precision
favorite count: 0
tagged with: python-3.x
tagged with: python
has answer: http://stackoverflow.com/a/51223847
type: AnsweredQuestion
score: 3
downvote count: 0
has body: I have an issue with floating-point numbers: a = 0.4812 b = 0.4813 a-b -9.999999999998899e-05 a = Decimal(0.4812) b = Decimal(0.4813) a-b Decimal('-0.000099999999999988986587595718447118997573852539062500') How can I get exactly -0.0001?
tagged with: floating-point

http://stackoverflow.com/comment/89437925
comment on: http://stackoverflow.com/q/51229013
score: 0
has text: The problem may just be that you’re trying to run it from inside PyCharm. If you run it in a normal Terminal window, does it work?
type: Comment
type: QuestionComment

python-module-unicodedata
tags question: http://stackoverflow.com/q/51186075
type: Tag
tag name: python-module-unicodedata

http://stackoverflow.com/comment/89364739
type: QuestionComment
comment on: http://stackoverflow.com/q/51190182
has text: Indeed this should be `R = np.array(['ab', 'bc', 'c'])` .see my answer. cheers.
score: 0
type: Comment

http://stackoverflow.com/a/57783953
score: -1
has body: Just open file: venv/lib/python3.7/site-packages/django/contrib/admin/widgets.py and replace the lines related_url += '?' + '&amp;amp;'.join( '%s=%s' % (k, v) for k, v in params.items(),) with related_url += '?' + '&amp;amp;'.join('%s=%s' % (k, v) for k, v in params.items())
answers question: http://stackoverflow.com/q/51265858
type: Answer
upvote count: 2
has comment: http://stackoverflow.com/comment/102002045
downvote count: 3
has comment: http://stackoverflow.com/comment/103078971

http://stackoverflow.com/comment/89434319
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51217876
has text: actually i did update `pip` after getting conda errors. Initially i wasnt getting errors while updating , my connection disconnect multiple times when after that upon updating i get these errors. After getting these error - I updated pip though. Is there any way to clean the corrupted packages using anaconda
score: 0

http://stackoverflow.com/q/51174403
type: Question
answer count: 1
tagged with: terminal
score: 0
tagged with: python
tagged with: command
type: UnansweredQuestion
has title: Starting a netcat listener in new terminal window from python script
has body: Total python noob here but trying to learn I am trying to launch a new terminal window which is running a netcat listener on port 7777 from a python script. I have tried... import os netcat = '--command \"nc -nvlp 7777\"' print ("Starting listener on port 7777") from subprocess import call call(['xfce4-terminal', netcat]) and from subprocess import call call(['xfce4-terminal', '--command', '"nc -nvlp 7777"')] but no dice. The second example will actually launch the terminal and look for a command, but doesn't execute the netcat "argument". This seems to be caused by the fact that using --command requires my netcat argument to be surrounded by quotes. Thanks in advance for all help
has answer: http://stackoverflow.com/a/51208598

http://stackoverflow.com/q/51240863
downvote count: 0
favorite count: 0
has title: Python SQlite select query returning list instead of integer
has comment: http://stackoverflow.com/comment/89460876
has comment: http://stackoverflow.com/comment/89460581
has comment: http://stackoverflow.com/comment/89460600
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/89460712
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51241035
score: 1
type: Question
accepted answer: http://stackoverflow.com/a/51241035
has body: I have a function to query DB and return a value like below def find_dase(Plants): conn = sqlite3.connect("dexro.db") cursor = conn.cursor() cursor.execute(("SELECT Years FROM Plants_no WHERE Plant=?"),(Plants,)) data = cursor.fetchall() conn.close() return data when i execute this i am getting a list instead of the value print(find_dase('dex')) print(type(find_dase('dex'))) Output: [('10',)] &lt;class 'list'&gt; How can i fetch only the integer value
has comment: http://stackoverflow.com/comment/89460655
tagged with: sqlite
answer count: 1

http://stackoverflow.com/a/58476133
has comment: http://stackoverflow.com/comment/114222300
has comment: http://stackoverflow.com/comment/116869663
downvote count: 0
type: Answer
has body: This solution may be helpful for Windows users. pip uninstall jupyter Go to ~\AppData\Roaming (AppData is a hidden file) and delete the folder named jupyter and python(if there exists.) Delete ~\.jupyter, ~\.ipython. pip install jupyter I was using Jupiter without anaconda and this perfectly fixed the issue. Not sure if this works for Jupiter with anaconda. I used this trick it worked for me, I also use Jupiter without Anaconda.
upvote count: 2
answers question: http://stackoverflow.com/q/51204683
score: 2

http://stackoverflow.com/comment/89598082
type: Comment
has text: Now I guess the dataset and the expected output is clear?
type: QuestionComment
comment on: http://stackoverflow.com/q/51302668
score: 0

http://stackoverflow.com/comment/89600465
score: 0
type: AnswerComment
has text: This is not what I have discovered from other resources so far. Like https://stackoverflow.com/questions/22589868/call-python-code-from-c-via-cython. But I think it's just my code is not working and there might be a solution for it.
comment on: http://stackoverflow.com/a/51311567
type: Comment

http://stackoverflow.com/comment/89395707
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/51205868
has text: Actually, not quite correct. The target still is the function `myProcess` but it cannot be pickled from your module due to the fact that `__main__.myProcess` is the process at the point you call `start()`.

http://stackoverflow.com/q/51323622
has answer: http://stackoverflow.com/a/51323761
tagged with: python
type: UnansweredQuestion
tagged with: oop
type: Question
linked to: http://stackoverflow.com/q/1841565
answer count: 2
has body: I'm a beginner trying to improve my Python skills. I've found a very similar question to mine but since the source code was different, it did no benefit. Here is the link for the question: ValueError: invalid literal for int() with base 10: &#39;&#39; Anyways, here is my code: correct_answer= 41 guess = int(input("Guess the number")) if int(input()) == correct_answer: print ("You found my number!") if int (input()) &gt;= correct_answer: print ("My number is lower.") if int (input()) &lt;= correct_answer: print ("My number is higher.") else: print ("You didn't write any numbers!") Here, I wanted to write a simple guessing game. The number computer has in mind is 41, and the user has to guess the number after "Guess the number". If the input of a user is greater than 41, the program says "My number is lower" and if the input is smaller than 41, the program says "My number is greater." When I run this code, I get the "ValueError: invalid literal for int() with base 10: '' Thank you in advance for helping me solve this problem :)
has answer: http://stackoverflow.com/a/51323693
has title: Why do I get "ValueError: invalid literal for int() with base 10". in this Python code?
has comment: http://stackoverflow.com/comment/89622348
score: 0

http://stackoverflow.com/a/58764690
type: Answer
score: 33
answers question: http://stackoverflow.com/q/51297102
has comment: http://stackoverflow.com/comment/138093396
upvote count: 33
has comment: http://stackoverflow.com/comment/119102097
has body: Edit Configurations -> Allow parallel run. Done
downvote count: 0

http://stackoverflow.com/q/51247419
has comment: http://stackoverflow.com/comment/89545058
has answer: http://stackoverflow.com/a/51708891
type: Question
has comment: http://stackoverflow.com/comment/89479026
linked to: http://stackoverflow.com/q/4830856
downvote count: 0
answer count: 1
linked to: http://stackoverflow.com/q/14850853
has comment: http://stackoverflow.com/comment/89495615
has body: I would like to use my own package located in private repository. Actually, i use requirements.txt file to install dependencies in my Python AppEngine. However, i don't understand where do I have to add my private dependency. Thanks
has comment: http://stackoverflow.com/comment/89495578
has comment: http://stackoverflow.com/comment/123162937
favorite count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: google-app-engine
tagged with: pip
tagged with: python
has title: Use private repository for Python in Google App Engine
score: 2
has comment: http://stackoverflow.com/comment/89483902

http://stackoverflow.com/q/51168640
downvote count: 0
has title: Pandas:How to convert date format %Y-%M-%D into %Y%M%D?
type: AnsweredQuestion
tagged with: format-conversion
score: 3
tagged with: dataframe
possible better answer: http://stackoverflow.com/a/51168682
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/51168669
has answer: http://stackoverflow.com/a/51168682
accepted answer: http://stackoverflow.com/a/51168669
upvote count: 3
tagged with: pandas
has body: I have a dataframe, which can be shown as follows: Input import pandas as pd df=pd.DataFrame({'time':['2018-07-04','2018-04-03',]}) print('df\n',df) Output time 0 2018-07-04 1 2018-04-03 Expected time 0 20180704 1 20180403
tagged with: datetime
tagged with: python
favorite count: 0

http://stackoverflow.com/q/51305432
tagged with: python
has body: Is it possible to use pandas INSIDE a greenplum database, and if so how? I am inside greenplum. I am creating a function with: CREATE OR REPLACE FUNCTION myfunction() RETURNS text AS $$ ... python code ... rv = plpy.execute("SELECT * FROM mytable") ... $$ LANGUAGE plpythonu; SELECT public.myfunction() The command rv = plpy.execute("SELECT * FROM mytable") generates an object of type PlyResult. At this point, I want to analyze the data in rv with python pandas, for instance. How can I convert rv to a dataframe? Thank you!
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/53760004
answer count: 2
tagged with: pandas
has title: Greenplum pandas dataframe integration in plpython procedure (from INSIDE the database)
downvote count: 0
score: 1
tagged with: greenplum
tagged with: server-side
favorite count: 0
has answer: http://stackoverflow.com/a/51905544
tagged with: postgresql
type: UnansweredQuestion

http://stackoverflow.com/q/51170574
answer count: 1
has body: Is there a built-in aggregate function in Python? Example code: def aggregate(iterable, f, *args): if len(args) == 1: accumulator = args[0] elif len(args) == 0: accumulator = None else: raise Exception("Invalid accumulator") for i, item in enumerate(iterable): if i == 0 and accumulator == None: accumulator = item else: accumulator = f(accumulator, item) return accumulator if __name__ == "__main__": l = range(10) s1 = aggregate(l, lambda s, x : s+x) print(s1) s2 = aggregate(l, lambda s, x : "{}, {}".format(s, x)) print(s2) s3 = aggregate(l, lambda s, x: [x] + s, list()) print(s3) Output: 45 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/89323983
downvote count: 0
has title: Built in aggregate function in python
tagged with: aggregate
type: UnansweredQuestion
type: Question
score: 2
has comment: http://stackoverflow.com/comment/89323852
has answer: http://stackoverflow.com/a/51170723
upvote count: 2

http://stackoverflow.com/comment/89491700
comment on: http://stackoverflow.com/q/51256297
score: 0
has text: @RafaelC Yes, it did throw that warning! I edited the question to include a portion of the input and output.
type: QuestionComment
type: Comment

http://stackoverflow.com/a/51183397
score: 1
type: AcceptedAnswer
downvote count: 0
has body: Suppose you have data like this: data = { "list1": [[100, 101, 102], [110, 111, 112], [120, 121, 123]], "list2": [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], "list3": [[200, 201, 202], [210, 211, 212], [220, 221, 223]], } If it is homework, your teacher probably want you to solve it using recursion, but I recommend using an iterative version in Python unless you can assure you would not stack more than 999 calls: fetch_element(data, listname, *indices): value = data[listname] for index in indices: value = value[index] return value Then you have the list of elements you want: desired = [ ["list1", 0, 0], ["list2", 7], ["list3", 2, 2], ] Now you can do: &gt;&gt;&gt; [fetch_element(data, *line) for line in desired] [100, 7, 223] Which is the same as: &gt;&gt;&gt; [data["list1"][0][0], data["list2"][7], data["list3"][2][2]] [100, 7, 223]
type: Answer
has comment: http://stackoverflow.com/comment/89358423
upvote count: 1
accepted answer of: http://stackoverflow.com/q/51180906
answers question: http://stackoverflow.com/q/51180906

kivy-language
type: Tag
tags question: http://stackoverflow.com/q/51313098
tag name: kivy-language

http://stackoverflow.com/comment/89546168
has text: on what base you have to arrange the order of words ?
type: AnswerComment
type: Comment
score: 0
comment on: http://stackoverflow.com/a/51283383

http://stackoverflow.com/comment/89366646
score: 0
type: Comment
type: QuestionComment
has text: Hi! thank you for the fast reply. I just edited the Question
comment on: http://stackoverflow.com/q/51167506

http://stackoverflow.com/q/51198485
upvote count: 2
type: UnansweredQuestion
downvote count: 2
tagged with: python
has title: How do you use a list as an index argument for numpy ndarrays?
has body: So I have a problem that might be super duper simple. I have these numpy ndarrays that I allocated and want to assign values to them via indices returned as lists. It might be easier if I showed you some example code. The questionable code I have is at the bottom, and in my testing (before actually taking this to scale) I keep getting syntax errors :'( EDIT: edited to make it easier to troubleshoot and put some example code at the bottoms import numpy as np def do_stuff(index, mask): # this is where the calculations are made magic = sum(mask) return index, magic def foo(full_index, comparison_dims, *xargs): # I have this function executed in Parallel since I'm using a machine with 36 nodes per core, and can access upto 16 cores for each script #blessed # figure out how many dimensions there are, and how big they are parent_dims = [] parent_diffs = [] for j in xargs: parent_dims += [len(j)] parent_diffs += [j[1] - j[0]] # this is used to find a mask index = [] # this is where the individual dimension indices will be stored dim_n = 0 # loop through the dimensions while dim_n &lt; len(parent_dims): dim_index = full_index % parent_dims[dim_n] index += [dim_index] if dim_n == 0: mask = (comparison_dims[dim_n] &gt; xargs[dim_n][dim_index] - parent_diffs[dim_n]/2) * \ (comparison_dims[dim_n] &lt;= xargs[dim_n][dim_index] +parent_diffs[dim_n] / 2) else: mask *= (comparison_dims[dim_n] &gt; xargs[dim_n][dim_index] - parent_diffs[dim_n]/2) * \ (comparison_dims[dim_n] &lt;=xargs[dim_n][dim_index] + parent_diffs[dim_n] / 2) full_index //= parent_dims[dim_n] dim_n += 1 return do_stuff(index, mask) def bar(comparison_dims, *xargs): if len(xargs) == comparison_dims.shape[0]: pass elif len(comparison_dims.shape) == 2: pass else: raise ValueError("silly person, you failed") from joblib import Parallel, delayed dims = [] for j in xargs: dims += [len(j)] myArray = np.empty(tuple(dims)) results = Parallel(n_jobs=1)( delayed(foo)( index, comparison_dims, *xargs) for index in range(np.pr…
has comment: http://stackoverflow.com/comment/89379611
score: 0
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/89378835
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/51199126

http://stackoverflow.com/a/51287668
has comment: http://stackoverflow.com/comment/89553068
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/89553314
accepted answer of: http://stackoverflow.com/q/51287522
has body: The nonlocal checks the nearest enclosing scope, excluding globals (that is, module level variables). That is, your f() function should declare a x for it to work, as nonlocal can't see the global x = 100 variable. See https://docs.python.org/3/reference/simple_stmts.html#the-global-statement. As to why the error is raised without running the function, it is because the variable names are bound at compile-time, so it doesn't matter that you don't use this function at all. See https://docs.python.org/3/reference/executionmodel.html#resolution-of-names However, global has different behaviour. Just like nonlocal if the global x already exists, it is used instead of the local one. However, if it doesn't, it means "if I create a variable named x, create it on the global scope, instead of the function scope". So, in your example x = 100 def f(): global x global xx x = 99 xx = 123 return x print(f()) # 99 print(x) # 99 print(xx) # 123 a xx variable has appeared in the global namespace. It is only a hint to the compiler though, so if you declared global xx without assigning it, and try to print(xx) later, you still get a NameError for using an undefined variable
answers question: http://stackoverflow.com/q/51287522
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/89553951
has comment: http://stackoverflow.com/comment/89554351
has comment: http://stackoverflow.com/comment/89553751
has comment: http://stackoverflow.com/comment/89553896
type: Answer
has comment: http://stackoverflow.com/comment/89554146
has comment: http://stackoverflow.com/comment/89552918

http://stackoverflow.com/a/51316426
type: Answer
answers question: http://stackoverflow.com/q/51316106
score: 0
has body: @csevier Right on! It was an import error. Thank you! First I got the absolute path in the python console for the ClassName using : import os import ClassName os.path.abspath(ClassName.file) After that, I added the following code just before load : import sys sys.path.append('path/to/ClassName')

http://stackoverflow.com/q/51244636
favorite count: 0
downvote count: 0
has body: I am trying to create a function that takes a set of observed and expected data points, determines the optimum function for calibration and applies this calibration on the whole data set (from which the data points are a subset). However, I want to ensure that the polynomial function that is fitted by either scipy.optimize.curve_fit or numpy.polyfitis monotonic (first derivative doesn't change sign). The current test code that I have for this is below: #! /usr/bin/env python from scipy.optimize import curve_fit import matplotlib.pyplot as plt import numpy as np import math import sys import random random.seed(28) ############# # Test Data # ############# measuredMaximaMZ = [100.0, 201.0, 222.0, 401.0, 500.0] presentCalibrants = [100.5, 200.5, 300.5, 400.5, 500.5] Fake_Raw_X = np.linspace(100,500,1000) Fake_Raw_Y = random.sample(xrange(100000), 1000) ############# # Functions # ############# def powerLaw(x,a,b,c): penalty = 0 if b &gt; 2.: penalty = abs(b-1.)*10000 if b &lt; 0.: penalty = abs(2.-b)*10000 return a*x**b + c + penalty class powerLawCall: def __init__(self,x,a,b,c): self.a = a self.b = b self.c = c self.f = lambda x: a*x**b+c def __call__(self,x): return self.f(x) def describe(self): return str(self.a)+"*X^"+str(self.b)+"+"+str(self.c) def performCalibration(measured, expected): RMS = sys.maxint func = None # Power Law z = curve_fit(powerLaw, measured, expected) RMS_buffer = [] for index, i in enumerate(measured): RMS_buffer.append((powerLaw(i,*z[0])-expected[index])**2) RMS_buffer = np.mean(RMS_buffer) RMS_buffer = math.sqrt(RMS_buffer) if RMS_buffer &lt; RMS: RMS = RMS_buffer func = powerLawCall(0,*z[0]) # Polynomials between 1 and len(expected) for i in range(1,len(expected)): RMS_buffer = [] z = np.polyfit(measured, expected, i) f = np.poly1d(z) for index, j in enumerate(measured): RMS_buffer.append((f(j) - expected[index])**2) RMS_buffer = np.mean(RMS_buffer) RMS_buffer = math.sqrt(RMS_buffer) if RMS_buffer &lt; RMS: RMS = RMS_buffer func = f return…
type: UnansweredQuestion
has title: Limit curve_fit or polyfit to monotone functions
tagged with: scipy
type: Question
score: 1
linked to: http://stackoverflow.com/q/16760788
has answer: http://stackoverflow.com/a/51255306
upvote count: 1
has comment: http://stackoverflow.com/comment/89505763
answer count: 1
tagged with: polynomials
tagged with: curve-fitting
tagged with: python
has comment: http://stackoverflow.com/comment/89468606

http://stackoverflow.com/q/51272418
favorite count: 0
has answer: http://stackoverflow.com/a/51272499
tagged with: python
tagged with: subprocess
type: UnansweredQuestion
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/51276578
has title: QPlainTextEdit: subprocess segmentation fault using threads
type: Question
has answer: http://stackoverflow.com/a/51272590
tagged with: pyside
has body: Segmentation Fault in subprocess.stdout while displaying on QPlainTextEdit Hi, I am starting a thread to the function shown and streaming its result to a QTextEdit object in the thread. The function sometimes crashes with a segmentation fault for unknown reasons. self.plainTextEdit = QPlainTextEdit() self.thread = Thread(target = runcmd, args = ("make dc",)) self.thread.start() self.thread.join() def runcmd(self,cmd): process = subprocess.Popen(shlex.split(cmd),stdout=subprocess.PIPE, bufsize=-1) while True: line = process.stdout.readline() if not line: break self.plainTextEdit.moveCursor(QTextCursor.End) self.plainTextEdit.insertPlainText(line.strip()) process.terminate() The make dc command is a call to the design compiler synthesis tool. If I try to print the line variable instead of writing to the plainTextEdit Object the thread runs fine, displaying the result in the terminal window. Any help/advice is welcome...... Thank You
answer count: 3
tagged with: pyqt
downvote count: 0
tagged with: segmentation-fault

http://stackoverflow.com/q/51254834
tagged with: python
answer count: 4
has answer: http://stackoverflow.com/a/51255216
score: 2
upvote count: 2
type: UnansweredQuestion
tagged with: bin
tagged with: count
has title: Pandas Dataframe: Count and Bin integers and datetime into ranges producing two output dataframes
type: Question
has answer: http://stackoverflow.com/a/51255323
has comment: http://stackoverflow.com/comment/89488860
has body: I have the Following Dataframe: ID Minutes Datetime 1 30 6/4/2018 23:47:00 2 420 3 433 6/10/2018 2:50 4 580 6/9/2018 3:10 5 1020 I want to count the number of times the Minutes occur between a certain range. I want to do a similar count for datetime field (timestamp falls within certain range of time). Below is the output I want: MIN_RANGE COUNT 6-8 hours 2 8-10 hours 1 10-12 hours 0 12-14 hours 0 14-16 hours 0 16+ hours 1 RANGE COUNT 8pm - 10pm 0 10pm - 12am 1 12am - 2am 0 2am-4am 2 4am-6am 0 6am-8am 0 8am -10am 0 10am - 12pm 0 12pm - 2pm 0 2pm - 4pm 0 4pm - 6pm 0 6pm - 8pm 0 I have searched around google and stackoverflow on how to do this (searching bins and stuff) but couldn't find anything directly related to what I am trying to do. Help?
has answer: http://stackoverflow.com/a/51255959
has answer: http://stackoverflow.com/a/51255275
downvote count: 0
tagged with: label
favorite count: 0
tagged with: pandas

http://stackoverflow.com/q/51275555
tagged with: python
score: -2
has answer: http://stackoverflow.com/a/51275729
tagged with: file
type: Question
has comment: http://stackoverflow.com/comment/89574431
has body: I have a file in which date field in YYYYMMDD format. I need to pick that date and product to join with another file by subtracting 12 months to get other information. File1 20180131,Apple 20180228,Orange 20180331,Grapes File2 20170131,Apple,45 20170131,Orange,20 20170228,Orange,35 20170331,Apple,25 Output 20180131,Apple,45 20180228,Orange,35 20180331,Grapes,null How to subtract 12 months or 1 year from given date(yyyymmdd) and get the answer in the same format.
upvote count: 0
tagged with: date
has comment: http://stackoverflow.com/comment/89529017
has comment: http://stackoverflow.com/comment/89574414
answer count: 1
favorite count: 0
has title: Subtract a year from given date (not current time) in python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89592681
downvote count: 2

http://stackoverflow.com/comment/89560301
type: QuestionComment
score: 3
comment on: http://stackoverflow.com/q/51291281
type: Comment
has text: You should include what you've tried so we can try to address you problem more effectively.

http://stackoverflow.com/comment/89328369
has text: Ok, sorry, i'm new here. Will do next time
type: Comment
comment on: http://stackoverflow.com/q/51171367
score: 0
type: QuestionComment

http://stackoverflow.com/a/51236071
type: Answer
accepted answer of: http://stackoverflow.com/q/51235924
score: 1
upvote count: 1
has body: Alt1: You could do it with two masks (conditions). This should be readable and make sense. m1 = (df.gender == 'male') m2 = (df.gender.duplicated()) df.loc[m1&amp;m2, 'score'] = 0 Alt2: Slice away the first truth value of the nonzero mask (requires import numpy as np). This should be faster. m = np.nonzero(df.gender=='male')[0][1:] df.loc[m, 'score'] = 0 Full example: import pandas as pd import numpy as np df = pd.DataFrame({ 'gender': ['male','female','male','female','male'], 'score': 34 }) m1 = (df.gender == 'male') m2 = (df.gender.duplicated()) m = np.nonzero(df.gender=='male')[0][1:] df.loc[m, 'score'] = 0 print(df) Returns: gender score 0 male 34 1 female 34 2 male 0 3 female 34 4 male 0
answers question: http://stackoverflow.com/q/51235924
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/89539197
type: QuestionComment
comment on: http://stackoverflow.com/q/51257116
score: 0
has text: You are choosing Chi-squared as the scoring when you write: `SelectKBest(chi2, k=1)`. Are you asking what chi-squared is?
type: Comment

audacity
type: Tag
tags question: http://stackoverflow.com/q/51321355
tag name: audacity

http://stackoverflow.com/a/51228544
answers question: http://stackoverflow.com/q/51228465
type: Answer
accepted answer of: http://stackoverflow.com/q/51228465
score: 3
has body: BeautifulSoup supports CSS selectors which allow you to select elements based on the content of particular attributes. This includes the selector *= for contains. import requests as req from bs4 import BeautifulSoup url = req.get( 'https://www.racingnsw.com.au/media-news-premierships/latest-news/') data = url.content soup = BeautifulSoup(data, "html.parser") for items in soup.select('a[class*="_self"]'): print(items)
upvote count: 3
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/89604890
comment on: http://stackoverflow.com/a/51302419
score: 0
type: Comment
has text: I tried to do the same for another value (nom2 = 2nd author) but it didn't work because nom2 is an indexed value: `nom2 = art['authFullName_s'][1]` I tried this: `print(nom, ', ' if len(nom2)!=0 else "", vol if len(nom2)!=0 else "", ', ', tit, '. ', jou, '.', dat, '. Pubmed: ' if len(pbm)!=0 else "", pbm if len(pbm)!=0 else "", sep="") ` @Reaganrewop
type: AnswerComment

http://stackoverflow.com/q/51212367
has body: I discovered that there is ALTabletService methods that is not listed on the official Aldebaran ALTabletService API. For example if you initialize: tabletService = self.session().service("ALTabletService") then you can call: tabletService._installApk("path_to_apk") tabletService._uninstallApps() tabletService._stopApk("package_name") tabletService._openSettings() How can I the list of all "private" methods the AL serices? I guess I can find the binaries and then I can try to decompile the files, but I suppose there is an easier way to do that.
favorite count: 0
possible better answer: http://stackoverflow.com/a/51233167
has answer: http://stackoverflow.com/a/51233167
has answer: http://stackoverflow.com/a/51493622
accepted answer: http://stackoverflow.com/a/51493622
tagged with: python
score: 2
type: AnsweredQuestion
downvote count: 0
type: Question
has title: How can I list all hidden methods for ALTabletService and the other services?
tagged with: pepper
upvote count: 2
answer count: 2
tagged with: nao-robot

http://stackoverflow.com/comment/89480257
has text: it seems like both `x, y = 0, x + 1` and `y, x = x+1, 0` throws an error?
comment on: http://stackoverflow.com/q/51250570
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/q/51235186
has answer: http://stackoverflow.com/a/51244235
type: Question
tagged with: python-3.5
answer count: 1
has comment: http://stackoverflow.com/comment/89460337
has comment: http://stackoverflow.com/comment/89464798
favorite count: 0
has comment: http://stackoverflow.com/comment/89466796
has body: I'd like to include Python.h (from the Python distribution in my Anaconda folder) in my project to call a python script. The program compiles fine when I don't include python. But as soon as I do, I get undefined reference errors to functions implemented in Qt classes (so not my own functions!). The python version I'd like to include is 3.5.5. The part that confuses me most is undefined reference to QJsonValue::toString(). This method is implemented inline so how can its implementation not be found? According to QtCreator the problem originates in a compiled object that tries to call this function. This is a minimally (not) working example: The .pro file: QT -= gui CONFIG += c++11 console no_keywords SOURCES += main.cpp INCLUDEPATH += {path to python include} LIBS += -L{path to python lib} -lpython3.5m And the main.cpp file: #include &lt;Python.h&gt; #include &lt;QCoreApplication&gt; #include &lt;QJsonValue&gt; int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); PyObject *obj; QJsonValue value; value.toString(); return a.exec(); } Update: It seems like including Python from Anaconda is causing the issue. When I remove LIBS += -L{path to python lib} -lpython3.5m it compiles just fine. And when I remove INCLUDEPATH += {path to python include} but keep the other line I get the following error: /{user}/build-TestProject-Qt_5_9-Debug/TestProject: /{user}/anaconda3/lib/libQt5Core.so.5: version `Qt_5.9' not found (required by /{user}/build-TestProject-Qt_5_9-Debug/TestProject)
upvote count: 3
has comment: http://stackoverflow.com/comment/89466425
has comment: http://stackoverflow.com/comment/89466022
tagged with: python
has comment: http://stackoverflow.com/comment/89466711
tagged with: c++
has comment: http://stackoverflow.com/comment/89457495
downvote count: 0
accepted answer: http://stackoverflow.com/a/51244235
tagged with: qt
type: AnsweredQuestion
score: 3
tagged with: anaconda
linked to: http://stackoverflow.com/q/48398899
has title: Including Python.h in Qt application causes undefined reference to Qt functions

http://stackoverflow.com/q/51317225
has body: Just some context: I took over my live website from my developer recently, I have some basic coding knowledge but I'm not very proficient. I tried adding a 'purchase_type' attribute to the Product model, but the new attribute is not showing up in the admin dashboard even after making migrations. When I query the database however, the attribute is there and returns the right value. 1. Added 'purchase_type' to models.py: class Product(models.Model): index_number = models.IntegerField(default=None, blank=True, null=True) name = models.CharField(max_length=500, blank=True, null=True) coming_soon = models.BooleanField(default=False) retail_price = models.DecimalField(max_digits=100, decimal_places=2, default=None, null=True) calories = models.IntegerField(default=None, blank=True, null=True) protein_class = models.CharField(max_length=500, blank=True, null=True) carb_class = models.CharField(max_length=500, blank=True, null=True) fat_class = models.CharField(max_length=500, blank=True, null=True) purchase_type = models.CharField(max_length=500, default="Subscription") 2. Added 'purchase_type' into the fieldsets in admin.py: class ProductAdmin(admin.ModelAdmin): list_display = ("name", "index_number", "coming_soon", "retail_price", "calories", "protein_class", "carb_class", "fat_class") search_fields = ("name",) list_filter = ("protein_class", "carb_class", "fat_class") ordering = ("index_number",) fieldsets = ( ("Main Info", { "fields": ("index_number", "name", "coming_soon", "retail_price", "calories", "protein_class", "carb_class", "fat_class", "purchase_type"), }), 3. Ran the following commmands in running order: ./manage.py migrate ./manage.py makemigrations webapp ./manage.py migrate 4. When I query the database for purchase_type, the correct value is returned: ./manage.py shell from webapp.models import Product &gt;&gt;&gt; print(Product.objects.values('purchase_type')) [{'purchase_type': u'Subscription'}, {'purchase_type': u'Subscription'}, {'purchase_type': u'Sub…
favorite count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89611194
tagged with: mysql
tagged with: django
upvote count: 1
has comment: http://stackoverflow.com/comment/89614100
has comment: http://stackoverflow.com/comment/89614014
type: Question
has comment: http://stackoverflow.com/comment/89614020
score: 1
has comment: http://stackoverflow.com/comment/89610795
has title: Django new attribute not up showing in admin dashboard after making migrations
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/51318403

http://stackoverflow.com/a/51217143
has comment: http://stackoverflow.com/comment/89415939
accepted answer of: http://stackoverflow.com/q/51217028
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89415595
type: Answer
has comment: http://stackoverflow.com/comment/89415560
score: 3
upvote count: 3
has body: output must be a string, right? That's why 'port 1.1' in output is True when it's actually 'port 1.16'. So you could simply divide it in a list and check if the number of the port is in it: matches = {x for x in port_list if x.split()[1] in output.split()} No need to use regex ;) Edit: x.split() divides the string in a list. Each division is on a space. So the result of it is ['port', '1.16']. We use the [1] index notation to specify the object on index 1 (python index start on 0) - '1.16'. That way, we're checking if the number is on the list of words on output.
answers question: http://stackoverflow.com/q/51217028
downvote count: 0

http://stackoverflow.com/comment/89648355
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/51323838
type: Comment
has text: @praveen - yes, only change `2` to `2000`

http://stackoverflow.com/q/51257802
tagged with: python
answer count: 0
has title: To check the status of relay using interrupt in raspberry pi
upvote count: 1
type: Question
downvote count: 0
tagged with: raspberry-pi3
score: 1
favorite count: 0
has body: I am working with a raspberry pi with a relay with the incandescent bulb, buzzer, and button via SSH. The code is in a way that when I press a key from the keyboard the bulb and buzzer should be ON and when I press button both should get OFF. But my button code is not working properly. And also I want to check the status of the relay using the interrupt and whenever the light on it should be sent a message to the database. But I don't know with interrupts. Below is my code. Please help me. Thanks in advance import RPi.GPIO as GPIO import time in1 = 25 #GPIO25 pin22 buzzer=24 #GPIO24 PIN18 led=8 #GPIO8 PIN24 button=23 #GPIO23 PIN 16 GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) GPIO.setup(in1, GPIO.OUT) GPIO.setup(buzzer,GPIO.OUT) GPIO.setup(led,GPIO.OUT) #GPIO.setup(button,GPIO.IN,pull_up_down=GPIO.PUD_DOWN) GPIO.setup(button, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.output(in1, False) GPIO.output(buzzer,False) GPIO.output(led,False) try: GPIO.output(in1,False) while True: GPIO.output(in1,False) # check from database whether it is effective or deffective .currently I have inputted from keyboard variable=raw_input() if variable=="a": m=variable for x in m: GPIO.output(in1, True) time.sleep(0.05) GPIO.output(in1, False) time.sleep(0.05) GPIO.output(buzzer,True) GPIO.output(led,True) if in1==True || buzzer==True: print "messge to database:pending" #def my_callback(channel): #if GPIO.input(button) == True: GPIO.wait_for_edge(button, GPIO.FALLING) #if variable=="b": #while 1: GPIO.output(in1,False) GPIO.output(led,False) GPIO.output(buzzer,False) print "mesage to database:ack completed" #else: #pass #else: #pass GPIO.output(in1,False) except: GPIO.cleanup() GPIO.output(in1,False) If there is any error in my code please help me to rectify that. Thanks
type: UnansweredQuestion

http://stackoverflow.com/q/51247201
has answer: http://stackoverflow.com/a/51249897
accepted answer: http://stackoverflow.com/a/51249897
tagged with: sqlalchemy
has comment: http://stackoverflow.com/comment/89477222
type: Question
has comment: http://stackoverflow.com/comment/89476593
linked to: http://stackoverflow.com/q/11249059
has body: I was reading the documentation of SqlAlchemy regarding the upsert operation on postgres dialect at http://docs.sqlalchemy.org/en/latest/dialects/postgresql.html#insert-on-conflict-upsert Is there a way to know if the upsert has been an insert or an update? The documentation seems to omit this detail.
linked to: http://stackoverflow.com/q/40878027
tagged with: postgresql
answer count: 2
upvote count: 7
linked to: http://stackoverflow.com/q/9407442
favorite count: 0
linked to: http://stackoverflow.com/q/39058213
has comment: http://stackoverflow.com/comment/89476376
has comment: http://stackoverflow.com/comment/89476828
tagged with: python
has answer: http://stackoverflow.com/a/51248947
has comment: http://stackoverflow.com/comment/89474337
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89474600
downvote count: 0
score: 7
possible better answer: http://stackoverflow.com/a/51248947
has title: How to distinguish conflict in sqlalchemy INSERT…ON CONFLICT (Upsert)

http://stackoverflow.com/q/51197551
linked to: http://stackoverflow.com/q/2966981
favorite count: 0
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89382533
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/89376898
has body: I'm building a desktop application using node.js,electron.js,Vue.js and Python. I'm im using python to do some printing. I'm using the python-shell npm library (https://www.npmjs.com/package/python-shell). From python I'm using the pywin32 and sys libraries to print and to get the arguments i pass from JavaScript code. In my JavaScript code I have done as below and my output has more than 4000 characters. This the string i want to get printed. but not all the lines are getting printed. Is there a character limit when passing the values? If so how can i know the limit and can someone suggest me a better path to do this const PythonShell = require("python-shell"); var options = { pythonOptions: ['-u'], scriptPath: __dirname, args: [printerName, output, imgPath] }; PythonShell.run("../../../../extras/script/printer.py", options, function (err, results) { if (err) throw err; for(var k in results){ console.log(results[k]) } });
type: Question
has title: How to pass an argument which exceeds length of 4000 from Javascript to Python using python shell
has comment: http://stackoverflow.com/comment/89377218
tagged with: javascript
has answer: http://stackoverflow.com/a/51197730
accepted answer: http://stackoverflow.com/a/51197730
answer count: 2
possible better answer: http://stackoverflow.com/a/51197765
upvote count: 1
has answer: http://stackoverflow.com/a/51197765

http://stackoverflow.com/a/51222668
answers question: http://stackoverflow.com/q/51221755
downvote count: 0
upvote count: 2
type: Answer
score: 2
has body: There is no way to change the spacing between items in a tkinter listbox, other than to insert blank items.

http://stackoverflow.com/comment/89325805
type: Comment
type: QuestionComment
has text: Refactoring questions are rather broad; this question would be a better fit for Codereview (given that it is your own code and that it works). See https://codereview.stackexchange.com/help/on-topic
score: 2
comment on: http://stackoverflow.com/q/51171644

http://stackoverflow.com/comment/89346971
type: AnswerComment
score: 0
type: Comment
has text: I have provided an data for which literally a straight line fits perfectly. Hence the expected loss should be 0. But by this computation, the loss is oscillates around 0.015. Is this an inherent problem of the model or it can be perfected to get better values?
comment on: http://stackoverflow.com/a/51182121

http://stackoverflow.com/comment/89377662
has text: See the [Paramiko SFTP documentation](http://docs.paramiko.org/en/2.4/api/sftp.html#paramiko.sftp_client.SFTPClient.get). `get()` expects you to pass a local filename to copy the file to. Although it doesn't explicitly say, it probably always returns `None`.
score: 0
comment on: http://stackoverflow.com/q/51196930
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89530940
type: Comment
comment on: http://stackoverflow.com/q/51224609
score: 0
type: QuestionComment
has text: Thank you @SIM , this helped!

http://stackoverflow.com/comment/89326253
type: AnswerComment
comment on: http://stackoverflow.com/a/51171773
has text: @RiccardoOrlando. Modified to work with iterators of unequal length
type: Comment
score: 0

http://stackoverflow.com/a/60891329
has body: I was desperately looking for a way to color nodes on the basis of node properties we define. For example, I was dealing with some pricing and wanted to color nodes if the price of an item in node lies in some range. Thanks, DYZ for the steps, I used your steps to make things work. I am going to post more detailed answer, so it can be helpful for others who want to do the same For those reading the data from an extra file and want to color the graph on the basis of this data I used the following approach. my property data file was saved in dictionary format by using dumpfn from monty, so I am reading this by using loadfn from monty.serialization import dumpfn, loadfn from collections import defaultdict property_data = loadfn("property_data_file") attribute_color_dict = defaultdict(dict) I assume one has networkx graph (say graph) of whose node you want to color #iterate through graph nodes for i in graph.nodes: #get property you want to color and make a range for each color target_property_to_color = property_data[i]['property_you_want_to_color'] if float(target_property_to_color) &lt;=2000: attribute_color_dict[i]['color'] = "#0000FF" #blue color elif 2000&lt; float(target_property_to_color) &lt;10000: attribute_color_dict[i]['color'] = "#008000" #green color else: attribute_color_dict[i]['color'] = '#FF0000' #red color attributes = dict(attribute_color_dict) #add attributes in the graph nx.set_node_attributes(graph, attributes) #save the graph in graphml format nx.write_graphml(graph, "colored_nodes.graphml" ) Now, you can open your gephi app and then load the graph. At first you will see the edges colored according to node color but you can get rid of this by unchecking node color option in gephi (as shown below).
answers question: http://stackoverflow.com/q/51202477
score: 0
type: Answer

http://stackoverflow.com/comment/89610567
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51317100
has text: I use function for that. Class-based has no problem.

http://stackoverflow.com/q/51180563
tagged with: python
has answer: http://stackoverflow.com/a/51180911
has body: I have a JSON of the following sort. In another table, I have JSONPaths, which tells me to get certain values. If I am to get the values of child elements, I need to get all the corresponding parent attribute values and store all of these values in a dataframe as a single row. { "Parent": { "Name": "Bob", "Age": "80", "Children": [ { "Name": "Michael", "Gender":"M", "Children": [ { "Name": "Ezee", "Gender": "M", "Age": 20 }, { "Name": "Ezee", "Gender": "M", "Age": 28, "Children": [ { "Name": "Dre", "Age": 1 }, { "Name": "George", "Age": 2 } ] } ], "Age": 50, "MiddleName": "Jay" }, { "Name": "Justin", "Gender": "M", "Children": [ { "Name": "Emily", "Age": 18, "Gender": "F" } ], "Age": 45 } ] } } Say I need to get the values for the JSON path: Parent/Children/0/Children/0/Name, I need to get the attribute values of name, age, etc. for the corresponding parent (Parent/Children/0/[Name or Age or etc.]) and store all the above values as a single row. Currently, I am able to get the parent values separately by passing the related path and children values separately by passing that path. def findValue(path, json_data): paths = path.split("/") data = json_data for i in range(0,len(paths)): if isinstance(data, list): paths[i]=int(paths[i]) data = data[paths[i]] else: data = data.get(paths[i]) return data How could I achieve this?
type: AnsweredQuestion
score: 0
tagged with: http://stackoverflow.com/tag/json
type: Question
accepted answer: http://stackoverflow.com/a/51180911
answer count: 2
possible better answer: http://stackoverflow.com/a/51180792
has title: Printing parent data along with child data of nested JSON
has answer: http://stackoverflow.com/a/51180792

http://stackoverflow.com/comment/89396670
type: Comment
has text: @SreeramTP yes, the classifier performance itself is an issue orthogonal to the threshold choice (i.e. it's always better to start from more accurate predictions)
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51192702

http://stackoverflow.com/a/51253088
type: Answer
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/89485325
accepted answer of: http://stackoverflow.com/q/51252820
answers question: http://stackoverflow.com/q/51252820
has comment: http://stackoverflow.com/comment/89486217
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89486208
has body: You cant do it with django, because django have syncronous call... so to you get any response from django again you need make a new request or refresh your page... since you need something dinamic, you should use Javascript to do that. document.getElementById('yourBox').onchange = function() { document.getElementById('yourText').disabled = !this.checked; }; &lt;input type="text" id="yourText" disabled /&gt; &lt;input type="checkbox" id="yourBox" /&gt;
has comment: http://stackoverflow.com/comment/89486179

http://stackoverflow.com/q/51299836
has body: I've got multiple outputs from my model from multiple Dense layers. My model has 'accuracy' as the only metric in compilation. I'd like to know the loss and accuracy for each output. This is some part of my code. scores = model.evaluate(X_test, [y_test_one, y_test_two], verbose=1) When I printed out the scores, this is the result. [0.7185557290413819, 0.3189622712272771, 0.39959345855771927, 0.8470299135229717, 0.8016634374641469] What are these numbers represent? I'm new to Keras and this might be a trivial question. However, I have read the docs from Keras but I'm still not sure.
has title: What values are returned from model.evaluate() in Keras?
type: AnsweredQuestion
upvote count: 55
downvote count: 0
tagged with: keras
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/70113193
has answer: http://stackoverflow.com/a/70113193
has answer: http://stackoverflow.com/a/51303340
answer count: 2
tagged with: python
accepted answer: http://stackoverflow.com/a/51303340
score: 55

http://stackoverflow.com/comment/89496498
has text: In both cases it prints true
comment on: http://stackoverflow.com/q/51259003
type: QuestionComment
type: Comment
score: 2

http://stackoverflow.com/q/51236338
has comment: http://stackoverflow.com/comment/89451728
has comment: http://stackoverflow.com/comment/89452631
has comment: http://stackoverflow.com/comment/89451721
has comment: http://stackoverflow.com/comment/89452542
has comment: http://stackoverflow.com/comment/89451908
tagged with: python
has comment: http://stackoverflow.com/comment/89467004
type: AnsweredQuestion
score: 1
has body: I trained and saved a Bidirectional LSTM model in Keras successfully with: model = Sequential() model.add(Bidirectional(LSTM(N_HIDDEN_NEURONS, return_sequences=True, activation="tanh", input_shape=(SEGMENT_TIME_SIZE, N_FEATURES)))) model.add(Bidirectional(LSTM(N_HIDDEN_NEURONS))) model.add(Dropout(0.5)) model.add(Dense(N_CLASSES, activation='sigmoid')) model.compile('adam', 'binary_crossentropy', metrics=['accuracy']) model.fit(X_train, y_train, batch_size=BATCH_SIZE, epochs=N_EPOCHS, validation_data=[X_test, y_test]) model.save('model_keras/model.h5') However, when I want to load it with: model = load_model('model_keras/model.h5') I get an error: ValueError: You are trying to load a weight file containing 3 layers into a model with 0 layers. I also tried different methods like saving and loading model architecture and weights separately but none of them worked for me. Also, previously, when I was using normal (unidirectional) LSTMs, loading the model worked fine.
tagged with: machine-learning
upvote count: 1
has comment: http://stackoverflow.com/comment/89467674
type: Question
has comment: http://stackoverflow.com/comment/89451860
has comment: http://stackoverflow.com/comment/89451867
has comment: http://stackoverflow.com/comment/89451930
has comment: http://stackoverflow.com/comment/89451949
has comment: http://stackoverflow.com/comment/89452040
has comment: http://stackoverflow.com/comment/89451703
tagged with: lstm
has comment: http://stackoverflow.com/comment/89451708
has title: Loading saved model (Bidirectional LSTM) in Keras
has answer: http://stackoverflow.com/a/51244728
accepted answer: http://stackoverflow.com/a/51244728
downvote count: 0
answer count: 1
tagged with: neural-network
tagged with: keras
favorite count: 0

http://stackoverflow.com/q/51178847
has title: Python type() not giving exact class type instead gives metaclass type
score: 2
tagged with: metaclass
downvote count: 0
possible better answer: http://stackoverflow.com/a/51178951
tagged with: method-resolution-order
has answer: http://stackoverflow.com/a/51178919
has body: I am trying to pass the type of a class to a method so that it can be dynamically instantiated. The class extends to a base class which further extends to an abstract class. Now when I check the type of my class it comes as the abstract class type instead of the child class. Here is how my classes look like class AMeta(type): # stuff class Parent(six.with_metaclass(AMeta, object)): # stuff class Child(Parent): # stuff Now when I use type(Child) or Child.__class__ it gives me AMeta whereas I would like to get Child. I want to pass this Child to another method which would dynamically create its object. def create_obj(clzz): return clzz() When I call the method like create_obj(type(Child)) it doesn't work and breaks but when I call Child.mro()[0] it works fine what is happening here and is there another way to achieve what I am achieving via mro method?
type: Question
accepted answer: http://stackoverflow.com/a/51178919
has comment: http://stackoverflow.com/comment/89340382
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89340311
tagged with: inheritance
tagged with: six
upvote count: 2
answer count: 2
has answer: http://stackoverflow.com/a/51178951
favorite count: 0
tagged with: python

http://stackoverflow.com/a/51259202
has comment: http://stackoverflow.com/comment/89497474
has body: Please try to execute provided command in installation docs of pytorch. pyTorch
has comment: http://stackoverflow.com/comment/89497086
has comment: http://stackoverflow.com/comment/89497427
has comment: http://stackoverflow.com/comment/89496851
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51259119
has comment: http://stackoverflow.com/comment/89497988

http://stackoverflow.com/a/51300769
has body: After hours of working, here's the idea to solve the problem: First, make iteration of rows for Data1 dataframe. Don't forget to add attribute iterrows that will return row selection. And don't forget to define index and rows. To make file for every row, define the directory followed by (row[title]) to make it dynamic. However, the directory result/ is not exist yet. User makedirs to make it. And finally, write (row[desc]) inside the txt file. Here we go: import os for idx,row in data1.iterrows(): filename = "result/"+str(row['title'])+".txt" os.makedirs(os.path.dirname(filename), exist_ok=True) with open(filename, "w+") as f: f.write(row['desc']) f.close() print (idx)
type: Answer
answers question: http://stackoverflow.com/q/51287196
score: 0

http://stackoverflow.com/comment/89450288
type: Comment
type: QuestionComment
has text: Please do not include screenshots of either code or data as we cannot copy them, if necessary.
comment on: http://stackoverflow.com/q/51235481
score: 0

http://stackoverflow.com/a/51223693
downvote count: 0
answers question: http://stackoverflow.com/q/51223638
has comment: http://stackoverflow.com/comment/89427723
has comment: http://stackoverflow.com/comment/89427649
type: Answer
has body: Entity.__init__(self, n) takes two arguments: self and n. You're supplying only one, and getting a TypeError. Observe: &gt;&gt;&gt; class A: ... def __init__(self, n): ... print(n) ... &gt;&gt;&gt; A.__init__('s') Traceback (most recent call last): File "&lt;string&gt;", line 1, in &lt;module&gt; TypeError: __init__() missing 1 required positional argument: 'n' To test the constructor, you could do: with self.assertRaises(TypeError): Entity("2") Now, why does this happen and where could one get that self argument from? The thing is that __init__ is supplied with this argument automatically be A.__new__, so you could call A.__new__ yourself, which would result in this weird looking code: self.assertRaises(TypeError, A.__new__(A).__init__, "2")
upvote count: 1
has comment: http://stackoverflow.com/comment/89427792
score: 1
accepted answer of: http://stackoverflow.com/q/51223638
type: AcceptedAnswer

http://stackoverflow.com/a/51288034
answers question: http://stackoverflow.com/q/51287504
score: 4
type: Answer
upvote count: 4
downvote count: 0
has body: First, you should begin with a datetime series; if you don't have one, use pd.to_datetime to force this conversion. This will permit vectorised computations: df = pd.DataFrame({'col': ['2014-07-30 12:19:22', '2014-07-30 05:52:05', '2014-07-30 20:15:00']}) df['col'] = pd.to_datetime(df['col']) Next, note you cannot remove time from a datetime series in Pandas. By definition, a datetime series will include both "date" and "time" components. Normalize time You can use pd.Series.dt.floor or pd.Series.dt.normalize to reset the time component to 00:00:00: df['col_floored'] = df['col'].dt.floor('d') df['col_normalized'] = df['col'].dt.normalize() print(df['col_floored'].iloc[0]) # 2014-07-30 00:00:00 print(df['col_normalized'].iloc[0]) # 2014-07-30 00:00:00 Convert to datetime.date pointers You can convert your datetime series to an object series, consisting of datetime.date objects representing dates: df['col_date'] = df['col'].dt.date print(df['col_date'].iloc[0]) # 2014-07-30 Since these are not held in a contiguous memory block, operations on df['col_date'] will not be vectorised. How to check the difference It's useful to check the dtype for the series we have derived. Notice the one option which "removes" time involves converting your series to object. Computations will be non-vectorised with such a series, since it consists of pointers to datetime.date objects instead of data in a contiguous memory block. print(df.dtypes) col datetime64[ns] col_date object col_floored datetime64[ns] col_normalized datetime64[ns]

http://stackoverflow.com/comment/89643232
type: Comment
has text: I've never used the or_ operator. I didn't even know it existed. I would probably just programatically do it in plain python. Just filter the object you already have with an "or" in your "if" statement, or an "if/else" statement or something like that.
comment on: http://stackoverflow.com/a/51313548
type: AnswerComment
score: 0

http://stackoverflow.com/a/51280771
has body: Here you can find list of chromium command line switches. I believe it's also valid for chrome. There is --homepage switch, that allows setting homepage to be opened in any new opened tab. So I believe you can solve your problem by setting: option.add_argument('--homepage=%s' % some_page_other_than_google)
answers question: http://stackoverflow.com/q/51280539
score: 0
has comment: http://stackoverflow.com/comment/89577440
type: Answer

http://stackoverflow.com/comment/89529364
score: 8
comment on: http://stackoverflow.com/q/51275717
has text: It looks like you define `how_often` as an int, then test its equality to strings
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89341109
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51179062
has text: Either way. Just make sure the reference to the image is not destroyed.
type: AnswerComment

http://stackoverflow.com/a/51255591
has body: You should not use plt.Subplot. Instead directly create the subplot while adding it ax = fig.add_subplot(inner_grid[n]) While not strictly necessary it may help to add the axes as argument to Basemap; this may help remembering which axes is actually being used. m = Basemap(lat_0=0,lon_0=0, ax=ax) Complete code: import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec from mpl_toolkits.basemap import Basemap outer_grid = gridspec.GridSpec(2, 1, wspace=0.2, hspace=0.2) #create plot fig = plt.figure(figsize=(10, 8)) i=0 while i&lt;2: inner_grid = gridspec.GridSpecFromSubplotSpec(3, 3, subplot_spec=outer_grid[i], wspace=0.0, hspace=0.0) n=0 while n&lt;9: ax = fig.add_subplot(inner_grid[n]) n=n+1 m = Basemap(lat_0=0,lon_0=0, ax=ax) m.drawcoastlines() i=i+1 plt.suptitle('Gridspec/Basemap') plt.show()
upvote count: 3
accepted answer of: http://stackoverflow.com/q/51255537
answers question: http://stackoverflow.com/q/51255537
score: 3
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/comment/89479090
type: QuestionComment
has text: should each window be a new dataframe? Or all windows should be combined in a single dataframe?
comment on: http://stackoverflow.com/q/51245432
type: Comment
score: 0

http://stackoverflow.com/a/51285825
has body: Check if this boilerplate could help you. import argparse from flask import Flask def create_app(config=None): app = Flask(__name__) app.config.update(dict(DEBUG=True)) app.config.update(config or {}) # Definition of the routes. Put them into their own file. See also # Flask Blueprints: http://flask.pocoo.org/docs/latest/blueprints @app.route("/") def hello_world(): return "Hello World" return app if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument('dir', type=str, help='specify the images directory') parser.add_argument("-p", "--port", action="store", default="8000") args = parser.parse_args() port = int(args.port) app = create_app() app.run(host="0.0.0.0", port=port)
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51285205

sitemap
type: Tag
tags question: http://stackoverflow.com/q/51172332
tag name: sitemap

http://stackoverflow.com/comment/89359976
comment on: http://stackoverflow.com/a/51186268
score: 0
type: AnswerComment
type: Comment
has text: And on your 1st point, I think an approach similar to this could be used. After reading your point, I think I could just use the encoder on each iteration, calculate the loss by then taking the transpose of each encoding weight matrix and hence simulate the decoding process, from which the loss can be computed. Next, from this loss I could train just the encoder weights as you outlined. This would be repeated until the loss is sufficiently low and I could then construct the permanent decoder through transposing the trained encoder weights and save the whole model.

http://stackoverflow.com/comment/89430250
has text: It would be great if you could *'show'* us some code and maybe an image describing your problem.
type: Comment
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/51224905

numpy
tags question: http://stackoverflow.com/q/51228828
tags question: http://stackoverflow.com/q/51291993
tags question: http://stackoverflow.com/q/51225657
tags question: http://stackoverflow.com/q/51259361
tags question: http://stackoverflow.com/q/51307284
tags question: http://stackoverflow.com/q/51287299
tags question: http://stackoverflow.com/q/51195343
tags question: http://stackoverflow.com/q/51214496
tags question: http://stackoverflow.com/q/51234440
tags question: http://stackoverflow.com/q/51305486
tags question: http://stackoverflow.com/q/51176843
tags question: http://stackoverflow.com/q/51213309
tags question: http://stackoverflow.com/q/51301149
tags question: http://stackoverflow.com/q/51232019
tags question: http://stackoverflow.com/q/51216579
tags question: http://stackoverflow.com/q/51230158
tags question: http://stackoverflow.com/q/51227864
tags question: http://stackoverflow.com/q/51298856
tags question: http://stackoverflow.com/q/51179118
tags question: http://stackoverflow.com/q/51279973
tags question: http://stackoverflow.com/q/51315414
tags question: http://stackoverflow.com/q/51265419
tags question: http://stackoverflow.com/q/51198333
tags question: http://stackoverflow.com/q/51298331
tags question: http://stackoverflow.com/q/51192207
tags question: http://stackoverflow.com/q/51212744
tags question: http://stackoverflow.com/q/51295666
tags question: http://stackoverflow.com/q/51237710
tags question: http://stackoverflow.com/q/51285593
tags question: http://stackoverflow.com/q/51196166
tags question: http://stackoverflow.com/q/51286830
tags question: http://stackoverflow.com/q/51300476
tags question: http://stackoverflow.com/q/51230516
tags question: http://stackoverflow.com/q/51243609
tags question: http://stackoverflow.com/q/51178629
tags question: http://stackoverflow.com/q/51170561
tags question: http://stackoverflow.com/q/51249848
tags question: http://stackoverflow.com/q/51279464
tags question: http://stackoverflow.com/q/51320044
tags question: http://stackoverflow.com/q/51247168
tags question: http://stackoverflow.com/q/51170737
tags question: http://stackoverflow.com/q/51311547
tags question: http://stackoverflow.com/q/51302364
tags question: http://stackoverflow.com/q/51311709
tags question: http://stackoverflow.com/q/51177821
tags question: http://stackoverflow.com/q/51194652
tags question: http://stackoverflow.com/q/51246704
tags question: http://stackoverflow.com/q/51294486
tags question: http://stackoverflow.com/q/51214329
tags question: http://stackoverflow.com/q/51273000
tags question: http://stackoverflow.com/q/51236518
tags question: http://stackoverflow.com/q/51215052
tags question: http://stackoverflow.com/q/51211176
tags question: http://stackoverflow.com/q/51211416
tags question: http://stackoverflow.com/q/51190480
tags question: http://stackoverflow.com/q/51304809
tags question: http://stackoverflow.com/q/51298604
tags question: http://stackoverflow.com/q/51310009
tags question: http://stackoverflow.com/q/51240086
tags question: http://stackoverflow.com/q/51205314
tags question: http://stackoverflow.com/q/51295178
tags question: http://stackoverflow.com/q/51303551
tags question: http://stackoverflow.com/q/51296260
tags question: http://stackoverflow.com/q/51223268
tags question: http://stackoverflow.com/q/51267858
tags question: http://stackoverflow.com/q/51190620
tags question: http://stackoverflow.com/q/51205149
tags question: http://stackoverflow.com/q/51205502
tags question: http://stackoverflow.com/q/51179290
tags question: http://stackoverflow.com/q/51193320
tags question: http://stackoverflow.com/q/51297668
tags question: http://stackoverflow.com/q/51307345
tags question: http://stackoverflow.com/q/51297531
tags question: http://stackoverflow.com/q/51313086
tags question: http://stackoverflow.com/q/51272894
tags question: http://stackoverflow.com/q/51269808
tags question: http://stackoverflow.com/q/51250951
tags question: http://stackoverflow.com/q/51171827
tags question: http://stackoverflow.com/q/51314628
tags question: http://stackoverflow.com/q/51201747

http://stackoverflow.com/comment/89634312
has text: That doesn’t answer what the protocol is supposed to be. And meanwhile, it doesn’t matter whether the other side is a client or a server, it’s still the same question: are you trying to read until the server closes or at least half-shutdowns the connection, or until there’s a momentary lull in traffic, or what?
score: 1
comment on: http://stackoverflow.com/q/51316029
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51322963
type: Answer
answers question: http://stackoverflow.com/q/51322889
upvote count: 14
score: 14
accepted answer of: http://stackoverflow.com/q/51322889
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/134480085
has body: There is property called .url &gt;&gt;&gt; import requests &gt;&gt;&gt; url = 'https://www.amazon.com/' &gt;&gt;&gt; response = requests.get(url) &gt;&gt;&gt; response.url u'https://www.amazon.com/'

http://stackoverflow.com/q/51303063
has title: In Python when utilizing a dictionary, how do you return the keys with same values?
has body: I am new to Python and a beginner and I am struggling with learning a concept for the dictionary class in python. I have a dictionary that maps names of students with a test score. I need to find a way to return any instance of students having the same test score. So far I have something like this but I have been unable to proceed further. def student_scores(): scores={'Shawn':95, 'Craig':74, 'William':96, 'Sara':84, 'Adam':91 'Harold':74, 'Nelson': 87} I looked in my class textbook for examples and found nothing that can help me solve this problem.
answer count: 4
has answer: http://stackoverflow.com/a/51303288
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51303365
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/51303235
type: Question
has comment: http://stackoverflow.com/comment/89582841
has comment: http://stackoverflow.com/comment/89582789
score: 0
has answer: http://stackoverflow.com/a/51304787

http://stackoverflow.com/q/51240581
type: Question
has answer: http://stackoverflow.com/a/51243580
score: 1
has body: I want to remove duplicate data from my collection in MongoDB. How can I accomplish this? Please refer to this example to understand my problem: My collection name &amp; questions are in this col/row as follows - { "questionText" : "what is android ?", "__v" : 0, "_id" : ObjectId("540f346c3e7fc1234ffa7085"), "userId" : "102" }, { "questionText" : "what is android ?", "__v" : 0, "_id" : ObjectId("540f346c3e7fc1054ffa7086"), "userId" : "102" } How do I remove the duplicate question by the same userId? Any help? I'm using Python and MongoDB.
has title: Check and remove duplicates in python MongoDB
tagged with: mongodb
answer count: 2
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/68033410
tagged with: python
linked to: http://stackoverflow.com/q/30187688
type: UnansweredQuestion
upvote count: 1

http://stackoverflow.com/comment/89550573
score: 0
type: QuestionComment
has text: You can display the empty intervals by using the resample command. E.g. `df.resample('hour', on='other_col').sum().fillna(0)`
type: Comment
comment on: http://stackoverflow.com/q/51286294

http://stackoverflow.com/a/51222162
has comment: http://stackoverflow.com/comment/89437891
has comment: http://stackoverflow.com/comment/89425120
score: -1
has comment: http://stackoverflow.com/comment/89437631
has comment: http://stackoverflow.com/comment/89437822
has comment: http://stackoverflow.com/comment/89424928
upvote count: 0
has comment: http://stackoverflow.com/comment/89426407
has comment: http://stackoverflow.com/comment/89425139
has comment: http://stackoverflow.com/comment/89424971
has comment: http://stackoverflow.com/comment/89425246
has comment: http://stackoverflow.com/comment/89425035
has comment: http://stackoverflow.com/comment/89437223
has comment: http://stackoverflow.com/comment/89425026
answers question: http://stackoverflow.com/q/51222105
type: Answer
has body: Obviously the import PATH is different when you run the script from the command prompt and when it's run from cron. Find out what is the import PATH: $ python &gt;&gt;&gt; import sys &gt;&gt;&gt; sys.path Then copy-paste the list of directories into the beginning of your script, like: import sys sys.path = [ ... what you found in the previous step ... ] import boto3 # this should be AFTER you've made changes to sys.path
has comment: http://stackoverflow.com/comment/89437805
downvote count: 1
has comment: http://stackoverflow.com/comment/89437896
has comment: http://stackoverflow.com/comment/89437910
has comment: http://stackoverflow.com/comment/89437987

http://stackoverflow.com/a/51310963
type: Answer
has comment: http://stackoverflow.com/comment/89599382
has body: Here is @user2357112's solution: def sample_indices(X, n=4): pair_indices = np.random.randint(X.shape[0]**2, size=n) pair_indices = np.hstack(((pair_indices // X.shape[0]).reshape((-1,1)), (pair_indices % X.shape[0]).reshape((-1,1)))) good_indices = pair_indices[:,0] != pair_indices[:,1] return X[pair_indices[good_indices]]
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/89600452
has comment: http://stackoverflow.com/comment/89600267
downvote count: 0
answers question: http://stackoverflow.com/q/51310009
has comment: http://stackoverflow.com/comment/89600374
has comment: http://stackoverflow.com/comment/89600404

http://stackoverflow.com/comment/89885719
score: 0
type: QuestionComment
type: Comment
has text: Nothing crazy. I plan on using sockets and passing the identifier of the connection, if such a thing exists, between my services.
comment on: http://stackoverflow.com/q/51249104

http://stackoverflow.com/comment/89367451
has text: Are the lines *unique* in files a and b? In other words, will there only ever be *at most* 2 consecutive lines that are the same in c.txt?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51192126

http://stackoverflow.com/q/51256630
answer count: 1
tagged with: unicode
has comment: http://stackoverflow.com/comment/89492337
score: 0
has comment: http://stackoverflow.com/comment/89493126
tagged with: python
has comment: http://stackoverflow.com/comment/89492546
has title: Saving all words as python source code including punctuation
has body: As in python 2.7, I can save all unicode string into Python source code. In the following code, #!/usr/bin/python #coding:utf-8 a = u'我很好,你呢?' with open('test.txt', 'wb') as f: f.write(repr(a)) What I expect is giving me back a txt with following wording u'我很好,你呢?' but turns out it is u'我很好,你呢?' Why punctuation is not handled? Is there anyway to handle the punctuation too? Updated: Though I will take @Blckknght advisement in comment as using other encoding is still fine for my purpose, but I am still open to see if any answer about saving punctuation as python string. Thx.
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89492165
accepted answer: http://stackoverflow.com/a/51258850
type: Question
has answer: http://stackoverflow.com/a/51258850

http://stackoverflow.com/a/51302993
has body: You were pretty close. Here's the edited code that works: def traverse(start, steps, grid, direction): """ Input a starting point and number of steps to Traverse """ x, y = start[0], start[1] # EDIT: remove "- 1" print(x, y) j, k = direction[0], direction[1] print(j, k) try: for i in range(steps): print(grid[x+i*j][y+i*k]) # EDIT: i*j instead of i+j yield grid[x+i*j][y+i*k] # EDIT: i*j instead of i+j except IndexError: pass print() # Example d = traverse((6, 8), 4, grid, (1, 1)) p = prod([x for x in d]) print('26 x 63 x 78 x 14 = ', 1788696, p == 1788696, '\nActual:', p) # [26, 63, 78, 14] 1788696 print() #Answer d = traverse((15, 3), 4, grid, (-1, 1)) # EDIT: fix direction p = prod([x for x in d]) print('87 x 97 x 94 x 89 = ', 70600674, p == 70600674, '\nActual:', p) # [87, 97, 94, 89] 70600674 I commented all edits I did to your code to make it work. Please comment below if you have any questions.
answers question: http://stackoverflow.com/q/51302673
upvote count: 1
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/89582970
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/51302673

http://stackoverflow.com/q/51317262
answer count: 2
has comment: http://stackoverflow.com/comment/89610554
has comment: http://stackoverflow.com/comment/89612579
possible better answer: http://stackoverflow.com/a/51317344
has title: how to replace all the occurrence of specified characters from a dictionary
has comment: http://stackoverflow.com/comment/89610839
favorite count: 0
has comment: http://stackoverflow.com/comment/89612628
has comment: http://stackoverflow.com/comment/89612313
has comment: http://stackoverflow.com/comment/89612389
has comment: http://stackoverflow.com/comment/89613942
downvote count: 2
has comment: http://stackoverflow.com/comment/89610587
tagged with: encryption
has comment: http://stackoverflow.com/comment/89610650
tagged with: python
has comment: http://stackoverflow.com/comment/89610798
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51317985
type: Question
has comment: http://stackoverflow.com/comment/89612262
upvote count: 0
score: -2
has body: i am currently working on a encryption decryption program . so i have a original string variable and then i convert the string into special character string using my dictionary . Now if some one gives me special character string again , how do i decrypt it ? i am trying this code but , it does not work . enc_str= "`~```~`~`````" # this is 0315 dnory = {'0': '~', '1': '~`', '2': '~``', '3': '~```', '4': '~````', '5': '~`````', '6': '~``````', '7': '~```````', '8': '~````````', '9': '~`````````'} def decrypt(dnory,enc_str): dec_list = [] dnory_reverse = dict([[v,k] for k,v in dnory.items()]) for key in dnory_reverse : if(enc_str.find(key)&gt;0) : dec_list.append(dnory_reverse[key]) print(dec_list) decrypt(dnory,enc_str)
has answer: http://stackoverflow.com/a/51317344
accepted answer: http://stackoverflow.com/a/51317985
has comment: http://stackoverflow.com/comment/89610734

http://stackoverflow.com/a/51200729
score: 0
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/51198754
has body: this one works for me: def runCmdfile(): # File Path to source code: 'C:\LargeFolder\Files' myDir = os.getcwd() # File Path to .cmd file: 'C:\LargeFolder\Files\CorrectFolder' myDir = os.path.join(myDir, 'CorrectFolder') # Popen does not take cwd into account for the file to execute # so we build the FULL PATH on our own runThis = Popen(os.path.join(myDir, 'Run_setup.cmd'), cwd=myDir) stdout, stderr = runThis.communicate()
answers question: http://stackoverflow.com/q/51198754

http://stackoverflow.com/a/51252971
answers question: http://stackoverflow.com/q/51251086
accepted answer of: http://stackoverflow.com/q/51251086
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 1
has body: According to [Python]: types - A foreign function library for Python, you should set argtypes and restype (this is one way) for the function you're calling ([MS.Docs]: LogonUserW function). Below is a minimal example for calling it. If however, you need to call multiple such functions, you could also consider [GitHub]: Python for Windows (pywin32) Extensions, which is a Python wrapper over WINAPIs. code.py: import sys import ctypes from ctypes import wintypes def main(): advapi32_dll = ctypes.WinDLL("advapi32.dll") logon_user_func = advapi32_dll.LogonUserW logon_user_func.argtypes = [wintypes.LPCWSTR, wintypes.LPCWSTR, wintypes.LPCWSTR, wintypes.DWORD, wintypes.DWORD, wintypes.PHANDLE] logon_user_func.restype = wintypes.BOOL user = "dummy_user" domain = "dummy_domain" pwd = "dummy_pwd" logon_type = 2 provider = 0 handle = wintypes.HANDLE() ret = logon_user_func(user, domain, pwd, logon_type, provider, ctypes.byref(handle)) print("{:s} returned {:}".format(logon_user_func.__name__, "TRUE" if ret else "FALSE")) if __name__ == "__main__": print("Python {:s} on {:s}\n".format(sys.version, sys.platform)) main() Notes: Besides argtypes / restypes: In Python3 strings are wide by default, so no need for encode() The HANDLE is passed via byref Output: (py35x64_test) e:\Work\Dev\StackOverflow\q051251086&gt;"e:\Work\Dev\VEnvs\py35x64_test\Scripts\python.exe" code.py Python 3.5.4 (v3.5.4:3f56838, Aug 8 2017, 02:17:05) [MSC v.1900 64 bit (AMD64)] on win32 LogonUserW returned FALSE
score: 1

http://stackoverflow.com/comment/89535603
type: QuestionComment
has text: Hello seuling, yes so in my database it's only saving the attributes from User and the cellphone is null for all the users. I'm trying to figure out how can I save the user and a userprofile related to it together. Thank you
score: 0
comment on: http://stackoverflow.com/q/51278679
type: Comment

http://stackoverflow.com/q/51312601
has comment: http://stackoverflow.com/comment/89624343
has comment: http://stackoverflow.com/comment/89602848
score: 0
has comment: http://stackoverflow.com/comment/89602681
tagged with: python
answer count: 0
type: UnansweredQuestion
tagged with: authentication
tagged with: django
has comment: http://stackoverflow.com/comment/89602409
type: Question
has comment: http://stackoverflow.com/comment/89603867
has body: I'm creating a system in Django with admins(not superuser) and employees working under them. I've created admins registration and login using Django's built-in models. Now I have created custom model for employee's profile. The admin can only register the employee using his dashboard. This part has been done. Now I want to know that how to authenticate the employee's credentials so that the he/she can login to his/her own dashboard? Note that the admin and superuser are different in this case. Admin cannot access superuser's panel. The models are: #ADMIN PROFILE class AdminProfile(models.Model): user=models.OneToOneField(User) image = models.ImageField(upload_to='profile_pics/admin/', blank=True) def __str__(self): return self.user.username #EMPLOYEE PROFILE class EmployeeProfile(models.Model): admin_name = models.ForeignKey(AdminProfile, on_delete = models.CASCADE, default=1) emp_name = models.CharField(max_length=50) email = models.EmailField(max_length=127, unique=True, null=False, blank=False) password = models.CharField(max_length=20) contact_no = models.PositiveIntegerField() location = models.CharField(max_length=50) image = models.ImageField(upload_to='profile_pics/employee/', blank=True) def __str__(self): return self.email I want to have login validation for EmployeeProfile model. I have already tried custom authentication using backends but it failed. I'm new to Django and this is the part of my first project in Django. Thank you in advance. Edit: I solved this question by extending User model in the Employee profile as well.
has comment: http://stackoverflow.com/comment/89602570
has title: Custom Login form in Django
has comment: http://stackoverflow.com/comment/89623334
has comment: http://stackoverflow.com/comment/89623439

http://stackoverflow.com/q/51194310
favorite count: 0
linked to: http://stackoverflow.com/q/9500598
has body: I am trying to deploy a Django based product on an Ubuntu server with Apache. Everything goes well so far, and I can get de applications served by Apache, but I find that these applications lose all their styling. This is the first time I do this, so I made some research and found and followed this tutorial that is pretty good, but I haven't found any reference to the problem I am having. This is in my settings.py: STATICFILES_DIRS = (os.path.join(BASE_DIR,'FrontEndApp','public'),) STATIC_URL = '/res/' STATIC_ROOT = os.path.join(BASE_DIR, 'static/') And this is my 000-default.conf: ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined Alias /static /home/axel/IntellibookProject/Intellibook/static &lt;Directory /home/axel/IntellibookProject/Intellibook/static&gt; Require all granted &lt;/Directory&gt; &lt;Directory /home/axel/IntellibookProject/Intellibook/Intellibook&gt; &lt;Files wsgi.py&gt; Require all granted &lt;/Files&gt; &lt;/Directory&gt; WSGIDaemonProcess Intellibook python-home=/home/axel/IntellibookProject/IntellibookVenv python-path=/home/axel/IntellibookProject/Intellibook WSGIProcessGroup Intellibook WSGIScriptAlias / /home/axel/IntellibookProject/Intellibook/Intellibook/wsgi.py I made the test serving the applications with pyhton manage.py runserver 0.0.0.0:8000, and everything worked perfectly. The problem exists only when the applications are served with Apache.
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/51194538
type: AnsweredQuestion
score: 1
upvote count: 1
has title: Django deployed with Apache on Ubuntu loses all its styling
type: Question
tagged with: apache
accepted answer: http://stackoverflow.com/a/51194538
tagged with: ubuntu
downvote count: 0
answer count: 1

http://stackoverflow.com/a/51217493
has comment: http://stackoverflow.com/comment/89417655
downvote count: 0
score: 1
has body: You haven't instantiated your formset. A factory is something that returns a class, so here modelformset_factory returns a formset class that you then need to instantiate in both your get and post blocks. def get_assumptions(request): AssumptionsFormset = modelformset_factory( Assumptions, form=AssumptionsForm, extra=5) if request.method == 'POST': formset = AssumptionsFormset(request.POST) if formset.is_valid(): ... else: formset = AssumptionsFormset() return render(request, 'assumptions.html', {'formset': formset, 'model_names': model_names}) Also note, you don't need to check is_valid() on each form; if the formset is valid, all the forms will be valid.
upvote count: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51217408
accepted answer of: http://stackoverflow.com/q/51217408
has comment: http://stackoverflow.com/comment/89416525
type: Answer

http://stackoverflow.com/a/51191070
has body: The Run/debug configurations can be opened from here. There you can add the environment variable using this.(click the 3 dot icon next to the environment variables)
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/89387457
has comment: http://stackoverflow.com/comment/89390402
has comment: http://stackoverflow.com/comment/89413336
type: Answer
score: 6
upvote count: 6
accepted answer of: http://stackoverflow.com/q/51188806
has comment: http://stackoverflow.com/comment/89387546
has comment: http://stackoverflow.com/comment/89388011
answers question: http://stackoverflow.com/q/51188806
has comment: http://stackoverflow.com/comment/89389831

http://stackoverflow.com/comment/89613548
type: QuestionComment
has text: Please post a simple understandable dataframe and a expected output for that
comment on: http://stackoverflow.com/q/51317720
score: 0
type: Comment

http://stackoverflow.com/comment/89493354
comment on: http://stackoverflow.com/a/51257209
type: Comment
has text: @MadPhysicist thank you. Yours is very clever as well.
score: 1
type: AnswerComment

http://stackoverflow.com/q/51195348
has comment: http://stackoverflow.com/comment/89374775
has comment: http://stackoverflow.com/comment/89374715
has body: I want to give an image and a list to a keras model for a GAN. The discriminator will get image and some list both are of fixed size i.e. 128x128x3 and 384 and the generator will produce images of 128x128x3 that the disc has to mark fake. So the problem is that I can't figure out what should be the input shape for the discriminator and how it should be initialized. Here is the most relevant initializer simple code which needs to be changed to get an image and list as input where disc gets just a 128x128x3 image and it all works fine:- arr=embeddings #384 length long list self.generator = self.build_generator() z = Input(shape=(100,)) img = self.generator(z) #gen gets noise and generates 128x128x3 self.discriminator.trainable = False valid = self.discriminator(img) #should get 128x128x3 image and "arr" list self.combined = Model(z, valid) self.combined.compile(loss='binary_crossentropy', optimizer=optimizer) And the training code is like this which should be changed accordingly:- d_loss_real = self.discriminator.train_on_batch(pics, valid) d_loss_fake = self.discriminator.train_on_batch(gen_pics, fake) d_loss = 0.5 * np.add(d_loss_real, d_loss_fake) g_loss = self.combined.train_on_batch(latent_code, valid) The disc architecture is like this, its input layer should be changed like this that it can take a list as well with the image:- model = Sequential() model.add(Conv2D(32, kernel_size=5, strides=2, input_shape=(128,128,3), padding="same")) model.add(LeakyReLU(alpha=0.2)) model.add(Dropout(0.25)) model.add(Conv2D(48, kernel_size=5, strides=2, padding="same")) model.add(BatchNormalization(momentum=0.8)) model.add(LeakyReLU(alpha=0.2)) model.add(Dropout(0.25)) model.add(Conv2D(64, kernel_size=5, strides=2, padding="same")) model.add(BatchNormalization(momentum=0.8)) model.add(LeakyReLU(alpha=0.2)) model.add(Dropout(0.25)) model.add(Conv2D(128, kernel_size=5, strides=2, padding="same")) model.add(BatchNormalization(momentum=0.8)) model.add(LeakyReLU(alpha=0.2)) model.ad…
has comment: http://stackoverflow.com/comment/89403823
tagged with: tensorflow
type: Question
has title: Give a list and an image as input to a keras model
linked to: http://stackoverflow.com/q/51211443
has comment: http://stackoverflow.com/comment/89378945
downvote count: 0
tagged with: keras
has answer: http://stackoverflow.com/a/51196321
answer count: 1
score: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/89389936
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89376001
tagged with: input
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/89374675

http://stackoverflow.com/a/51213425
answers question: http://stackoverflow.com/q/51213309
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/89407939
type: AcceptedAnswer
has body: Approach #1 We could leverage broadcasting to generate all indices and index - In [19]: a Out[19]: array([[ 0, 1], [ 2, 3], [ 4, 5], [ 6, 7], [ 8, 9], [10, 11]]) In [21]: mask Out[21]: array([0, 2]) In [24]: a[mask[:,None] + np.arange(3)] Out[24]: array([[[0, 1], [2, 3], [4, 5]], [[4, 5], [6, 7], [8, 9]]]) Approach #2 We can also leverage np.lib.stride_tricks.as_strided based scikit-image's view_as_windows for a more efficient solution - In [43]: from skimage.util.shape import view_as_windows In [44]: view_as_windows(a,(3,a.shape[1]))[mask][:,0] Out[44]: array([[[0, 1], [2, 3], [4, 5]], [[4, 5], [6, 7], [8, 9]]])
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/51213309

http://stackoverflow.com/q/51276435
has body: If I use this code import numpy as np import matplotlib.pyplot as plt x = np.linspace(-1.0, 1.0, 100) y = np.linspace(-1.0, 1.0, 100) X, Y = np.meshgrid(x,y) F = X**2 + Y**2 - 0.6 plt.contour(X,Y,F,[0]) plt.show() which I found here, it works, but the spacing on the graph is distorted based on the window size. Is there a way around this?
favorite count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/51276471
score: 1
tagged with: matplotlib
type: Question
downvote count: 0
has title: How can I keep the grid spacing consistent in pyplot
linked to: http://stackoverflow.com/q/32092899
answer count: 1

http://stackoverflow.com/comment/89559504
type: QuestionComment
score: 1
has text: It may be that you're using a shell session from before you added `qpdf` to `PATH`. Try running the python from a new session.
type: Comment
comment on: http://stackoverflow.com/q/51290814

http://stackoverflow.com/a/51295863
upvote count: 1
has body: i find out wat's wrong , i must put an import as it is a package with import suite_syracuse.Next inkstand of import Next thx anyways :)
type: Answer
has comment: http://stackoverflow.com/comment/89569564
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/51295767

http://stackoverflow.com/comment/89520713
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51249981
score: 0
has text: Ok thanks @tehhnowch

http://stackoverflow.com/comment/89419615
comment on: http://stackoverflow.com/q/51219159
score: 0
type: Comment
type: QuestionComment
has text: I haven't run the code at all yet, tbh. I'm a little hesitant to run this since I've never written anything that touches the directory like this.

http://stackoverflow.com/comment/89448008
comment on: http://stackoverflow.com/q/51234212
type: Comment
type: QuestionComment
score: 1
has text: @PRMoureu as requested, I have added full traceback to the post. All this is on the Anaconda command prompt.

http://stackoverflow.com/q/51253175
has answer: http://stackoverflow.com/a/51253532
has title: 'python2' is not recognized as an internal or external command. Windows 10
score: 2
downvote count: 0
tagged with: python-2.7
type: AnsweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/17900954
accepted answer: http://stackoverflow.com/a/51253532
favorite count: 0
has comment: http://stackoverflow.com/comment/89485836
type: Question
upvote count: 2
answer count: 1
has body: How do I add python2 to PATH? python works fine, however I am invoking a make file that points to many files with calls to python2. C:\Users\andcy\$DETECTRON&gt;python2 'python2' is not recognized as an internal or external command, operable program or batch file. Unfortunately, my search for related points brought me answers that did not apply. For example, the following SO post only shows how to add python to the path, not python2. Add “python2” path to command line on Windows 7

http://stackoverflow.com/comment/89762944
comment on: http://stackoverflow.com/q/51275725
score: 0
has text: I run your code and it produces valid WAVs. Try reinstalling `wavio`
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51305898
has title: import subpackage with libs in python
upvote count: 1
tagged with: import
has comment: http://stackoverflow.com/comment/89589287
type: UnansweredQuestion
answer count: 0
downvote count: 0
has body: I use python script (e.g. script.py) and this script use third-party packages (sdk1, sdk2..) First I put sdk1 and sdk2 packages into root directory: /root script.py /sdk1 ... /sdk2 ... In my script used import sdk1 and it worked well. Then i decided to change structure of my project: /root script.py /libs __init__.py /sdk1 ... /sdk2 ... And now import sdk1 doesn't work. Also, don't work import libs.sdk1, import sdk1 from libs, import * from libs, sys.path.append('/libs') and ton other ways I tried. I killed five hours trying to understand the magic of importing packages in python, but I did not find any right solution for my simple case. Please, help me... UPD: Python version is Python3.6
has comment: http://stackoverflow.com/comment/89591185
has comment: http://stackoverflow.com/comment/89588467
score: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/89591451
tagged with: package
tagged with: python

google-oauth
type: Tag
tags question: http://stackoverflow.com/q/51294143
tag name: google-oauth

http://stackoverflow.com/q/51212916
score: 1
tagged with: pyside
upvote count: 1
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/51219002
accepted answer: http://stackoverflow.com/a/51219002
has body: How can I filters rows in a QTableView, using a search string that checks every display role's value of each column per row? Keeping in mind in this case the columns which are visible can change based on the Checkboxes. While maintaining the ability to Sort the rows by clicking on the Column headers. import os, sys, json, pprint sys.path.append(os.environ.get('PS_SITEPACKAGES')) from Qt import QtGui, QtWidgets, QtCore class QDictTableView(QtWidgets.QWidget): def __init__(self, *args, **kwargs): super(QDictTableView, self).__init__(*args, **kwargs) self.resize(400,300) # controls self.ui_search_input = QtWidgets.QLineEdit() self.ui_search_input.setPlaceholderText('Search...') self.ui_name_filter = QtWidgets.QCheckBox('Name') self.ui_age_filter = QtWidgets.QCheckBox('Age') self.ui_career_filter = QtWidgets.QCheckBox('Career') self.ui_item_table = QtWidgets.QTableView() self.ui_item_table.setEditTriggers(QtWidgets.QAbstractItemView.NoEditTriggers) self.ui_item_table.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows) self.ui_item_table.verticalHeader().hide() self.ui_item_table.setModel(QtGui.QStandardItemModel()) # lay main lay_filters = QtWidgets.QHBoxLayout() lay_filters.addWidget(self.ui_name_filter) lay_filters.addWidget(self.ui_age_filter) lay_filters.addWidget(self.ui_career_filter) lay_main = QtWidgets.QVBoxLayout() lay_main.setAlignment(QtCore.Qt.AlignTop) lay_main.addWidget(self.ui_search_input) lay_main.addLayout(lay_filters) lay_main.addWidget(self.ui_item_table) self.setLayout(lay_main) # connections self.ui_search_input.textChanged.connect(self.changed_text) self.ui_name_filter.stateChanged.connect(self.populate_table) self.ui_age_filter.stateChanged.connect(self.populate_table) self.ui_career_filter.stateChanged.connect(self.populate_table) # being self.populate_table() self.ui_name_filter.setChecked(True) self.ui_age_filter.setChecked(True) self.ui_career_filter.setChecked(True) # methods def changed_text(self, text): print 'SEARCHING:', text d…
tagged with: python
type: AnsweredQuestion
has title: Search all rows in QTableView using PySide
downvote count: 0
type: Question

http://stackoverflow.com/q/51238112
has title: GroupBy and aggregate function in Pandas
has body: I have a time series dataset as below. I would like to split this into multiple 20s bins, get the min and max timestamps in each bin and add a flag to each bin based on whether there is at least 1 successful result (success: result = 0; failed: result = 1) data = [{"product": "abc", "test_tstamp": 1530693399, "result": 1}, {"product": "abc", "test_tstamp": 1530693405, "result": 0}, {"product": "abc", "test_tstamp": 1530693410, "result": 1}, {"product": "abc", "test_tstamp": 1530693411, "result": 0}, {"product": "abc", "test_tstamp": 1530693415, "result": 0}, {"product": "abc", "test_tstamp": 1530693420, "result": 0}, {"product": "abc", "test_tstamp": 1530693430, "result": 0}, {"product": "abc", "test_tstamp": 1530693431, "result": 0}] I'm able to cut the data into 20s intervals using pandas.cut()and get the min and max timestamps for each bin import numpy as np import pandas as pd arange = np.arange(1530693398, 1530693440, 20) data = [{"product": "abc", "test_tstamp": 1530693399, "result": 1}, {"product": "abc", "test_tstamp": 1530693405, "result": 0}, {"product": "abc", "test_tstamp": 1530693410, "result": 1}, {"product": "abc", "test_tstamp": 1530693411, "result": 0}, {"product": "abc", "test_tstamp": 1530693415, "result": 0}, {"product": "abc", "test_tstamp": 1530693420, "result": 1}, {"product": "abc", "test_tstamp": 1530693430, "result": 1}, {"product": "abc", "test_tstamp": 1530693431, "result": 1}] df = pd.DataFrame(data) df['bins'] = pd.cut(df['test_tstamp'], arange) output_1 = df.groupby(["bins"]).agg({'result': np.ma.count, 'test_tstamp': {'mindate': np.min, 'maxdate': np.max}}) test_tstamp result maxdate mindate count bins (1530693398, 1530693418] 1530693415 1530693399 5 (1530693418, 1530693438] 1530693431 1530693420 3 and able to find result success and result failed using groupby() output_2 = df.groupby(["bins", "result"]).result.count() result bins result (1530693398, 1530693418] 0 3 1 2 (1530693418, 1530693438] 0 3 I'm not sure how to combine output_1…
has answer: http://stackoverflow.com/a/51238205
tagged with: pandas-groupby
tagged with: pandas
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89476903
accepted answer: http://stackoverflow.com/a/51238205
type: Question
tagged with: python
score: 0
answer count: 1

http://stackoverflow.com/q/51208644
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
score: 2
tagged with: breadth-first-search
upvote count: 3
has answer: http://stackoverflow.com/a/79322011
downvote count: 1
type: Question
tagged with: algorithm
answer count: 1
has body: I tried this breadth first search practice problem from hackerearth(link to problem). My code passed the sample test case. But I am missing something when it comes to the submission test cases. I ran "my output" and the "test output" through a document distance program that i coded up(for the first submission input), and the distance was found to be ~ 0.52 (deg) [0 deg meaning the documents are exactly same, and 90 deg meaning the documents are entirely different]. This was done only to approximately measure how wrong i was. I need help to find what case(s) I'm failing to account for in my code. problem description: In a social networking site, people are connected with other people. The whole system appears as a giant connected graph. In this question, you are required to answer the total number of people connected at t nodes away from each other (t distance connectivity). For example: Two persons directly connected are at 1 distance connectivity. While the two persons having a common contact without having direct connectivity, are at 2 distance connectivity. First line of input line contains, two integers n and e, where n is the nodes and e are the edges. Next e line will contain two integers u and v meaning that node u and node v are connected to each other in undirected fashion. Next line contains single integer, m, which is number of queries. Next m lines, each have two inputs, one as source node and other as a required t distance connectivity which should be used to process query. Note: The index of nodes will be 0-based. The example and the test case shown is of 1-based index. For submitting the solution, use 0-based indexing. sample input: 9 10 1 2 2 3 1 7 2 4 3 4 4 7 7 8 9 7 7 6 5 6 3 4 2 5 3 2 1 output: 4 4 3 Explanation After creating the graph, there was 3 queries, i. Source node: 4, and we have to find out total number of nodes at a distance of 2 from node 4. 1(4->2->1), 8(4->7->8), 9(4->7->9), 6(4->7->6) = 4 ii. Similarly as above iii. Source node: 2, …
has title: bfs social network algorithm(graph algorithm) - hackerearth

http://stackoverflow.com/q/51310177
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/89596994
tagged with: python
type: UnansweredQuestion
upvote count: 1
has comment: http://stackoverflow.com/comment/89597013
has body: I have a variable in my python script that holds the path to a file as a string. Is there a way, through a python module, etc, to keep the file path updated if the file were to be moved to another destination?
has comment: http://stackoverflow.com/comment/89597192
score: 1
has answer: http://stackoverflow.com/a/51310363
has answer: http://stackoverflow.com/a/51310528
has title: Python module to keep a file location variable updated?
type: Question
tagged with: python-2.7
answer count: 2

http://stackoverflow.com/comment/89440735
type: QuestionComment
comment on: http://stackoverflow.com/q/51230326
has text: I ended up with def shuttle_maint(): removed = open("Todays-Adapto.csv", "a", newline="") removed_write = csv.writer(removed) removed_write.writerow([var_1_default.get(), "Removed for maintenance on", now_date, "@" , now_time]) removed.close() Thanks :)
score: 0
type: Comment

http://stackoverflow.com/a/51239343
answers question: http://stackoverflow.com/q/51239045
type: AcceptedAnswer
type: Answer
upvote count: 1
has body: By default if nothing is passed using super when the exception is raised, there is no explanation, it only shows in the trace back where/which line raised the exception. But passing the message gives that explanation when the exception is raised. Example 1: class GenericMaxException(Exception): """Base class for all Max layer exceptions.""" def __init__(self, * ,message): """ Constructor. Parameters: Required: message - String describing exception. Optional: None """ super().__init__() raise GenericMaxException(message="This is the reason.") Output : Traceback (most recent call last): File "/home/user/PycharmProjects/pythonTutorials/tutorials/temp.py", line 19, in &lt;module&gt; raise GenericMaxException(message="This is the reason.") __main__.GenericMaxException # No explanation why it occurred only mentioned is where it occurred Example 2: class GenericMaxException(Exception): """Base class for all Max layer exceptions.""" def __init__(self, *, message): """ Constructor. Parameters: Required: message - String describing exception. Optional: None """ super().__init__(message) raise GenericMaxException(message="This is the reason.") Output : Traceback (most recent call last): File "/home/user/PycharmProjects/pythonTutorials/tutorials/temp.py", line 19, in &lt;module&gt; raise GenericMaxException(message="This is the reason.") __main__.GenericMaxException: This is the reason. # Here is the explanation.
score: 1
accepted answer of: http://stackoverflow.com/q/51239045
downvote count: 0

http://stackoverflow.com/comment/89387256
type: QuestionComment
comment on: http://stackoverflow.com/q/51202874
has text: Where did you get that code? If you're copying and pasting from sample code that you don't understand, using really old sample code is probably an especially bad idea, and you should look for newer examples. The examples in the `openpyxl` docs are both up-to-date and generally better than random stuff you find on some blog post by some guy.
score: 1
type: Comment

http://stackoverflow.com/comment/89410488
score: 0
type: AnswerComment
has text: So I need to remove `Resnet50_model.add(tf.keras.layers.GlobalAveragePooling2D(input_shape=train_DogResnet50.shape[1:]))` from my model definition and instead add `pooling="avg"` or `pooling="max"` in my ResNet call?
type: Comment
comment on: http://stackoverflow.com/a/51214181

http://stackoverflow.com/q/51290791
has body: I noticed that the de facto standard for array manipulation in Python is through the excellent numpy library. However, I know that the Python Standard Library has an array module, which seems to me to have a similar use-case as Numpy. Is there any actual real-world example where array is desirable over numpy or just plain list? From my naive interpretation, array is just memory-efficient container for homogeneous data, but offers no means of improving computational efficiency. EDIT Just out of curiosity, I searched through Github and import array for Python hits 186'721 counts, while import numpy hits 8'062'678 counts. However, I could not find a popular repository using array.
tagged with: numpy
has comment: http://stackoverflow.com/comment/89561414
downvote count: 1
tagged with: arrays
has comment: http://stackoverflow.com/comment/89561445
favorite count: 0
linked to: http://stackoverflow.com/q/449560
answer count: 3
has title: Numpy arrays vs Python arrays
tagged with: python
has answer: http://stackoverflow.com/a/51293300
accepted answer: http://stackoverflow.com/a/51293300
duplicate of: http://stackoverflow.com/q/111983
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51294054
upvote count: 8
possible better answer: http://stackoverflow.com/a/51290834
type: Question
has answer: http://stackoverflow.com/a/51290834
score: 7
has comment: http://stackoverflow.com/comment/89559401
linked to: http://stackoverflow.com/q/111983

http://stackoverflow.com/comment/89467775
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51244348
score: 1
has text: Closely related: [Python overriding getter without setter](//stackoverflow.com/q/15785982).

http://stackoverflow.com/q/51316579
has answer: http://stackoverflow.com/a/51316841
has comment: http://stackoverflow.com/comment/89609552
has comment: http://stackoverflow.com/comment/89609598
has answer: http://stackoverflow.com/a/51317278
has comment: http://stackoverflow.com/comment/89609501
tagged with: python-3.x
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89609700
tagged with: python
has title: How to create a JSON file from several dictionaries and one list in python
has comment: http://stackoverflow.com/comment/89609647
has comment: http://stackoverflow.com/comment/89609720
has comment: http://stackoverflow.com/comment/89609509
tagged with: http://stackoverflow.com/tag/json
tagged with: flask-restful
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/89609847
has body: I'm trying to create a JSON file in the following format: [ { "startTimestamp" : "2016-01-03 13:55:00", "platform" : "MobileWeb", "product" : "20013509_825", "ctr" : 0.0150 }, {...} ] And the values are stored in the following way: startTimeStamp is in a list called timestampsJSON platform is in a dictionary in this form productBoughtPlatform[product] = platform product is in a dictionary in this form productBoughtCount[product] = count ctr is in a dictionary in this form CTR_Product[product] = ctr I was trying to make something of the kind: response = json.dumps({"startTimestamp":ts, for ts in timestampsJSON.items() "platform":plat, for plat in productBoughtPlatform.items() "product":pro, for pro, key in productBoughtCount.items() "ctr":ctr, for ctr in CTR_Product.items()}) I know the syntax is invalid, but can somebody suggest a way to structure this data in a JSON? Thanks!
score: 0

http://stackoverflow.com/comment/89373057
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51195543
type: AnswerComment
has text: I tried again but I still get "selenium.common.exceptions.TimeoutException: Message:". I don't really know why.

http://stackoverflow.com/comment/89493290
type: Comment
type: QuestionComment
has text: lscpu gives `CPU(s): 32`
comment on: http://stackoverflow.com/q/51256738
score: 0

http://stackoverflow.com/a/51191697
score: 0
has body: You can always overwrite the property of any build in Django model. sample: from django.contrib.auth.models import AbstractUser class User(AbstractUser): password = CharField( max_length=150, required=True, #if you want that field to be mandatory validators=[ RegexValidator( regex='^([-\w]+)$', message='your custom error message', ), ] )
type: Answer
answers question: http://stackoverflow.com/q/51187604

http://stackoverflow.com/a/51323356
upvote count: 3
accepted answer of: http://stackoverflow.com/q/51323311
score: 3
answers question: http://stackoverflow.com/q/51323311
type: AcceptedAnswer
downvote count: 0
has body: Use reindex by Multiindex created by MultiIndex.from_product by all unique values of ID with np.arange by minimal and maximal years: mux = pd.MultiIndex.from_product([df['ID'].unique(), np.arange(df['Year'].min(), df['Year'].max() + 1)], names=['ID','Year']) df = df.set_index(['ID','Year']).reindex(mux).reset_index() print (df) ID Year Data1 Data2 0 345 2010 3.0 2.0 1 345 2011 1.0 4.0 2 345 2012 5.0 2.0 3 345 2013 3.0 1.0 4 345 2014 3.0 1.0 5 345 2015 3.0 1.0 6 345 2016 3.0 1.0 7 123 2010 1.0 1.0 8 123 2011 NaN NaN 9 123 2012 0.0 2.0 10 123 2013 NaN NaN 11 123 2014 NaN NaN 12 123 2015 NaN NaN 13 123 2016 0.0 2.0
type: Answer

http://stackoverflow.com/comment/89925491
type: AnswerComment
score: 0
type: Comment
has text: thanks. I have a few more pressing matters to attend to but will try out your solution and let you know how it works
comment on: http://stackoverflow.com/a/51413802

http://stackoverflow.com/a/51174280
score: 0
has body: try specifying the path for your csv file: import os.path save_path = 'C:/example/' csvName = os.path.join(save_path, "Mycsv"+".csv") csvfile = open(csvName, "w")
answers question: http://stackoverflow.com/q/51173791
type: Answer

http://stackoverflow.com/a/54324451
type: Answer
has body: You can also use Python scapy module to get the mac from scapy.all import * def get_mac(ip_address): responses,unanswered = srp(Ether(dst="ff:ff:ff:ff:ff:ff")/ARP(pdst=ip_address),timeout=2,retry=10) # return the MAC address from a response for s,r in responses: return r[Ether].src return None print(get_mac("192.168.31.14"))
score: 0
answers question: http://stackoverflow.com/q/51239691

http://stackoverflow.com/comment/89598787
type: AnswerComment
score: 0
type: Comment
has text: It's a case where ````fps```` is not defined but ````fn```` is defined... Are you sure your conditions have covered all the cases?
comment on: http://stackoverflow.com/a/51310735

http://stackoverflow.com/a/51233413
answers question: http://stackoverflow.com/q/51233383
type: Answer
score: 2
downvote count: 0
has body: You could capture the 2 parts in a capturing group: ^https?://[^/]+/([^/]+).*/(.*)$ That would match: ^ Match from the start of the string https?:// Match http with an optional s followed by :// [^/]+/ Match not a forward slash using a negated character class followed by a forward slash ([^/]+) Capture in a group (group 1) not a forward slash .* Match any character zero or more times / Match literally (this is the last slash because the .* is greedy (.*)$ Match in a capturing group (group 2) zero or more times any character and assert the end of the line $ Your matches are in the first and second capturing group. Demo Or you could parse the url, get the path, split by a / and get your parts by index: from urlparse import urlparse o = urlparse('http://www.example.com/some-text-to-get/jkl/another-text-to-get') parts = filter(None, o.path.split('/')) print(parts[0]) print(parts[2]) Or if you want to get the parts that contain a - you could use: parts = filter(lambda x: '-' in x, o.path.split('/')) print(parts) Demo
upvote count: 2
has comment: http://stackoverflow.com/comment/89446725

http://stackoverflow.com/comment/89572096
comment on: http://stackoverflow.com/q/51297282
has text: I'm suggesting editing your question to include this information, it seems intrinsic to what you're asking.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51261697
downvote count: 0
answers question: http://stackoverflow.com/q/51261305
type: Answer
has body: You can use a regex to find all instances of "values between two brackets" and then pull out the final one. For example, if we have the following data: df = pd.DataFrame({'col': ['assdffjhjhjh(12tytyt)bhhh(AS7878788)', 'asjhgdv(abjhsgf)(abjsdfvhg)afdsgf']}) and we do: df['col'] = df['col'].str.findall(r'\(([^\(^\)]+)\)').str[-1] this gets us: col 0 AS7878788 1 abjsdfvhg To explain what the regex is doing, it is trying to find all instances where we have: \( # an open bracket ([^\(^\)]+) # anything that isn't an open bracket or a close bracket for one or more characters \) # a close bracket We can see how this is working if we take the .str[-1] from the end of our previous statement, as df['col'] = df['col'].str.findall(r'\(([^\(^\)]+)\)') gives us: col 0 [12tytyt, AS7878788] 1 [abjhsgf, abjsdfvhg]
upvote count: 1
score: 1

http://stackoverflow.com/q/51276866
tagged with: python
upvote count: 2
has comment: http://stackoverflow.com/comment/89605204
tagged with: tensorflow
tagged with: opencv
type: UnansweredQuestion
has title: How can I use a custom tensorflow model with the CV2 DNN module?
score: 2
has comment: http://stackoverflow.com/comment/89609377
answer count: 0
downvote count: 0
favorite count: 0
has body: I retrained an object detection model based on Google's Tensorflow object detection API. I exported it as a frozen inference graph. I would like to use it with CV2's DNN module: cap = cv2.VideoCapture(URL) cvNet = cv2.dnn.readNetFromTensorflow('graph.pb', 'graph.pbtxt') while True: ret, img = cap.read() rows = img.shape[0] cols = img.shape[1] cvNet.setInput(cv2.dnn.blobFromImage(img, 1.0/127.5, (300, 300), (127.5, 127.5, 127.5), swapRB=True, crop=False)) cvOut = cv2Net.forward() for detection in cv2Out[0,0,:,:]: score = float(detection[2]) if score &gt; 0.3: left = detection[3] * cols top = detection[4] * rows right = detection[5] * cols bottom = detection[6] * rows cv2.rectangle(img, (int(left), int(top)), (int(right), int(bottom)), (23, 230, 210), thickness=2) cv2.imshow('img', img) if cv2.waitKey(1) ==27: exit(0) I get this error: Const input blob for weights not found in function getConstBlob From my research, I believe I have to optimize the inference graph. I can't find any documentation as how to do this. If anyone could point me in the right direction, it would be very much appreciated.
type: Question
has comment: http://stackoverflow.com/comment/89605283

http://stackoverflow.com/comment/89374043
type: Comment
type: QuestionComment
has text: I just don't want to have to keep adding it to the path every time I want to use it.
score: 0
comment on: http://stackoverflow.com/q/51195276

http://stackoverflow.com/comment/89526080
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51272328
has text: @MehrdadMoharrami create the `Queue` and instead of passing the list to the subprocess, pass the created `Queue`. Then the subprocess can call `.put()` to put data in the queue while the main process stays in a loop calling `.get()` and receiving data, then `.append`ing it to the list you want. That way the lists are not shared - they stay in the main process.

http://stackoverflow.com/a/51290463
score: 2
answers question: http://stackoverflow.com/q/51290275
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51290275
has body: If you need a scalar, use pd.DataFrame.at with scalar inputs: df3.at[min_time_diff.idxmin(), 'Date'] If you need a series, use pd.DataFrame.loc with a list row indexer: df3.loc[[min_time_diff.idxmin()], 'Date'] Here's a demo: df = pd.DataFrame([[0, 1], [2, 3], [4, 5]], columns=['col1', 'col2']) print(df.at[df['col1'].idxmin(), 'col2']) 1 print(df.loc[[df['col1'].idxmin()], 'col2']) 0 1 Name: col2, dtype: int64
upvote count: 2
type: Answer

http://stackoverflow.com/comment/89451339
comment on: http://stackoverflow.com/q/51234534
score: 0
has text: my questions was does itertools.permutations guarantee the result is sorted if input is sorted? it has been answered below thanks
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51168105
type: AnsweredQuestion
downvote count: 0
linked to: http://stackoverflow.com/q/28679930
type: Question
upvote count: 2
has body: I want to delete all rows containing required string , Suppose I have following dataframe: A B C 1 a x w g n 3 l p j p v I want to delete all rows containing string p. I have search for it but most of the answer is on the basis of column name , in my case I will not be aware of column it can be present in any of the column. Output dataframe should be A B C 1 a x w g n
answer count: 1
has answer: http://stackoverflow.com/a/51168135
favorite count: 0
accepted answer: http://stackoverflow.com/a/51168135
tagged with: pandas
has title: Pandas How to delete rows containing required string
tagged with: python
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89319220
score: 2

http://stackoverflow.com/a/51227397
answers question: http://stackoverflow.com/q/51174715
has body: It is considered bad practice to have functions defined as you are suggesting. The best way to do it is to have function defined at the outer level, and call them wherever you need to use them.
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/89468262

http://stackoverflow.com/q/51250542
type: Question
score: 0
has answer: http://stackoverflow.com/a/51251167
answer count: 1
tagged with: python
tagged with: webdriverwait
type: UnansweredQuestion
tagged with: selenium
has body: I'm trying to automate a process that utilizes a webserver for various computational tasks. There are multiple tasks on multiple pages, so I'm using explicit waits. This works for everything except one particular task, which takes 5-7 minutes to complete (much longer than anything else). Whenever I try the following: def next5(): try: myElem5 = WebDriverWait(driver, 600).until(EC.element_to_be_clickable((By.CSS_SELECTOR, '#fmdsetup &gt; table &gt; tbody &gt; tr:nth-child(2) &gt; td &gt; input[type="radio"]'))) next5 = driver.find_element_by_class_name('nav_entry') next5.click() except TimeoutException: print("Timed out waiting for page to load (next5)") I receive the TimeoutException print statement. I've tried longer wait times, but it always times out. The weird thing is that it throws back the TimeoutException before 10 minutes has passed. Also, the script works perfectly if I simply use a sleep function: def next5(): time.sleep(600) next5 = driver.find_element_by_class_name('nav_entry') next5.click() As I said before, I have multiple instances of next&lt;#&gt;() functions that work perfectly, and only differ in the wait time. What's different about this situation, and how can I make it work?
has title: Selenium (python) explicit wait timeout error
tagged with: timeout

http://stackoverflow.com/q/51219752
upvote count: 1
has comment: http://stackoverflow.com/comment/89421027
type: Question
has comment: http://stackoverflow.com/comment/89420519
has answer: http://stackoverflow.com/a/51219822
has comment: http://stackoverflow.com/comment/89421214
has comment: http://stackoverflow.com/comment/89421180
has title: How do I scan a sentence in Python
linked to: http://stackoverflow.com/q/22735440
tagged with: nltk
downvote count: 5
answer count: 3
has comment: http://stackoverflow.com/comment/89420545
tagged with: string
linked to: http://stackoverflow.com/q/5036700
accepted answer: http://stackoverflow.com/a/51219822
favorite count: 0
has comment: http://stackoverflow.com/comment/89420515
has comment: http://stackoverflow.com/comment/89420649
has answer: http://stackoverflow.com/a/51220251
has answer: http://stackoverflow.com/a/51219792
tagged with: python
duplicate of: http://stackoverflow.com/q/22735440
has body: Suppose I have a text file : As a manager, he told FIFA TV he communicates his messages in a measured way. “I’m not one of the lads,” Southgate explained. Is there a way to get the sentence inside the quote (") and save that sentence as variable? I know I have to use the scanner method, but I'm new to python language and I don't know how. Can someone give me an example on how to store this?
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89421002
has comment: http://stackoverflow.com/comment/89420465
possible better answer: http://stackoverflow.com/a/51219792
score: -4

http://stackoverflow.com/comment/89356760
type: Comment
score: 0
has text: clf.fit, during the training part
comment on: http://stackoverflow.com/q/51187225
type: QuestionComment

http://stackoverflow.com/a/51310734
answers question: http://stackoverflow.com/q/51310619
has body: If I understand your question, the files are being sorted opposite of the order you'd like. You might want to look at the docs for sorted() I suggest using the reverse flag: files = sorted(files, key=lambda, reverse=True)
type: Answer
has comment: http://stackoverflow.com/comment/89598136
has comment: http://stackoverflow.com/comment/89598163
score: 0

http://stackoverflow.com/q/51286830
has answer: http://stackoverflow.com/a/51287369
type: Question
tagged with: numpy
accepted answer: http://stackoverflow.com/a/51287369
tagged with: numerical-integration
linked to: http://stackoverflow.com/q/5965583
tagged with: numerical-methods
answer count: 1
downvote count: 0
has body: I'd like to calculate an integral of the form where I want the results as an array (to eventually plot them as a function of omega). I have import numpy as np import pylab as plt from scipy import integrate w = np.linspace(-5, 5, 1000) def g(x): return np.exp(-2*x) def complexexponential(x, w): return np.exp(-1j*w*x) def integrand(x, w): return g(x)*complexexponential(x, w) integrated = np.real(integrate.quad(integrand, 0, np.inf, args = (w))) which gives me the error "supplied function does not return a valid float". I am not very familiar with the integrate-function of Scipy. Many thanks for your help in advance!
favorite count: 0
has title: Calculate Integral over array in Python with output array
upvote count: 2
tagged with: python
score: 2
type: AnsweredQuestion
tagged with: scipy

http://stackoverflow.com/a/51243217
has comment: http://stackoverflow.com/comment/89466799
answers question: http://stackoverflow.com/q/51242967
score: 0
type: Answer
has body: An idea is to split your df into 50 df's inside a list and then: for i in range(50): list[i].to_excel("file.xlsx", sheet_name = f"Sheet{i+1}")

http://stackoverflow.com/comment/89620971
has text: I'm not sure I follow. Why wouldn't `df = df'xl', 'Form_ID', 'Date', 'Value'` work?
comment on: http://stackoverflow.com/a/51322763
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/51193479
has comment: http://stackoverflow.com/comment/89368545
downvote count: 1
has body: Your approach for data generation is interesting, but you don't have to generate every 100-byte sample out of your texts. Replace the problematic code with something like this: for i in range(0, article_length - seq_length, 1): if random.randint(1,10) not in [5, 6] : continue # this will skip 80% of the samples seq_in = article[i:i + seq_length] seq_out = article[i + seq_length] dataX.append([tokens[char] for char in seq_in]) dataY.append(tokens[seq_out]) Place import random somewhere around the beginning of the file. And once you put this into your code, only 1 out of 5 sequence will get into your training data, effectively reducing the size. There's a way to make generation of the randomly sampled character strings more efficient, but it will require rewriting your code, and this approach just adds one extra line.
score: 0
has comment: http://stackoverflow.com/comment/89368691
answers question: http://stackoverflow.com/q/51193305
type: Answer
has comment: http://stackoverflow.com/comment/89369217
upvote count: 1

http://stackoverflow.com/comment/89565004
has text: BTW, don't use `str` as a variable name, since that shadows the built-in `str` type.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51293444
score: 1

http://stackoverflow.com/comment/89523508
type: QuestionComment
comment on: http://stackoverflow.com/q/51272705
has text: could you post some sample data & expected output please. that would clarify the question better than your description
score: 0
type: Comment

http://stackoverflow.com/q/51309906
has answer: http://stackoverflow.com/a/51309941
has title: I've got a logical Error in my first if statement program
type: AnsweredQuestion
tagged with: if-statement
possible better answer: http://stackoverflow.com/a/51309941
has comment: http://stackoverflow.com/comment/89596467
type: Question
has answer: http://stackoverflow.com/a/51309948
answer count: 2
accepted answer: http://stackoverflow.com/a/51309948
score: -2
tagged with: logical-operators
downvote count: 2
favorite count: 0
tagged with: python-3.x
upvote count: 0
has comment: http://stackoverflow.com/comment/89596336
has comment: http://stackoverflow.com/comment/89596414
tagged with: python
has body: I have typed this code in python, age = int(input("Enter your age: ")) if age &lt; 13: print("You are a Kid!") elif (age == 13 and age &lt; 18): print("You are a teenager!") else: print("You are an adult!") For the age greater than 13 I'm getting YOU ARE AN ADULT Where did i go wrong? Looking forward for your help :)

http://stackoverflow.com/comment/89405424
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51212178
has text: The library you link to [raises exceptions from the `sqlite3` module](https://docs.python.org/3/library/sqlite3.html#exceptions), so catching `sqlite.IntegrityError` would do.
score: 0

gnu-make
type: Tag
tags question: http://stackoverflow.com/q/51311793
tag name: gnu-make

http://stackoverflow.com/a/51387852
type: Answer
upvote count: 4
downvote count: 0
answers question: http://stackoverflow.com/q/51279610
has body: You should be properly subclassing dataframe. In order to get copy-constructor methods to work, pandas describes that you must set the _constructor property (along with other information). You could do something like the following: class SPDF(DataFrame): @property def _constructor(self): return SPDF If you need to preserve custom attributes (not functions - those will be there), during copy-constructor methods (like diff), then you can do something like the following class SPDF(DataFrame): _metadata = ['prop'] prop = 1 @property def _constructor(self): return SPDF Notice the output is as desired: df = SPDF(np.eye(4)) print(type(df)) [&lt;class '__main__.SPDF'&gt;] new = df.diff() print(type(new)) [&lt;class '__main__.SPDF'&gt;]
accepted answer of: http://stackoverflow.com/q/51279610
has comment: http://stackoverflow.com/comment/89912138
score: 4
type: AcceptedAnswer

http://stackoverflow.com/a/51306569
has comment: http://stackoverflow.com/comment/89589981
has comment: http://stackoverflow.com/comment/89589929
has comment: http://stackoverflow.com/comment/89589960
has body: TypeError: list indices must be integers or slices, not str That means you can't index a list with str, only integers and slices. With that, you can find that in this line: filtered_data = ans[~np.isnan(ans["ki"])] ans is a list, and can't be indexed by a string.
answers question: http://stackoverflow.com/q/51306393
upvote count: 2
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/89589988
downvote count: 0

http://stackoverflow.com/a/51182121
score: 7
upvote count: 7
accepted answer of: http://stackoverflow.com/q/51181393
answers question: http://stackoverflow.com/q/51181393
has comment: http://stackoverflow.com/comment/89346971
has comment: http://stackoverflow.com/comment/89347054
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: You should increase the learning rate of optimizer. The default value of learning rate in RMSprop optimizer is set to 0.001, therefore the model takes a few hundred epochs to converge to a final solution (probably you have noticed this yourself that the loss value decreases slowly as shown in the training log). To set the learning rate import optimizers module: from keras import optimizers # ... model.compile(optimizer=optimizers.RMSprop(lr=0.1), loss='mean_squared_error', metrics=['mae']) Either of 0.01 or 0.1 should work fine. After this modification you may not need to train the model for 200 epochs. Even 5, 10 or 20 epochs may be enough. Also note that you are performing a regression task (i.e. predicting real numbers) and 'accuracy' as metric is used when you are performing a classification task (i.e. predicting discrete labels like category of an image). Therefore, as you can see above, I have replaced it with mae (i.e. mean absolute error) which is also much more interpretable than the value of loss (i.e. mean squared error) used here.

http://stackoverflow.com/comment/89451476
has text: The code you've shown us doesn't demonstrate the problem you say you're having. If you want us to debug your code, you need to give us a [mcve] that actually has the problem you need debugged, not similar code that already works.
comment on: http://stackoverflow.com/q/51236069
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89631372
type: AnswerComment
comment on: http://stackoverflow.com/a/51311540
type: Comment
has text: @DePP KeyError tells me you do not have the column that you want to access. Also, for shift, you can refer to the documentation [here](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.shift.html). shift(1) shifts elements to next sequence while shift(-1) does the opposite. I hope it helps.
score: 0

http://stackoverflow.com/comment/89558871
type: Comment
type: QuestionComment
has text: What if you `click()` on `<Select>` and after `click()` on element from list which appear? Like a real human.
comment on: http://stackoverflow.com/q/51290499
score: 0

http://stackoverflow.com/comment/89476654
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51220805
has text: HI Kavko, I think I might need to clarify here a bit. I went to deep not knowing what I actually needed to do. I was given a few gif files which have an x axis showing date and a y axis showing colors . the gif was of a area and on the map showed the precipitation according to the color scheme on the y axis. I assumed I would need to retrieve the values from this file in that manner. However on the link posted previously I found that this was not needed and I used scipy to import the file. When i compared the output of the file i read vs another file it was the same. My code was incorrect.
type: Comment

http://stackoverflow.com/comment/89407954
has text: Looks like `tkSnack.py` isn't present at all, let alone in somewhere on your `PYTHONPATH`…
comment on: http://stackoverflow.com/q/51203301
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51249484
has body: You're calling resample on a pd.Series containing only your Date variable as a string, so pandas is summing up the strings by concatenating them together in each row. Change this: Wind_Weekly = Wind['Date'].resample('W').sum() To this: Wind_Weekly = Wind.resample('W').sum() # Next also works, and removes Date column from the resulting sum Wind_Weekly = Wind.resample('W')['Actual', 'Forecast', 'Demand'].sum() Calling Wind['Date'] returns a pd.Series which ONLY contains your dates BEFORE being transformed to datetime. So no Actual, Forecast or Demand variables are actually passed to the resample call. You can check that: &gt;&gt;&gt; type(Wind['Date']) &lt;class 'pandas.core.series.Series'&gt; For testing, I reproduced your problem with the following code: import pandas as pd import numpy as np rng = pd.date_range('1/1/2012', periods=100, freq='D') df = pd.DataFrame( # Construct df with a datetime index and some numbers {'ones': np.ones(100), 'twos': np.full(100, 2), 'zeros': np.zeros(100)}, index=rng ) df['Date'] = rng.astype(str) # re-add index as a str In the interpreter: &gt;&gt;&gt; df.resample('W').sum() # works out of the box ones twos zeros 2012-01-01 1.0 2 0.0 2012-01-08 7.0 14 0.0 2012-01-15 7.0 14 0.0 ... &gt;&gt;&gt; df['Date'].resample('W').sum() # same result as you, only resample 'Date' column 2012-01-01 2012-01-01 2012-01-08 2012-01-022012-01-032012-01-042012-01-052012-0... 2012-01-15 2012-01-092012-01-102012-01-112012-01-122012-0... 2012-01-22 2012-01-162012-01-172012-01-182012-01-192012-0... ...
has comment: http://stackoverflow.com/comment/89479102
has comment: http://stackoverflow.com/comment/89478238
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89478693
accepted answer of: http://stackoverflow.com/q/51249014
has comment: http://stackoverflow.com/comment/89479342
answers question: http://stackoverflow.com/q/51249014
has comment: http://stackoverflow.com/comment/89478499
type: Answer
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/89478998
upvote count: 2

http://stackoverflow.com/comment/89345811
comment on: http://stackoverflow.com/q/51181483
has text: @jedwards this indeed fixes the issue for the example I gave, am I doomed if I can't control the buffer output of the subprocess child? (my use case has a .exe file instead of write_output.py)
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89558203
type: Comment
has text: @blue_note That was meant to explain to Tiranyk that the loop calculates the expression he wants, whether or not it literally constructs the equivalent "hard-coded" expression.
type: AnswerComment
comment on: http://stackoverflow.com/a/51289404
score: 0

http://stackoverflow.com/comment/89619196
type: QuestionComment
comment on: http://stackoverflow.com/q/51321840
score: 0
has text: If the tensorrt are not supported the tf.matmul() function? if not, how can we do to solve the proble?
type: Comment

http://stackoverflow.com/comment/89400649
has text: Thanks for your answer. The `-2` in start and stop is the core of it. It works in this case, where `(20-10)%2 == 0`. Yet in other cases it doesn't: `a[11:20:2]` will give `array([11, 13, 15, 17, 19])` and `a[20-2:11-2:-2]` will give `array([18, 16, 14, 12, 10])`.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51209862

http://stackoverflow.com/a/65978501
answers question: http://stackoverflow.com/q/51302204
type: Answer
score: 0
has body: The option --onefile does not support arguments, if you changed generated spec file, you have to pass it to the pyinstaller, how documentation outlines: After you have created a spec file and modified it as necessary, you build the application by passing the spec file to the pyinstaller command. So the right way to call the command would be: pyinstaller --onefile MyScript.spec

http://stackoverflow.com/comment/89493397
type: Comment
comment on: http://stackoverflow.com/q/51242987
score: 0
type: QuestionComment
has text: Thanks for the pointer @soupault!

http://stackoverflow.com/comment/89336727
score: 4
has text: This is valid YAML, you can parse it with `yaml.load()`.
comment on: http://stackoverflow.com/q/51176980
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89560295
has text: Before compiling? (This is important)
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51290996
score: 0

http://stackoverflow.com/comment/89585031
comment on: http://stackoverflow.com/q/51303762
type: Comment
type: QuestionComment
score: 0
has text: Usually when you want to **use** something, you need to **have** it first. This also applies to code: if you want to use a var/func you need to have it defined at that point. Move the func definition before the line that throws the error. This is just 1st step. there are more to be done.

http://stackoverflow.com/comment/89547877
type: Comment
score: 0
comment on: http://stackoverflow.com/q/51268282
has text: Could it be there are some malformed csv lines and `read_csv()` just skips them? Do you have the same number of lines in Excel, Notepad++ and Pandas?
type: QuestionComment

http://stackoverflow.com/q/51308651
tagged with: python
has comment: http://stackoverflow.com/comment/89594405
has comment: http://stackoverflow.com/comment/89594110
linked to: http://stackoverflow.com/q/14031763
has title: Call function when Flask is stopped
score: 2
has comment: http://stackoverflow.com/comment/89594193
answer count: 0
duplicate of: http://stackoverflow.com/q/3850261
upvote count: 2
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/40866576
has comment: http://stackoverflow.com/comment/89593948
type: Question
linked to: http://stackoverflow.com/q/3850261
downvote count: 0
tagged with: flask
has comment: http://stackoverflow.com/comment/89594033
favorite count: 0
has body: Is there a way to call a function when Flask is killed? I want to run some server teardown tasks to gracefully stop my application. Also, is there a similar analog for Flask startup? I'm currently putting all my startup code in the same file that calls app = Flask(__name__) - not sure if that's good practice. Thanks!

http://stackoverflow.com/comment/89370653
has text: Could you please provide more information about the dataframes and what they mean? For example column names, what you are trying to achieve etc? See here for creating a [MCVE](https://stackoverflow.com/help/mcve)
comment on: http://stackoverflow.com/q/51194450
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51306493
has body: I want to make a weighted and un-directed graph in python. I have an edge list in a text file (all_edges.txt) in which each line shows 2 letters and a number the first and the second letters are the nodes that are connected to each other and the number is the weight of the corresponding edge. for example: A B 5 This means that node A is connected to node B and the weight of the corresponding edge is 5. Here is the code that I've written to import the graph from the text file: from igraph import * import csv as csvlib import random import numpy as np graph = Graph.Read_Ncol('all_edges.txt', weighted=True, directed=False) but I don't know how to include the weight of the edges.
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python
tagged with: igraph
has answer: http://stackoverflow.com/a/51332825
has title: Import / create a weighted and undirected graph from a txt file in igraph
tagged with: weighted
type: UnansweredQuestion
score: 1
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/89641137

http://stackoverflow.com/comment/89525158
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51273481
has text: Yes that's what I've been doing (see first code line of question). The queryset was just printed there to show that the value is indeed in the set of database objects.
score: 0

http://stackoverflow.com/comment/89447345
has text: How can I choose the output shape of this calculation?
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51234097

http://stackoverflow.com/comment/89417456
has text: ...okay, `blat is hashed` means it's a regular executable from the PATH (whose location was cached in-memory by the shell), so we don't need to worry about aliases or functions getting in the way.
comment on: http://stackoverflow.com/q/51218108
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/89479869
score: 1
has text: You should use the API to get data from instagram. https://www.instagram.com/developer/
type: QuestionComment
comment on: http://stackoverflow.com/q/51250461
type: Comment

http://stackoverflow.com/q/51220670
tagged with: flask
has comment: http://stackoverflow.com/comment/92941629
has comment: http://stackoverflow.com/comment/89425251
has title: web app development using flask and python
answer count: 1
tagged with: python-3.x
has body: I am developing a login form using flask version 1.0.2 in python 3.6 and HTML in Pycharm IDE but the problem is when i edit python code in app.py file i expect the changes to take effect and when i run on default url, http://127.0.0.1:5000/, it does not show the changes in the browser.The old first output keeps being printed. I have deleted cache and cookies and browser history from all browsers plus using CNTRL + F5 for hard refresh but the problem has persisted. from flask import Flask app = Flask(__name__) @app.route('/') def hello_world(): return 'men what are you doing !' if __name__ == '__main__': app.run() What could be the problem?**
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89422865
has comment: http://stackoverflow.com/comment/89453184
tagged with: python
tagged with: pycharm
has comment: http://stackoverflow.com/comment/89438140
score: 0
type: Question
has answer: http://stackoverflow.com/a/51229085

http://stackoverflow.com/q/51289274
downvote count: 0
favorite count: 0
tagged with: postgresql
tagged with: python
score: 4
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51291110
has body: I wrote a Python app which connects to Postgres DB using SQLAlchemy. The engine and session are defined in db.py engine = create_engine(URL(**settings.DATABASE)) session = scoped_session(sessionmaker(bind=engine)) Most of the db operations are in service.py which imports session from db.py from app.db import engine, session def get_door_ids(): result = session.query(ControllerDetail.door_id).distinct().all() ids = [c[0] for c in result] return ids def get_last_health_cd(door_id): result = session.query(ControllerDetail.door_health_cd).filter(ControllerDetail.door_id == door_id).order_by(ControllerDetail.etl_insert_ts.desc()).first() return result[0] Now everything works great, but the problem is I need to run the same thing every couple minutes repeatedly. So I have the following code in my main module: try: while True: run_task() time.sleep(120) except KeyboardInterrupt: print('Manual break by user') The DB time out idle connections every minute. So I get error every time the process goes to sleep for more than 1 minute. psycopg2.InternalError: terminating connection due to idle-in-transaction timeout SSL connection has been closed unexpectedly I wonder if there is a way to close the session and reopen it after time.sleep(120) so it won't get timed out. Maybe in the main modole, I import session from db as a global variable and somehow pass it to methods in services. How do I do that? I can't import session in services from main instead of db since main imports functions from services.
type: Question
has title: How to close and reconnect to avoid idle-in-transaction timeout using SQLAlchemy
has answer: http://stackoverflow.com/a/51290140
tagged with: sqlalchemy
upvote count: 4
answer count: 2
possible better answer: http://stackoverflow.com/a/51290140
accepted answer: http://stackoverflow.com/a/51291110

http://stackoverflow.com/q/51173450
downvote count: 0
answer count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/89402817
has title: Running/Debugging Pycharm Python Scripts with remote Docker Machine
favorite count: 0
tagged with: pycharm
has answer: http://stackoverflow.com/a/51210848
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89402496
tagged with: docker-machine
tagged with: docker-compose
score: 10
has body: I'm using a remote workstation (Ubunutu 18.04) with a GPU via Docker Machine. With PyCharm Professional 2018.1.4 I can connect remotely to the workstation and create/start containers, connect to them and attach a terminal. The problem occurs when I try to run a python script via docker compose with PyCharm. I get the error: python: can't open file '/opt/project/testing.py': [Errno 2] No such file or directory I have the following docker-compose file: version: '3' services: densepose: build: Dockerfile image: densepose volumes: - ./:/opt/project # I have tried adding and removing this to no avail - ./included_files:/included_files - ./output:/output And I am using the Dockerfile from here I have tried using both Ubuntu 17.10 and Windows 10 with PyCharm to connect to the remote station to do this but I receive the same error. Edit: After more digging it seems to be related to PyCharm copying files pr-emptively to the remote docker-machine. It should be using docker-machine scp but I'm not sure yet.
upvote count: 10
type: Question
accepted answer: http://stackoverflow.com/a/51210848

http://stackoverflow.com/comment/89615355
comment on: http://stackoverflow.com/q/51302668
has text: I had an solution for this from someone and its not there now, could someone explain me why please?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/68986620
type: Answer
score: 3
answers question: http://stackoverflow.com/q/51286748
upvote count: 3
downvote count: 0
has body: dataclass-wizard is a modern option that can work for you. It supports complex types such as date and time, most generics from the typing module, and also a nested dataclass structure. The "new style" annotations introduced in PEPs 585 and 604 can be ported back to Python 3.7 via a __future__ import as shown below. from __future__ import annotations # This can be removed in Python 3.10 from dataclasses import dataclass, field from dataclass_wizard import JSONWizard @dataclass class MyClass(JSONWizard): my_str: str | None is_active_tuple: tuple[bool, ...] list_of_int: list[int] = field(default_factory=list) string = """ { "my_str": 20, "ListOfInt": ["1", "2", 3], "isActiveTuple": ["true", false, 1] } """ instance = MyClass.from_json(string) print(repr(instance)) # MyClass(my_str='20', is_active_tuple=(True, False, True), list_of_int=[1, 2, 3]) print(instance.to_json()) # '{"myStr": "20", "isActiveTuple": [true, false, true], "listOfInt": [1, 2, 3]}' # True assert instance == MyClass.from_json(instance.to_json()) You can install the Dataclass Wizard with pip: $ pip install dataclass-wizard A bit of background info: For serialization, it uses a slightly modified (a bit more efficient) implementation of dataclasses.asdict. When de-serializing JSON to a dataclass instance, the first time it iterates over the dataclass fields and generates a parser for each annotated type, which makes it more efficient when the de-serialization process is run multiple times. Disclaimer: I am the creator (and maintainer) of this library.

http://stackoverflow.com/a/51239687
score: 0
type: Answer
has body: Use hex(i) to get hex representation of i Example: &gt;&gt;&gt; hex(65) '0x41' EDIT &gt;&gt;&gt;a = 123 &gt;&gt;&gt;'{:08x}'.format(a) '0000007b' l_dumpid is defined as an int and then you are changing it to string. I think that's what's causing the error. Otherwise this works fine.
answers question: http://stackoverflow.com/q/51239458
has comment: http://stackoverflow.com/comment/89458229

http://stackoverflow.com/q/51301448
has answer: http://stackoverflow.com/a/51307045
type: UnansweredQuestion
score: -3
has comment: http://stackoverflow.com/comment/89581619
type: Question
has body: I'm trying to encode the contents of a Python script in Linux. I just started off with a simple script called test.py - # !/app/logs/Python/bin/python3 # -*- coding: ascii -*- print ("hi") Once I have the script, I execute the vim -x test.py and enter the encryption key twice. Then save the file as normal and then execute the script using python test.py I tried almost all the examples provided in the link here but still i end up getting the below error - SyntaxError: Non-ASCII character '\x97' in file test.py on line 1, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details I checked the default encoding using print sys.getdefaultencoding() and it is acsii. What am i missing here. kindly clarify. I know this question is a duplicate but none of the solutions helped.
has title: Non-ASCII character '\x97' in file, but no encoding declared
downvote count: 3
has comment: http://stackoverflow.com/comment/89580110
has comment: http://stackoverflow.com/comment/89580256
upvote count: 0
has comment: http://stackoverflow.com/comment/89580760
answer count: 1
linked to: http://stackoverflow.com/q/261638
has comment: http://stackoverflow.com/comment/89580177
tagged with: unicode
favorite count: 0
has comment: http://stackoverflow.com/comment/89579990
tagged with: linux
has comment: http://stackoverflow.com/comment/89580352
has comment: http://stackoverflow.com/comment/89581452
tagged with: python

http://stackoverflow.com/comment/89629043
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51292712
has text: @Nikko updated it! I think it does what you are asking for now.

http://stackoverflow.com/a/51292413
downvote count: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/51278663
score: 2
has body: Paramiko does not support SSH "hostbased" authentication. Consider switching to a regular public key authentication. Note that some consider "IP-based authentication" (= authentication that does not require anything from the client) to be the SSH "hostbased" authentication. It's not. For "IP-based" authentication" you do not need any setup on the client side.
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51278663
upvote count: 3

http://stackoverflow.com/comment/89374156
type: AnswerComment
type: Comment
has text: As i told you any other command works fine. Including gunicorn. Only `./manage.py runserver` doesn't want to stop gracefully.
comment on: http://stackoverflow.com/a/51196243
score: 0

http://stackoverflow.com/comment/89602433
score: 0
type: QuestionComment
type: Comment
has text: you need to use `cv2.minMaxLoc()`
comment on: http://stackoverflow.com/q/51312645

http://stackoverflow.com/q/51277079
has comment: http://stackoverflow.com/comment/89672022
has comment: http://stackoverflow.com/comment/89532538
tagged with: numpy
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/89532570
has body: import numpy as np data = np.load('fff.npy') for line in data: print(line) I am trying to open .npy file which is containing image features. File "/home/savithri/anaconda3/lib/python3.6/site-packages/spyder/utils/site/sitecustomize.py", line 705, in runfile execfile(filename, namespace) File "/home/savithri/anaconda3/lib/python3.6/site-packages/spyder/utils/site/sitecustomize.py", line 102, in execfile exec(compile(f.read(), filename, 'exec'), namespace) File "/home/savithri/Documents/MSRIT_MTECH_2018/MTECH_PROJECT_MAIN/data/Flicker30k_Dataset/rr.py", line 3, in &lt;module&gt; for i,line in data: TypeError: iteration over a 0-d array
tagged with: python
has title: TypeError: iteration over a 0-d array
answer count: 0
has comment: http://stackoverflow.com/comment/89531879
type: UnansweredQuestion
upvote count: 1
type: Question
score: 1

http://stackoverflow.com/q/51202885
has answer: http://stackoverflow.com/a/51202938
has comment: http://stackoverflow.com/comment/89387168
score: 0
tagged with: for-loop
answer count: 1
has comment: http://stackoverflow.com/comment/89387234
has body: I have the following code that runs if Rank_Dict is able to be assigned. The issue is that if Rank_Dict looks like example A and has two sets of values it loops fine but if Rank_Dict only has one pair of values like example B then I get an error. Can you not loop over the result set that could only contain one value? Error: File "product.py", line 116, in &lt;module&gt; ProductCategoryId=ranking['ProductCategoryId']['value'] TypeError: string indices must be integers Code: try: Rank_Dict=products_as_dict['Product']['SalesRankings']['SalesRank'] except: print("Didn't find Product/SalesRankings/SalesRank") else: for ranking in Rank_Dict: ProductCategoryId=ranking['ProductCategoryId']['value'] Rank=ranking['Rank']['value'] Data Example A - loops fine [{'ProductCategoryId': {'value': 'home_improvement_display_on_website'}, 'Rank': {'value': '1335712'}}, {'ProductCategoryId': {'value': '17416540011'}, 'Rank': {'value': '2593'}}] Example B - fails to loop {'ProductCategoryId': {'value': 'home_improvement_display_on_website'}, 'Rank': {'value': '55928'}}
tagged with: python
has title: Python - For Loop fails if only one item. 'TypeError: string indices must be integers'
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89387011
type: Question

http://stackoverflow.com/comment/89371486
comment on: http://stackoverflow.com/q/51194784
type: QuestionComment
type: Comment
score: 1
has text: You could add python `logging` to see where your service is getting to before hanging/crashing.

http://stackoverflow.com/q/51225294
possible better answer: http://stackoverflow.com/a/51225374
answer count: 2
has answer: http://stackoverflow.com/a/51225359
has answer: http://stackoverflow.com/a/51225374
tagged with: python
has body: I want to conveniently open a file in a IPython terminal without switching to another terminal outside IPython. Specifically, can I open vim or other common text editors in a IPython terminal?
accepted answer: http://stackoverflow.com/a/51225359
score: 0
tagged with: ipython
has comment: http://stackoverflow.com/comment/89430910
has title: Edit text file in IPython terminal without switching terminal
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89430963
type: Question

http://stackoverflow.com/q/51245846
has answer: http://stackoverflow.com/a/51245965
upvote count: 2
tagged with: python
type: AnsweredQuestion
score: 2
has body: I have the following file structure . └── text_classifier ├── Experiment.py ├── __init__.py ├── constants.py ├── hyperparameters │ ├── Hyperparameter.py │ └── __init__.py ├── models │ ├── __init__.py │ ├── han.py │ └── model.py ├── trainers │ ├── __init__.py │ ├── dataset_trainer.py │ └── trainer.py └── utils ├── __init__.py ├── default_conf.yml ├── tf_utils.py └── utils.py I want to import text_classifier from an Ipython console. text_classifier/__init__.py contains import builtins import sys import os sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))) sys.path.append(os.path.dirname(os.path.dirname(__file__))) sys.path.append(os.path.dirname(__file__)) sys.path.append(__file__) print('\n'.join(sys.path)) from .experiment import Experiment from .hyperparameters import HP try: from IPython.lib import deepreload builtins.reload = deepreload.reload except: pass However running import text_classifier as tcl from the same location as text_classifier yields the following: /Users/victor/.pyenv/versions/3.6.4/Python.framework/Versions/3.6/lib/python36.zip /Users/victor/.pyenv/versions/3.6.4/Python.framework/Versions/3.6/lib/python3.6 /Users/victor/.pyenv/versions/3.6.4/lib/python3.6/lib-dynload /Users/victor/.pyenv/versions/3.6.4/Python.framework/Versions/3.6/lib/python3.6/site-packages /Users/victor/.pyenv/versions/3.6.4/lib/python3.6/site-packages /Users/victor/.pyenv/versions/3.6.4/Python.framework/Versions/3.6/lib/python3.6/site-packages/IPython/extensions /Users/victor/.ipython /Users/victor/Documents/documentation /Users/victor/Documents/documentation/han /Users/victor/Documents/documentation/han/text_classifier /Users/victor/Documents/documentation/han/text_classifier/__init__.py --------------------------------------------------------------------------- ModuleNotFoundError Traceback (most recent call last) &lt;ipython-input-1-256767c7aff3&gt; in &lt;module&gt;() ----&gt; 1 import text_classifier as tl ~/Documents/documentation/han/text_cla…
accepted answer: http://stackoverflow.com/a/51245965
type: Question
downvote count: 0
answer count: 1
favorite count: 0
has title: ModuleNotFoundError with package in path
tagged with: python-3.x

http://stackoverflow.com/a/51363356
downvote count: 0
answers question: http://stackoverflow.com/q/51297992
score: 1
has body: The problem is that you are (probably) trying to initialize the new network(x2) with parameters from the old one (x4). This doesn't work because, as the error states, the dimensions aren't compatible. There should be a similar line to this one that is causing the error. tl.files.load_and_assign_npz(sess=sess, name='model.npz', network=network) To fix this you have to retrain the network with the new scaling factor and use the new model for evaluation.
accepted answer of: http://stackoverflow.com/q/51297992
has comment: http://stackoverflow.com/comment/89765731
upvote count: 1
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/comment/89569794
type: AnswerComment
comment on: http://stackoverflow.com/a/51282868
type: Comment
score: 0
has text: Thanks. I tried the time taken for 100 locations with both the codes, your lambda and my for loop. The lambda based solution took `62.94639539718628s` and the for loop based one took `43.16185998916626s`. I'm a bit surprised, as I thought the lambda based solution should have been faster, from common knowledge!

http://stackoverflow.com/comment/89709273
comment on: http://stackoverflow.com/a/51317377
type: AnswerComment
has text: I also cannot play the resulting WAV files from the ffmpeg command with pyglet. I get en exception `pyglet.media.sources.riff.WAVEFormatException: Not a WAVE file`. I think, pyglet just cannot recognize the WAV file header because ffmpeg adds some metadata. But the files are certainly uncompressed .wav and can be read by Python's `wave` (as in my script). Maybe there is an option to avoid adding metadata to WAV?
score: 0
type: Comment

http://stackoverflow.com/comment/89551637
type: QuestionComment
has text: I edited my questions to include a simpler example of what I'm trying to accomplish. @hpaulj
comment on: http://stackoverflow.com/q/51277646
score: 0
type: Comment

http://stackoverflow.com/q/51261145
type: AnsweredQuestion
score: 3
tagged with: list
has comment: http://stackoverflow.com/comment/89500775
tagged with: selenium
type: Question
accepted answer: http://stackoverflow.com/a/51265935
answer count: 2
has title: How can I create a list of elements with the same xpath using selenium with python?
has comment: http://stackoverflow.com/comment/89502089
has comment: http://stackoverflow.com/comment/89501780
has comment: http://stackoverflow.com/comment/89500627
downvote count: 0
has comment: http://stackoverflow.com/comment/89501356
has comment: http://stackoverflow.com/comment/89503646
has comment: http://stackoverflow.com/comment/89500849
has comment: http://stackoverflow.com/comment/89500587
has answer: http://stackoverflow.com/a/51261439
has comment: http://stackoverflow.com/comment/89501531
has comment: http://stackoverflow.com/comment/89501874
favorite count: 0
has comment: http://stackoverflow.com/comment/89503552
tagged with: xpath
has answer: http://stackoverflow.com/a/51265935
has comment: http://stackoverflow.com/comment/89502751
upvote count: 3
has comment: http://stackoverflow.com/comment/89501440
has body: I need to click on several elements from the same table on the same webpage. I was thinking to do so with a for loop but in order to perform that action I first need to create a list of these elements. //table[@border='1']//a This is the xpath which selects all the elements from the table, how can I create a list of all these?
possible better answer: http://stackoverflow.com/a/51261439
tagged with: python
has comment: http://stackoverflow.com/comment/89503378
has comment: http://stackoverflow.com/comment/89501975
tagged with: selenium-webdriver

http://stackoverflow.com/q/51252687
has comment: http://stackoverflow.com/comment/89484236
has comment: http://stackoverflow.com/comment/89484844
favorite count: 0
linked to: http://stackoverflow.com/q/11476371
accepted answer: http://stackoverflow.com/a/51252733
duplicate of: http://stackoverflow.com/q/11476371
tagged with: python
has answer: http://stackoverflow.com/a/51252992
type: AnsweredQuestion
tagged with: list
has body: I have a list d that I wish to sort. I sort by the first column first. If its a tie there I then go on to use the second column to sort. Say I want to sort by the first column in ascending order but sort by the second column in descending order. Ascending being the default, using the reverse key I thought the below should work. sorted(d,key=lambda x: (x[0],x[1]),reverse=(False,True)) But it does not. It give the following error. reverse=(False,True)) TypeError: an integer is required (got type tuple) So if I'm not doing it right how to fix it? Or the way to do this is completely different? Advice on that would be helpful. My question indeed has some duplication but there are already interesting responses, so I would like to keep it.
type: Question
linked to: http://stackoverflow.com/q/11206884
has title: Set Ascending Descending for each column when sorting by multiple columns
score: 4
has answer: http://stackoverflow.com/a/51252733
upvote count: 4
answer count: 3
possible better answer: http://stackoverflow.com/a/51252873
downvote count: 0
tagged with: sorting
has answer: http://stackoverflow.com/a/51252873

http://stackoverflow.com/a/54946522
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51264478
has comment: http://stackoverflow.com/comment/96776106
has comment: http://stackoverflow.com/comment/96776124
has comment: http://stackoverflow.com/comment/96792873
has body: I only know this for principle component analysis for sure, but I guess it works similar for LSA and nobody else answered this question, so I'll try. Imagine that you have 2 documents and 3 features, resulting in a 3-dimensional coordinate system with two datapoints. These two datapoints can be connected with a straight line, and therefore only need a two-dimensional coordinate system to be described. Accordingly, two principle components are going to be enough to explain all the variance in the data. If you have higher dimensions, the number of documents you have will determine how many dimensions you need to describe your data.

http://stackoverflow.com/comment/89408428
comment on: http://stackoverflow.com/a/51213247
score: 0
type: AnswerComment
type: Comment
has text: geckodriver-v0.21.0 .. firefox v61, i think it's compatibale

http://stackoverflow.com/q/51199515
tagged with: selenium-webdriver
has comment: http://stackoverflow.com/comment/89381402
has comment: http://stackoverflow.com/comment/89381246
has answer: http://stackoverflow.com/a/51199691
downvote count: 3
tagged with: selenium
score: -1
duplicate of: http://stackoverflow.com/q/29858752
type: Question
has comment: http://stackoverflow.com/comment/89380836
has comment: http://stackoverflow.com/comment/89381212
answer count: 2
has comment: http://stackoverflow.com/comment/89381022
has comment: http://stackoverflow.com/comment/89380813
has comment: http://stackoverflow.com/comment/89381368
linked to: http://stackoverflow.com/q/29858752
favorite count: 0
has body: I have Chromium on my computer that runs Debian 9. Here's scraper.py: from selenium import webdriver import time options = webdriver.ChromeOptions() options.add_argument("--ignore-certificate-errors") options.add_argument("--test-type") options.binary_location = "/usr/bin/chromium" driver = webdriver.Chrome(chrome_options=options) driver.get("https://python.org") The Chromium binary is at the specified location. When I run python scraper.py, I get this error. Traceback (most recent call last): File "scraper.py", line 9, in &lt;module&gt; driver = webdriver.Chrome(chrome_options=options) File "/home/me/ENV/pbc_vss/local/lib/python2.7/site-packages/selenium/webdriver/chrome/webdriver.py", line 68, in __init__ self.service.start() File "/home/me/ENV/pbc_vss/local/lib/python2.7/site-packages/selenium/webdriver/common/service.py", line 83, in start os.path.basename(self.path), self.start_error_message) selenium.common.exceptions.WebDriverException: Message: 'chromedriver' executable needs to be in PATH. Please see https://sites.google.com/a/chromium.org/chromedriver/home
upvote count: 2
type: UnansweredQuestion
has title: Selenium error: 'chromedriver' executable needs to be in PATH
tagged with: python
has answer: http://stackoverflow.com/a/51199781
has comment: http://stackoverflow.com/comment/89380868

http://stackoverflow.com/comment/89340497
type: AnswerComment
has text: I fixed the index too with `df.index = pd.RangeIndex(len(df.index))` and now it takes 20 seconds which is bearable at least for me.
type: Comment
score: 1
comment on: http://stackoverflow.com/a/51175719

timeit
tag name: timeit
type: Tag
tags question: http://stackoverflow.com/q/51255592

http://stackoverflow.com/comment/90251573
comment on: http://stackoverflow.com/q/51254772
type: Comment
type: QuestionComment
has text: Update: One does not need c_0 and h_0 to perform inference over pre-trained LSTM. Verified the LSTM equations manually v/s Caffe output. Just use all zeros for c_0 and h_0 and it gave correct results. Blob: net.blobs['blob_name'] contains the output from blob_name layer. Hence in Caffe LSTM there is only net.blobs['lstm'] blob and contains the output as (Timestep, independent stream, Hidden size) dimensional output data
score: 0

http://stackoverflow.com/comment/89530076
score: 2
comment on: http://stackoverflow.com/q/51276092
type: Comment
type: QuestionComment
has text: `[` and `]` conventionally mean inclusive and `(` and `)` conventionally mean exclusive.

http://stackoverflow.com/comment/89692173
type: Comment
comment on: http://stackoverflow.com/a/51323434
has text: Thank you. This is precisely what I needed. It's the same logic but when your brain is fried it can be hard to see that. Thanks again!
score: 0
type: AnswerComment

http://stackoverflow.com/q/51190809
downvote count: 0
answer count: 1
favorite count: 0
tagged with: lightgbm
tagged with: python
type: AnsweredQuestion
has body: I am trying to build a classifier with LightGBM on a very imbalanced dataset. Imbalance is in the ratio 97:3, i.e.: Class 0 0.970691 1 0.029309 Params I used and the code for training is as shown below. lgb_params = { 'boosting_type': 'gbdt', 'objective': 'binary', 'metric':'auc', 'learning_rate': 0.1, 'is_unbalance': 'true', #because training data is unbalance (replaced with scale_pos_weight) 'num_leaves': 31, # we should let it be smaller than 2^(max_depth) 'max_depth': 6, # -1 means no limit 'subsample' : 0.78 } # Cross-validate cv_results = lgb.cv(lgb_params, dtrain, num_boost_round=1500, nfold=10, verbose_eval=10, early_stopping_rounds=40) nround = cv_results['auc-mean'].index(np.max(cv_results['auc-mean'])) print(nround) model = lgb.train(lgb_params, dtrain, num_boost_round=nround) preds = model.predict(test_feats) preds = [1 if x &gt;= 0.5 else 0 for x in preds] I ran CV to get the best model and best round. I got 0.994 AUC on CV and similar score in Validation set. But when I am predicting on the test set I am getting very bad results. I am sure that the train set is sampled perfectly. What parameters are needed to be tuned.? What is the reason for the problem.? Should I resample the dataset such that the highest class is reduced.?
tagged with: classification
tagged with: machine-learning
has comment: http://stackoverflow.com/comment/89363245
has answer: http://stackoverflow.com/a/51192702
type: Question
score: 10
has comment: http://stackoverflow.com/comment/89363692
upvote count: 10
has comment: http://stackoverflow.com/comment/89363652
tagged with: auc
has title: High AUC but bad predictions with imbalanced data
accepted answer: http://stackoverflow.com/a/51192702

http://stackoverflow.com/q/51276635
tagged with: selenium-webdriver
tagged with: selenium
upvote count: 1
tagged with: web-scraping
type: AnsweredQuestion
score: 1
accepted answer: http://stackoverflow.com/a/51318123
type: Question
has title: Having trouble extracting dynamic div list while scrolling down using Webdriver (selenium & python)
answer count: 1
downvote count: 0
favorite count: 0
tagged with: beautifulsoup
has body: I'm having a hard time trying to figure out how to get a refreshed dynamic list while scrolling down the page using Webdriver in Selenium and Python3. https://www.ubereats.com/stores/ this is the website that I'm trying to scrape and if the site directs you to the homepage, please type any city and click, which will show you list of restaurants in div. The interesting thing here is that if you go to inspect element, the list of &lt;div class="base_ ue-ff ...&gt;..&lt;/div&gt; changes as I scroll down the page and even I did scroll the page down using a webdriver in selenium python, it still retrieves the old data that has been extracted at the first place. Below is my sample code. I also made a sleep function to let the data to load, but there wasn't any difference to the data extraction. from bs4 import BeautifulSoup from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.common.exceptions import NoSuchElementException from urlib.request import urlopen from importlib import reload import re import sys driver = webdriver.Chrome(path_chrome_driver) driver.get('https://www.ubereats.com') wait_time_for_search_complete = float(np.random.uniform(1,2,1)) time.sleep(wait_time_for_search_complete) input_city_name = driver.find_element_by_xpath("//input[@placeholder='Enter your delivery address']") time_to_wait_to_enter_city_name = float(np.random.uniform(1, 2, 1)) time.sleep(time_to_wait_to_enter_city_name) input_city_name.send_keys('Sydney') time_to_wait_to_write_city = float(np.random.uniform(2, 3, 1)) time.sleep(time_to_wait_to_write_city) select_first_in_dropdown = driver.find_element_by_xpath('//*[@id="app-content"]/div/div[1]/div/div[1]/div[1]/div[2]/div/div/div[3]/div[1]/div/div/div[2]/div/div/button[1]') select_first_in_dropdown.click() time_to_wait_to_load_restaurants = float(np.random.uniform(2, 3, 1)) time.sleep(time_to_wait_to_load_restaurants) current_page = driver.page_source soup = BeautifulSoup(current_page,'html.parser')…
tagged with: python
has answer: http://stackoverflow.com/a/51318123

http://stackoverflow.com/q/51203713
has answer: http://stackoverflow.com/a/51203741
has answer: http://stackoverflow.com/a/51204051
favorite count: 0
tagged with: sequences
has comment: http://stackoverflow.com/comment/89388542
type: UnansweredQuestion
score: -3
tagged with: python
has title: Troubleshoot simple summation function
has comment: http://stackoverflow.com/comment/89388531
upvote count: 1
type: Question
has body: I want to create f(n) for Sn = n(n+1)/2. Does this make sense? I feel like a nerd! Here's what I wrote: def f(x): sum=n(n+1)/2 print(sum)
answer count: 2
downvote count: 4

http://stackoverflow.com/q/51250663
tagged with: python
score: 1
tagged with: pyqt5
upvote count: 1
has body: I am trying to create a Wizard using PyQt5 and I'm trying to make it so that the input entered by the user on one page influences what the user will see on the next page. However, when I try and do so, I only see the index value as opposed to the text. Creating a list and then mapping the index value to the appropriate location in the list in order to get the string seems a bit janky, so does anyone know if PyQt has a better function built-in that does this? class IntroductionPage(QtWidgets.QWizardPage): def __init__(self,*args,**kwargs): super().__init__() self.setTitle("Project Name") self.setSubTitle("Please select one of the available projects below") l = get_projects() comboBox = QtWidgets.QComboBox(self) [comboBox.addItem(i) for i in l] layout = QtWidgets.QGridLayout() layout.addWidget(comboBox) self.setLayout(layout) self.registerField("projectName",comboBox) class TaskPage(QtWidgets.QWizardPage): def __init__(self,*args,**kwargs): super().__init__() # currently returns an integer and not a string def initializePage(self): self.setTitle(self.field("projectName")) class My_Wizard(QtWidgets.QWizard): num_of_pages = 2 (intro,task) = range(num_of_pages) def __init__(self,*args,**kwargs): super(My_Wizard,self).__init__(*args,**kwargs) self.setPage(self.intro,IntroductionPage(self)) self.setPage(self.task,TaskPage(self)) self.setStartId(self.intro)
has answer: http://stackoverflow.com/a/51250908
linked to: http://stackoverflow.com/q/51273301
type: AnsweredQuestion
tagged with: qwizardpage
type: Question
answer count: 2
tagged with: pyqt
accepted answer: http://stackoverflow.com/a/51250908
tagged with: qwizard
downvote count: 0
has title: pyqt wizard registerfield as string and not integer
possible better answer: http://stackoverflow.com/a/75547436
favorite count: 0
has answer: http://stackoverflow.com/a/75547436

http://stackoverflow.com/q/51200908
score: 1
has answer: http://stackoverflow.com/a/51200947
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/51204399
has title: Python3: Decode UTF-8 bytes converted as string
has comment: http://stackoverflow.com/comment/89383473
has body: Suppose I have something like: a = "Gżegżółka" a = bytes(a, 'utf-8') a = str(a) which returns string in form: b'G\xc5\xbceg\xc5\xbc\xc3\xb3\xc5\x82ka' Now it's send as simple string (I get it as assertion from eval function). How the heck can I now get normal UTF-8 form of starting word? If there is some better compression than str(bytes(x)) then I would be glad to hear.
tagged with: decode
possible better answer: http://stackoverflow.com/a/51204399
answer count: 2
accepted answer: http://stackoverflow.com/a/51200947
favorite count: 0
tagged with: python-3.x
tagged with: encode
tagged with: python
tagged with: utf-8
type: AnsweredQuestion
upvote count: 2

http://stackoverflow.com/q/51265858
type: Question
answer count: 8
has answer: http://stackoverflow.com/a/51266000
has body: I just installed django and after installing that I created a django project and was trying to run django server by command: python manage.py runserver After that I'am getting error as: SyntaxError: Generator expression must be parenthesized
has answer: http://stackoverflow.com/a/65359517
has answer: http://stackoverflow.com/a/61564577
upvote count: 51
has comment: http://stackoverflow.com/comment/89509707
has answer: http://stackoverflow.com/a/52681880
accepted answer: http://stackoverflow.com/a/51266000
favorite count: 0
has comment: http://stackoverflow.com/comment/89509759
tagged with: django
tagged with: python
downvote count: 1
has answer: http://stackoverflow.com/a/57783953
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89509752
linked to: http://stackoverflow.com/q/48822571
has answer: http://stackoverflow.com/a/60825266
possible better answer: http://stackoverflow.com/a/53759957
score: 50
has comment: http://stackoverflow.com/comment/89509975
has title: SyntaxError: Generator expression must be parenthesized
has answer: http://stackoverflow.com/a/53759957
has answer: http://stackoverflow.com/a/61599977

http://stackoverflow.com/q/51286908
has comment: http://stackoverflow.com/comment/89569001
has comment: http://stackoverflow.com/comment/89568875
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/89552560
tagged with: python-3.6
score: 0
tagged with: windows-10
has answer: http://stackoverflow.com/a/54079346
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89551467
has comment: http://stackoverflow.com/comment/89551312
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89568792
has body: So I am not able to import BeautifulSoup after I have installed bs4. I have tried installing bs4 using pip, pip3, and pip3.6. All successfully install bs4, but I still get the error saying there is no module named bs4 when I try and import it. I have also tried doing it by using "pip install beautifulsoup4" with no luck. I am using python 3.6.5 on Windows 10. This is the output of my pip commands Let me know things I can try differently to get this working. Thanks for any help.
has answer: http://stackoverflow.com/a/51296286
has title: ModuleNotFoundError: No module named 'bs4' but I have bs4 installed I believe

http://stackoverflow.com/comment/89597783
score: 0
type: Comment
type: QuestionComment
has text: `spreadsheets.get`, request the appropriate fields. Note that the Python API Explorer can be **extremely** helpful: https://developers.google.com/apis-explorer/#p/sheets/v4/sheets.spreadsheets.get (it has an interactive and explanatory `fields` selector!)
comment on: http://stackoverflow.com/q/51302487

http://stackoverflow.com/q/51319065
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51319274
accepted answer: http://stackoverflow.com/a/51319274
has comment: http://stackoverflow.com/comment/89614069
has answer: http://stackoverflow.com/a/51319357
score: 1
tagged with: post
type: Question
upvote count: 2
answer count: 2
has title: Python/Django/Q search, How to find B field info. by searching A field info
has comment: http://stackoverflow.com/comment/89614064
has comment: http://stackoverflow.com/comment/89613960
favorite count: 0
possible better answer: http://stackoverflow.com/a/51319357
has comment: http://stackoverflow.com/comment/89614219
has body: Most examples are in the form of finding A in data A to Z. A DB table does not have a single field from A to Z. When a DB table has several fields together, I want to know the field I'm looking for as a field value and I want to figure out another value with that field value. For example, searching for a specific name in a DB that contains information from all the students will determine the age. from Python, Django DB My data consists of 3 rows: {title:'1', price:'20'} {title:'2', price:'30'} {title:'1', price:'10'} I want to find title '1' and then return price fileds Expexted Output: {title:'1', price:'20'} {title:'1', price:'10'} Views.py: @csrf_exempt def searching(request): if request.method == "POST": parameter = request.POST.get('title') searchResult = NaverData.objects.filter(Q(title__icontains=parameter)).distinct() ouput = searchResult return HttpResponse(ouput) else: #GET request return HttpResponse('GET REQUEST')
tagged with: django
tagged with: python
downvote count: 1

http://stackoverflow.com/a/51303122
upvote count: 2
has comment: http://stackoverflow.com/comment/89585071
has body: According to the documentation of zgeev (on http://www.netlib.org/lapack/explore-html/db/d55/group__complex16_g_eeigen_ga0eb4e3d75621a1ce1685064db1ac58f0.html#ga0eb4e3d75621a1ce1685064db1ac58f0): subroutine zgeev ( character JOBVL, character JOBVR, integer N, complex*16, dimension( lda, * ) A, integer LDA, complex*16, dimension( * ) W, complex*16, dimension( ldvl, * ) VL, integer LDVL, complex*16, dimension( ldvr, * ) VR, integer LDVR, complex*16, dimension( * ) WORK, integer LWORK, double precision, dimension( * ) RWORK, integer INFO ) The arrays you provide are of type complex(kind = 8) and not of type complex*16 and for RWord provided type real(kind = 8) instead of double precision. (Depending on the compiler the kind=8 can have a different meaning)
has comment: http://stackoverflow.com/comment/89589245
has comment: http://stackoverflow.com/comment/89583133
has comment: http://stackoverflow.com/comment/89585678
type: Answer
has comment: http://stackoverflow.com/comment/89585133
answers question: http://stackoverflow.com/q/51302912
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/89591151
has comment: http://stackoverflow.com/comment/89595946
has comment: http://stackoverflow.com/comment/89585350
has comment: http://stackoverflow.com/comment/89595726

http://stackoverflow.com/comment/89591529
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51294509
has text: @Vincent That is close to what the code in my answer does, except handles the remainder of the sleep precisely. This allows it to handle arbitrary points in the future. It would be nice if asyncio handled this automatically, but at this point it doesn't.
score: 0

http://stackoverflow.com/a/51269310
upvote count: 1
type: AcceptedAnswer
has body: I think the issue is you're mixing up datetime formats and string formats. from datetime import datetime time = datetime.strptime('01/01/2010', '%d/%m/%Y') newtime = datetime.strftime(time, '%d/%m/%Y') print(time, newtime) 2010-01-01 00:00:00 01/01/2010 Press any key to continue . . . Convert your date times to a string with the format you want using datetime.strftime, then you can use logic to do the calculation, i.e: A datetime object with value 2010-01-01 23:30:00 will always be converted to a string of type 2010-01-01 when using: value = datetime.strftime(value, '%Y-%m-%d') Can then perform logic on the two strings if value == newtime: print(value) Full example: from datetime import datetime time = datetime.strptime('01/01/2010 20:30:30', '%d/%m/%Y %H:%M:%S') newtime = datetime.strftime(time, '%d/%m/%Y') print(time) print(newtime) #Outputs: 2010-01-01 20:30:30 01/01/2010
type: Answer
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/51268834
accepted answer of: http://stackoverflow.com/q/51268834

file
tags question: http://stackoverflow.com/q/51219008
tags question: http://stackoverflow.com/q/51297805
type: Tag
tags question: http://stackoverflow.com/q/51191940
tags question: http://stackoverflow.com/q/51256300
tags question: http://stackoverflow.com/q/51310934
tags question: http://stackoverflow.com/q/51209186
tags question: http://stackoverflow.com/q/51321811
tag name: file
tags question: http://stackoverflow.com/q/51302203
tags question: http://stackoverflow.com/q/51176800
tags question: http://stackoverflow.com/q/51269269
tags question: http://stackoverflow.com/q/51288581
tags question: http://stackoverflow.com/q/51179833
tags question: http://stackoverflow.com/q/51275555
tags question: http://stackoverflow.com/q/51291013
tags question: http://stackoverflow.com/q/51313593
tags question: http://stackoverflow.com/q/51190501
tags question: http://stackoverflow.com/q/51225292
tags question: http://stackoverflow.com/q/51272446
tags question: http://stackoverflow.com/q/51300181
tags question: http://stackoverflow.com/q/51300363
tags question: http://stackoverflow.com/q/51287352
tags question: http://stackoverflow.com/q/51316221
tags question: http://stackoverflow.com/q/51210773
tags question: http://stackoverflow.com/q/51258273
tags question: http://stackoverflow.com/q/51256584
tags question: http://stackoverflow.com/q/51312198
tags question: http://stackoverflow.com/q/51167575
tags question: http://stackoverflow.com/q/51232745
tags question: http://stackoverflow.com/q/51258434
tags question: http://stackoverflow.com/q/51312142
tags question: http://stackoverflow.com/q/51213110
tags question: http://stackoverflow.com/q/51232315
tags question: http://stackoverflow.com/q/51187751
tags question: http://stackoverflow.com/q/51215981
tags question: http://stackoverflow.com/q/51299146

http://stackoverflow.com/comment/89620412
type: Comment
score: 0
comment on: http://stackoverflow.com/q/51321685
type: QuestionComment
has text: Ok, since you edited your question I assume this was a typo here on SO. Can you please include the full Traceback of the error you receive? I'm starting to wonder if the issue might be with your base class AdamsMethods

http://stackoverflow.com/q/51199309
downvote count: 0
has title: Pandas DataFrame to Dictionary with Tuples as Key and Values
score: 1
has comment: http://stackoverflow.com/comment/89380366
type: Question
has comment: http://stackoverflow.com/comment/89381404
has comment: http://stackoverflow.com/comment/89381434
tagged with: dataframe
has body: I need help doing the following: I have a CSV file as the following, loaded into a dataframe 'df'. There are multiple regions, different values for Memory, vCPUs and Storage corresponding to each 'Name'. There are 1700 rows in this dataframe. I need to create a dictionary that has the following: Key is a tuple with two elements: Name, and Region Value of the dictionary is a tuple: Windows On-demand cost and Linux On demand cost Ultimately, I want to create a program which does the following: The user inputs a certain CPU and Ram and Storage, and the program will sort through the data and pull the Name, as well as Windows and Linux prices for that processor if there is a match, or if not, will pull the processor closest to the inputted values. Thanks! Name Region API Memory vCPUs Storage Linux Windows 0 M1 General Purpose Small US West - NorCal m1.small 1.7 GiB 1 vCPUs 160 GiB $0.047000 hourly $0.078000 hourly 1 M1 General Purpose Medium US West - NorCal m1.medium 3.75 GiB 1 vCPUs 410 GiB $0.095000 hourly $0.157000 hourly 2 M1 General Purpose Large US West - NorCal m1.large 7.5 GiB 2 vCPUs 840 GiB $0.190000 hourly $0.314000 hourly 3 M1 General Purpose Extra Large US West - NorCal m1.xlarge 15.0 GiB 4 vCPUs 1680 GiB $0.379000 hourly $0.627000 hourly 4 C1 High-CPU Medium US West - NorCal c1.medium 1.7 GiB 2 vCPUs 350 GiB $0.148000 hourly $0.228000 hourly
answer count: 2
tagged with: pandas
upvote count: 1
has answer: http://stackoverflow.com/a/51200922
has comment: http://stackoverflow.com/comment/89380509
favorite count: 0
has comment: http://stackoverflow.com/comment/89380428
has answer: http://stackoverflow.com/a/51199605
type: UnansweredQuestion
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/89380976

http://stackoverflow.com/comment/89452230
score: 0
comment on: http://stackoverflow.com/a/51236631
type: Comment
type: AnswerComment
has text: Sorting is asymptotically suboptimal for this problem. O(n log n) vs O(n)

http://stackoverflow.com/comment/89337985
comment on: http://stackoverflow.com/a/51176849
type: AnswerComment
has text: anything inside os.popen(" ") will execute as it would in command terminal, so I will need to have more information but no reason to believe that it won't work
score: 0
type: Comment

http://stackoverflow.com/q/51171560
accepted answer: http://stackoverflow.com/a/51171714
has comment: http://stackoverflow.com/comment/89326081
has body: I have a data frame in pandas having two columns where each row is a list of strings, how would it be possible to check if there is word match(es) in these two columns on a unique row(flag column is the desired output) A B flag hello,hi,bye bye, also 1 but, as well see, pandas 0 I have tried df['A'].str.contains(df['B']) but I got this error TypeError: 'Series' objects are mutable, thus they cannot be hashed
has comment: http://stackoverflow.com/comment/89326337
tagged with: pandas
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/89325973
favorite count: 0
has title: compare two columns having list of strings in pandas
has answer: http://stackoverflow.com/a/51171714
tagged with: python
score: 2
type: AnsweredQuestion
upvote count: 2
has comment: http://stackoverflow.com/comment/89326229
type: Question

http://stackoverflow.com/a/51309480
answers question: http://stackoverflow.com/q/51308595
has body: Is this what you're trying to do? $ sed 's/\(<INCOND.*\)"/\1-DR"/' file <INCOND NAME="First-Cond-PROD-DR" /> <INCOND NAME="Second-Cond-PROD-DR" /> <INCOND NAME="Third-Cond-PROD-DR" />
score: 0
has comment: http://stackoverflow.com/comment/89600691
type: Answer

http://stackoverflow.com/a/51331729
has comment: http://stackoverflow.com/comment/89658036
has comment: http://stackoverflow.com/comment/89653087
type: Answer
has comment: http://stackoverflow.com/comment/89752230
has comment: http://stackoverflow.com/comment/89652060
has comment: http://stackoverflow.com/comment/89657417
upvote count: 1
answers question: http://stackoverflow.com/q/51193713
score: 1
has comment: http://stackoverflow.com/comment/89659499
has body: Okay, I finally had time to look at this. I will address each point of yours and then show the changes in the code. Let me know if you have any questions, or suggestions. Looks like you were able to do this yourself well enough. 1.a. This can be taken care of by blurring the image before doing any processing to it. The following changes to the code were made to accomplish this; ... start_time = time.time() blur_img = cv2.GaussianBlur(img,(5,5),0) #here # Use kmeans to convert to 2 color image hsv_img = cv2.cvtColor(blur_img, cv2.COLOR_BGR2HSV) ... I have changed the code to remove points that are on a line that perfectly follows the side of the image. It should be basically impossible for a grass edge to also coincide with this. ... allpnts = cv2.approxPolyDP(cnt,epsilon,True) new_allpnts = [] for i in range(len(allpnts)): a = (i-1) % len(allpnts) b = (i+1) % len(allpnts) if ((allpnts[i,0,0] == 0 or allpnts[i,0,0] == (img.shape[1]-1)) and (allpnts[i,0,1] == 0 or allpnts[i,0,1] == (img.shape[0]-1))): tmp1 = allpnts[a,0] - allpnts[i,0] tmp2 = allpnts[b,0] - allpnts[i,0] if not (0 in tmp1 and 0 in tmp2): new_allpnts.append(allpnts[i]) else: new_allpnts.append(allpnts[i]) ... cv2.drawContours(pntscanvas, new_allpnts, -1, (0, 0, 255), 2) ... Due to how the contours are found in the image, we can simply flip the thresholding function and find the contour around the other part of the image. Changes are below; ... #Extract contours from the mask ret,thresh = cv2.threshold(mask,250,255,cv2.THRESH_BINARY) #here im2,contours,hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) ... As for the color differences, you have converted your image into HSV format and before saving you are not switching it back to BGR. This change to HSV does give you better results so I would keep it, but it is a different palette. Changes are below; ... cv2.imshow('mask.bmp',mask) res2 = cv2.cvtColor(res2, cv2.COLOR_HSV2BGR) cv2.imwrite('CvKmeans2Color.bmp',res2) cv2.imshow('C…
downvote count: 0
has comment: http://stackoverflow.com/comment/89653312
has comment: http://stackoverflow.com/comment/89655869

http://stackoverflow.com/comment/89414552
score: 2
comment on: http://stackoverflow.com/q/51216292
has text: @tgikal: It's almost never necessary to use `keys()`. The dictionary is iterable, yielding its keys directly (and the `in` operator checks for keys in the dictionary as well). You're also not quite right that `keys` returns a list (that used to be true in Python 2, but is not any more). These days it returns a dictionary view object, which has some of the `set` API but doesn't need to copy any data (it just looks it up in the dictionary object).
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51317919
has comment: http://stackoverflow.com/comment/89612150
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89639729
tagged with: python
tagged with: web2py
answer count: 0
has body: I am following the web2py tutorial and am trying to execute the example of creating an image blog in Chapter 3.3: http://web2py.com/books/default/chapter/29/03/overview#An-image-blog After having removed menu.py and having replaced db.py with the code db = DAL("sqlite://storage.sqlite") db.define_table('image', Field('title', unique=True), Field('file', 'upload'), format = '%(title)s') db.define_table('post', Field('image_id', 'reference image'), Field('author'), Field('email'), Field('body', 'text')) db.image.title.requires = IS_NOT_IN_DB(db, db.image.title) db.post.image_id.requires = IS_IN_DB(db, db.image.id, '%(title)s') db.post.author.requires = IS_NOT_EMPTY() db.post.email.requires = IS_EMAIL() db.post.body.requires = IS_NOT_EMPTY() db.post.image_id.writable = db.post.image_id.readable = False , I am trying to access the database administration interface, but get an error ticket which starts with the following information: Traceback (most recent call last): File "C:\Users\username\Documents\Python lokal\web2py\gluon\restricted.py", line 219, in restricted exec(ccode, environment) File "c:/Users/username/Documents/Python lokal/web2py/applications/HB91_imageblog/views/appadmin.html", line 482, in &lt;module&gt; NameError: name 'configuration' is not defined I am not sure what I am missing, since I have exactly followed the tutorial.
type: Question
has title: Database administration not accessible in web2py
has comment: http://stackoverflow.com/comment/89629340
score: 0
has comment: http://stackoverflow.com/comment/89621653
has comment: http://stackoverflow.com/comment/89630909

http://stackoverflow.com/q/51290828
accepted answer: http://stackoverflow.com/a/51292299
type: Question
answer count: 2
score: 12
possible better answer: http://stackoverflow.com/a/75980877
has answer: http://stackoverflow.com/a/75980877
has title: Individual axes limits for pairplot in python
favorite count: 0
upvote count: 12
tagged with: seaborn
tagged with: python
type: AnsweredQuestion
has body: I'm fairly new to python and I'm trying to figure out how to set limits for individual axes for a pairplot. I know that using pairplot.set(xlim=(0,100), ylim = (0,100)) will set all the axes in a pairplot to go from 0 to 100, but some of my variables range from 0 to 300000 while others range from 0 80. I'm trying to avoid the auto scale feature because I'm removing some data occasionally but want to keep the context of the original set. I get something like below for example example
downvote count: 0
has answer: http://stackoverflow.com/a/51292299

http://stackoverflow.com/comment/89405328
type: AnswerComment
type: Comment
has text: @MiladKh I don't think so. This is a non-standard encoding so you either have to make it conform to a certain standard or parse it manually.
comment on: http://stackoverflow.com/a/51204341
score: 0

http://stackoverflow.com/comment/89817536
type: Comment
score: 0
type: AnswerComment
has text: In the documentation the algorithm was performed for a simple image containing coins. For the image you provided there were many holes inside which needed to be filled hence I performed opening morphology function.
comment on: http://stackoverflow.com/a/51342101

http://stackoverflow.com/q/51251479
accepted answer: http://stackoverflow.com/a/51251547
possible better answer: http://stackoverflow.com/a/51251573
has answer: http://stackoverflow.com/a/51251800
has answer: http://stackoverflow.com/a/51251573
type: Question
has body: I need help to get a random 4 digit long number with no repeated digits inside the number so I have import random numbers = random.sample(range(10), 4) Would this be the best way to go at it? I also need help with making sure the first digit is not 0, how could I do that? Cheers for the input
score: -6
upvote count: 0
has title: Python 3: How to get a random 4 digit number?
answer count: 7
has answer: http://stackoverflow.com/a/51251547
has answer: http://stackoverflow.com/a/71010985
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51251570
tagged with: python
has answer: http://stackoverflow.com/a/51251620
has answer: http://stackoverflow.com/a/51252137
downvote count: 6
type: AnsweredQuestion

http://stackoverflow.com/q/51282706
score: 1
favorite count: 0
has title: How to make geoencoding with Google Maps faster?
has comment: http://stackoverflow.com/comment/89543073
type: Question
has comment: http://stackoverflow.com/comment/89543262
tagged with: python
has answer: http://stackoverflow.com/a/51282868
answer count: 1
has comment: http://stackoverflow.com/comment/89543033
linked to: http://stackoverflow.com/q/51283361
upvote count: 1
has comment: http://stackoverflow.com/comment/89543161
tagged with: performance
tagged with: google-maps
has body: This is my code to extract latitudes and longitudes from location addresses in a CSV file. import pandas as pd import requests import json import time GOOGLE_MAPS_API_URL = 'https://maps.googleapis.com/maps/api/geocode/json' API_key= 'the-key' def gmaps_geoencoder(address): req = requests.get(GOOGLE_MAPS_API_URL+'?address='+address+'&amp;key='+API_key) res = req.json() result = res['results'][0] lat = result['geometry']['location']['lat'] lon = result['geometry']['location']['lng'] return lat, lon input_csv_file = r'path\to\location_list_100.csv' output_csv_file = r'path\to\location_list_100_new.csv' df = pd.read_csv(input_csv_file) #size of chunks of data to write to the csv chunksize = 10 t = time.time() for i in range(len(df)): place = df['ADDRESS'][i] lat, lon, res = gmaps_geoencoder(place) df['Lat'][i] = lat df['Lon'][i] = lon df.to_csv(output_csv_file, index=False, chunksize=chunksize) #size of data to append for each loop print('Time taken: '+str(time.time() - t)+'s') It took 47.75818920135498s for 100 records. That is, ~0.5s per record. How do I make it faster? I have ~ 1 million records to convert, and at this rate, it would take almost 6 days to finish the process!!! What is taking the time here: iterating through the dataframe, or fetching data with the gmaps API? If its the former, I suppose there should be some way to make it faster. But if its the latter, is there any fix?
has comment: http://stackoverflow.com/comment/89543233
tagged with: dataframe
type: UnansweredQuestion
tagged with: pandas
downvote count: 0
has comment: http://stackoverflow.com/comment/89543124

http://stackoverflow.com/q/51318246
answer count: 4
has answer: http://stackoverflow.com/a/51318853
has answer: http://stackoverflow.com/a/51318278
linked to: http://stackoverflow.com/q/4260280
accepted answer: http://stackoverflow.com/a/51318268
has answer: http://stackoverflow.com/a/51318513
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51318268
tagged with: list-comprehension
type: Question
has comment: http://stackoverflow.com/comment/89612427
score: 0
has title: Python list comprehension: assigning values in if else statement
has body: I am trying to write a List comprehension for below for loop in python num_list = [] for num in range(10): if num % 2 == 0: num_list.append('EVEN') else: num_list.append('ODD') I wrote something like [num if num % 2 == 0 'EVEN' else 'ODD' for num in range(10)] and [num if num % 2 == 0 then 'EVEN' else 'ODD' for num in range(10)] but both are giving syntax errors and not valid. I am new to pyhton, so not sure if this can be translated to a comprehension or not. Any help would be appreciated.
tagged with: python
possible better answer: http://stackoverflow.com/a/51318278

http://stackoverflow.com/comment/89554274
has text: updated it again
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51286264

http://stackoverflow.com/a/51244535
has comment: http://stackoverflow.com/comment/89499395
has comment: http://stackoverflow.com/comment/89469968
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: The @property decorator on a function creates a new property object and sets the decorated function as the getter. So within the same class, the @p.getter decorator is not very useful, no. However, the decorator is very useful if you wanted to override the getter in a subclass, or a reuse just the setter of the property on, but on a different class altogether: class Foo(object): @property def p(self): return self._p @p.setter def p(self, value): self._p = value class Bar(Foo): @Foo.p.getter def p(self): return self._p + 10 or by copying the property object across to a different class: class NotASubclass(object): @Foo.p.getter def p(self): return self._p * 10 Now Bar()and NotASubclass have a different getter for their property p, but both reuse the setter defined on the property for Foo(). In both cases the @p.getter decorator creates a new property instance to store as an attribute of the class object, but their fset attributes all point to the same, single function object that acts as the setter. This is why it is enough to just reference @Foo.p.getter in either case; you only need the single property instance in the class namespace. Also see How does the @property decorator work? and Python overriding getter without setter
accepted answer of: http://stackoverflow.com/q/51244348
has comment: http://stackoverflow.com/comment/89467629
upvote count: 3
score: 3
answers question: http://stackoverflow.com/q/51244348

http://stackoverflow.com/a/51258652
type: Answer
upvote count: 0
score: -2
downvote count: 2
has body: Try to use pipenv to manage your dependencies. Here: pipenv
answers question: http://stackoverflow.com/q/51258497

http://stackoverflow.com/comment/89439562
score: 1
has text: This is excellent, I like the one that uses np.array + repeat, thanks!
type: AnswerComment
comment on: http://stackoverflow.com/a/51229245
type: Comment

http://stackoverflow.com/comment/89614450
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51319253
has text: It works! Thank you very much Rakesh and shmee
score: 0

http://stackoverflow.com/comment/89552102
score: 0
has text: `x * y[:,None,None]`?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51287259

http://stackoverflow.com/comment/89551983
score: 0
has text: `regex` is usually not a solution but the part of the problem, avoid it, if you can do that using simpler methods.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51286999

http://stackoverflow.com/comment/89583782
comment on: http://stackoverflow.com/q/51303550
score: 0
type: Comment
type: QuestionComment
has text: Please post the actual code that tries to read the file. Perhaps it is cased wrong. `DrumsInfo.csv` will read `drumsinfo.csv` on a windows machine but not on a server

http://stackoverflow.com/a/51170991
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 14
score: 14
has comment: http://stackoverflow.com/comment/99479110
answers question: http://stackoverflow.com/q/51170763
accepted answer of: http://stackoverflow.com/q/51170763
has body: There are two solutions: df.col.apply method is more straightforward but also a little bit slower: In [1]: import pandas as pd In [2]: import re In [3]: df = pd.DataFrame({'col1':[1,2,3,4,5], 'col2':['admin', 'aa', 'bb', 'c_admin_d', 'ee_admin']}) In [4]: df Out[4]: col1 col2 0 1 admin 1 2 aa 2 3 bb 3 4 c_admin_d 4 5 ee_admin In [5]: r = re.compile(r'.*(admin).*') In [6]: df.col2.apply(lambda x: bool(r.match(x))) Out[6]: 0 True 1 False 2 False 3 True 4 True Name: col2, dtype: bool In [7]: %timeit -n 100000 df.col2.apply(lambda x: bool(r.match(x))) 167 µs ± 1.02 µs per loop (mean ± std. dev. of 7 runs, 100000 loops each) np.vectorize method require import numpy, but it's more efficient (about 4 times faster in my timeit test). In [1]: import numpy as np In [2]: import pandas as pd In [3]: import re In [4]: df = pd.DataFrame({'col1':[1,2,3,4,5], 'col2':['admin', 'aa', 'bb', 'c_admin_d', 'ee_admin']}) In [5]: df Out[5]: col1 col2 0 1 admin 1 2 aa 2 3 bb 3 4 c_admin_d 4 5 ee_admin In [6]: r = re.compile(r'.*(admin).*') In [7]: regmatch = np.vectorize(lambda x: bool(r.match(x))) In [8]: regmatch(df.col2.values) Out[8]: array([ True, False, False, True, True]) In [9]: %timeit -n 100000 regmatch(df.col2.values) 43.4 µs ± 362 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each) Since you have changed your question to check any cell, and also concern about time efficiency: # if you want to check all columns no mater what `dtypes` they are dfs = df.astype(str, copy=True, errors='raise') regmatch(dfs.values) # This will return a 2-d array of booleans regmatch(dfs.values).any() # For existence. You can still use df.applymap method, but again, it will be slower. dfs = df.astype(str, copy=True, errors='raise') r = re.compile(r'.*(admin).*') dfs.applymap(lambda x: bool(r.match(x))) # This will return a dataframe of booleans. dfs.applymap(lambda x: bool(r.match(x))).any().any() # For existence.

http://stackoverflow.com/q/51168841
accepted answer: http://stackoverflow.com/a/51169179
type: Question
answer count: 1
downvote count: 0
tagged with: keras
favorite count: 0
score: 3
tagged with: tensorboard
tagged with: python
has title: Keras - TensorBoard does not save the logs file
has answer: http://stackoverflow.com/a/51169179
upvote count: 3
type: AnsweredQuestion
has body: As an example of network, I used the first example here I would like to use tensorboard with this network. After read this documentation about how to use TensorBoard, I added these commands to the code: from keras.callbacks import TensorBoard TensorBoard("Directory path that contains the log files") The output sounds correct: Out[3]: &lt;keras.callbacks.TensorBoard at 0x7f14730e79b0&gt; But there is nothing in the directory... What I did wrong ? Here is the complete code: import keras from keras.models import Sequential from keras.layers import Dense, Dropout, Activation from keras.optimizers import SGD from keras.callbacks import TensorBoard # Generate dummy data import numpy as np x_train = np.random.random((1000, 20)) y_train = keras.utils.to_categorical(np.random.randint(10, size=(1000, 1)), num_classes=10) x_test = np.random.random((100, 20)) y_test = keras.utils.to_categorical(np.random.randint(10, size=(100, 1)), num_classes=10) model = Sequential() # Dense(64) is a fully-connected layer with 64 hidden units. # in the first layer, you must specify the expected input data shape: # here, 20-dimensional vectors. model.add(Dense(64, activation='relu', input_dim=20)) model.add(Dropout(0.5)) model.add(Dense(64, activation='relu')) model.add(Dropout(0.5)) model.add(Dense(10, activation='softmax')) sgd = SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True) model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy']) model.fit(x_train, y_train, epochs=20, batch_size=128) score = model.evaluate(x_test, y_test, batch_size=128) TensorBoard("Directory path that contains the log files")

django-apps
tag name: django-apps
tags question: http://stackoverflow.com/q/51179583
type: Tag

http://stackoverflow.com/comment/89573462
type: QuestionComment
has text: Well If there isn't a way to make a prediction without the full Keras package then yep you're right that is my problem
comment on: http://stackoverflow.com/q/51297972
score: 0
type: Comment

http://stackoverflow.com/comment/89370462
comment on: http://stackoverflow.com/q/51194171
type: Comment
score: 1
type: QuestionComment
has text: Use date_range method whereever you cant to create a date range. dates = pd.DataFrame({ 'DateCol' : pd.date_range('2018-01-01','2019-12-01',freq='M'), 'count' : np.random.randint(5,size=23) } )

http://stackoverflow.com/q/51259003
has comment: http://stackoverflow.com/comment/89496498
upvote count: 5
has comment: http://stackoverflow.com/comment/89500771
has comment: http://stackoverflow.com/comment/89496545
has comment: http://stackoverflow.com/comment/89496574
has comment: http://stackoverflow.com/comment/89497709
score: 4
linked to: http://stackoverflow.com/q/34147515
duplicate of: http://stackoverflow.com/q/34147515
favorite count: 0
has comment: http://stackoverflow.com/comment/89496583
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89496669
tagged with: python
has comment: http://stackoverflow.com/comment/89496718
has comment: http://stackoverflow.com/comment/89497369
answer count: 0
has comment: http://stackoverflow.com/comment/89496610
downvote count: 1
type: Question
has body: Please clarify my doubt about python identity operators is and is not. a,b = 10.0, 10.0 print (a is b) will result in True where as a = 10.0 b = 10.0 print (a is b) will result in False Why in the first case the id() function results is same value and different in the second case
has title: Python identity operators
has comment: http://stackoverflow.com/comment/89496532

http://stackoverflow.com/comment/89572934
type: Comment
type: QuestionComment
has text: I meant large input file itself. (Corrected my description) @Anthon I have a constraint where the file has duplicate keys. Just looking for some tweek possible
comment on: http://stackoverflow.com/q/51289824
score: 0

http://stackoverflow.com/comment/89457889
comment on: http://stackoverflow.com/q/51239512
score: 0
type: QuestionComment
has text: Where is `url` defined?
type: Comment

http://stackoverflow.com/q/51241367
has comment: http://stackoverflow.com/comment/89461644
type: Question
has answer: http://stackoverflow.com/a/65115447
has answer: http://stackoverflow.com/a/71429859
tagged with: matplotlib
score: 18
has answer: http://stackoverflow.com/a/72416163
has comment: http://stackoverflow.com/comment/89461681
possible better answer: http://stackoverflow.com/a/71429859
has body: Yet another question about matplotlib 3d surfaces... I have code which adds a scatter point to a matplotlib surface graph. The problem that I have is that the point always appears behind the surface, regardless of which angle you view it from. If I cobble an (admittedly ugly) version using 3 short lines to mark the same point, it is visible. I have turned off the depthshade function, so it isn't this. Can anybody explain what is going on and how I can correct it? Here is a simplified version of the code: import pandas as pd import matplotlib import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import numpy as np df = pd.DataFrame({10: {10: 1,15: 1,20: 1,25: 1,30: 1,35: 1,40: 1,45: 1,50: 1,55: 1,60: 1,65: 1,70: 1,75: 1,80: 1,85: 1,90: 1}, 15: {10: 4,15: 1,20: 1,25: 1,30: 1,35: 1,40: 1,45: 1,50: 1,55: 1,60: 1,65: 1,70: 1,75: 1,80: 1,85: 1,90: 1}, 20: {10: 6,15: 3,20: 1,25: 1,30: 1,35: 1,40: 1,45: 1,50: 1,55: 1,60: 1,65: 1,70: 1,75: 1,80: 1,85: 1,90: 1}, 25: {10: 7,15: 5,20: 3,25: 1,30: 1,35: 1,40: 1,45: 1,50: 1,55: 1,60: 1,65: 1,70: 1,75: 1,80: 1,85: 1,90: 1}, 30: {10: 9,15: 6,20: 4,25: 3,30: 1,35: 1,40: 1,45: 1,50: 1,55: 1,60: 1,65: 1,70: 1,75: 1,80: 1,85: 1,90: 1}, 35: {10: 10,15: 7,20: 5,25: 4,30: 2,35: 1,40: 1,45: 1,50: 1,55: 1,60: 1,65: 1,70: 1,75: 1,80: 1,85: 1,90: 1}, 40: {10: 11,15: 8,20: 6,25: 4,30: 3,35: 2,40: 1,45: 1,50: 1,55: 1,60: 1,65: 1,70: 1,75: 1,80: 1,85: 1,90: 1}, 45: {10: 12,15: 9,20: 7,25: 5,30: 4,35: 3,40: 2,45: 1,50: 1,55: 1,60: 1,65: 1,70: 1,75: 1,80: 1,85: 1,90: 1}, 50: {10: 13,15: 9,20: 7,25: 6,30: 5,35: 4,40: 3,45: 2,50: 1,55: 1,60: 1,65: 1,70: 1,75: 1,80: 1,85: 1,90: 1}, 55: {10: 14,15: 10,20: 8,25: 7,30: 5,35: 4,40: 3,45: 3,50: 2,55: 1,60: 1,65: 1,70: 1,75: 1,80: 1,85: 1,90: 1}, 60: {10: 15,15: 11,20: 9,25: 7,30: 6,35: 5,40: 4,45: 3,50: 3,55: 2,60: 1,65: 1,70: 1,75: 1,80: 1,85: 1,90: 1}, 65: {10: 16,15: 12,20: 9,25: 8,30: 6,35: 5,40: 5,45: 4,50: 3,55: 2,60: 2,65: 1,70: 1,75: 1,80: 1,85: 1,90: 1}, 70: {10: 17,15: 12,20: 1…
has title: matplotlib surface plot hides scatter points which should be in front
favorite count: 0
upvote count: 18
has comment: http://stackoverflow.com/comment/89461628
tagged with: python
answer count: 4
has answer: http://stackoverflow.com/a/51243274
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51243274
downvote count: 0

http://stackoverflow.com/comment/89551672
has text: @Anya: yes, but you do not create that immediately of course. It is more that each time you get an item, like `some_dict[''foo']` and `foo` is missing, you invoke `tree`, which will thus construct again a `defaultdict` with `tree` as factory. But you can indeed walk arbitrary deep in this `some_dict`.
score: 1
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51286496

datetime
tags question: http://stackoverflow.com/q/51199565
tags question: http://stackoverflow.com/q/51251113
tags question: http://stackoverflow.com/q/51268856
tags question: http://stackoverflow.com/q/51168640
tags question: http://stackoverflow.com/q/51206500
tags question: http://stackoverflow.com/q/51194450
tags question: http://stackoverflow.com/q/51173079
tags question: http://stackoverflow.com/q/51216169
tags question: http://stackoverflow.com/q/51194170
tags question: http://stackoverflow.com/q/51247535
tags question: http://stackoverflow.com/q/51171953
tags question: http://stackoverflow.com/q/51208570
tags question: http://stackoverflow.com/q/51194745
tags question: http://stackoverflow.com/q/51209020
tags question: http://stackoverflow.com/q/51235708
tags question: http://stackoverflow.com/q/51268834
tags question: http://stackoverflow.com/q/51189456
tags question: http://stackoverflow.com/q/51194350
tags question: http://stackoverflow.com/q/51232224
tags question: http://stackoverflow.com/q/51268370
tags question: http://stackoverflow.com/q/51303059
tags question: http://stackoverflow.com/q/51303794
tags question: http://stackoverflow.com/q/51197654
tags question: http://stackoverflow.com/q/51306939
tags question: http://stackoverflow.com/q/51287504
tag name: datetime
tags question: http://stackoverflow.com/q/51193392
tags question: http://stackoverflow.com/q/51178644
tags question: http://stackoverflow.com/q/51294657
tags question: http://stackoverflow.com/q/51324178
tags question: http://stackoverflow.com/q/51304723
tags question: http://stackoverflow.com/q/51275976
tags question: http://stackoverflow.com/q/51179796
tags question: http://stackoverflow.com/q/51234722
type: Tag
tags question: http://stackoverflow.com/q/51224774
tags question: http://stackoverflow.com/q/51245938
tags question: http://stackoverflow.com/q/51232664
tags question: http://stackoverflow.com/q/51255199
tags question: http://stackoverflow.com/q/51253312
tags question: http://stackoverflow.com/q/51316881
tags question: http://stackoverflow.com/q/51237176
tags question: http://stackoverflow.com/q/51293632
tags question: http://stackoverflow.com/q/51251934
tags question: http://stackoverflow.com/q/51193834
tags question: http://stackoverflow.com/q/51191665
tags question: http://stackoverflow.com/q/51281477
tags question: http://stackoverflow.com/q/51297844
tags question: http://stackoverflow.com/q/51283416

modelica
tag name: modelica
tags question: http://stackoverflow.com/q/51265302
type: Tag

http://stackoverflow.com/comment/89326490
type: AnswerComment
has text: @PJG, No problem, in around 10 mins you can accept the answer if you wish (green tick on left).
type: Comment
comment on: http://stackoverflow.com/a/51171896
score: 0

http://stackoverflow.com/q/51215583
type: Question
upvote count: 7
answer count: 1
tagged with: google-cloud-pubsub
tagged with: google-api-python-client
favorite count: 0
accepted answer: http://stackoverflow.com/a/51215846
has title: Google Cloud Pub Sub With Service Account
tagged with: python
has answer: http://stackoverflow.com/a/51215846
type: AnsweredQuestion
has body: Hi everyone I am having an issue with pub sub that is driving me nuts. Basically I have a service account with admin priivs for pubsub but I can't get any thing to work and am getting the following error: ERROR:root:AuthMetadataPluginCallback "" raised exception! Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/grpc/_plugin_wrapping.py", line 77, in call callback_state, callback)) File "/usr/local/lib/python2.7/dist-packages/google/auth/transport/grpc.py", line 77, in call callback(self._get_authorization_headers(context), None) File "/usr/local/lib/python2.7/dist-packages/google/auth/transport/grpc.py", line 61, in _get_authorization_headers self._credentials.before_request( AttributeError: 'str' object has no attribute 'before_request' Code is super simple from google.cloud import pubsub credentials = '/home/airflow/Desktop/test/config/test.json' publisher = pubsub.PublisherClient(credentials=credentials) topic_path = publisher.topic_path("test-proj", "test") for n in range(1, 2): data = u'Message number {}'.format(n) # Data must be a bytestring data = data.encode('utf-8') test = publisher.publish(topic_path, data=data).result() print(test, "s") Amy help would be really appreciated as the error message doesn't make much sense to me. Thanks
downvote count: 0
score: 7

http://stackoverflow.com/q/51219136
score: 1
tagged with: python-multiprocessing
type: Question
has answer: http://stackoverflow.com/a/51223798
downvote count: 0
answer count: 2
tagged with: multiprocess
favorite count: 0
has title: Multiprocessing using Python: How to parallelize nested loops and append results to dictionary?
type: UnansweredQuestion
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/51219246
has body: I am new to multiprocessing in Python and currently I am not sure how to proceed with the problem in my hand. I am trying to implement a function which has two loops (inner and outer loop) and append the results in a dictionary. The function and what I would like to achieve looks something like: def func(p, a): return p*a p_dict = dict() for p in all_possible_ps: #I would like to parallelize this alist = list() for a in all_possible_as: #And this for loop alist.append(func(p,a)) p_dict[p] = alist For the inner loop, I believe I can instantiate a pool, p=Pool(), then p.map(func, all_possible_as) to get alist. I am not sure how to parallelize both loops and at the same time distribute the number of processes for both loops.

http://stackoverflow.com/a/51312217
has comment: http://stackoverflow.com/comment/89601404
has comment: http://stackoverflow.com/comment/89601271
upvote count: 2
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89601370
type: Answer
score: 2
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51312186
has body: You can do this fairly quickly like so: my_matcher = {'r':0, 'b':1} new_input = [my_matcher.get(val) for val in c] If you need it to be a tuple, you can wrap it with tuple(new_input)
answers question: http://stackoverflow.com/q/51312186

django-rest-auth
tag name: django-rest-auth
tags question: http://stackoverflow.com/q/51255868
type: Tag

http://stackoverflow.com/a/51222419
upvote count: 3
has comment: http://stackoverflow.com/comment/89426104
has comment: http://stackoverflow.com/comment/89431753
has comment: http://stackoverflow.com/comment/89432006
downvote count: 0
has comment: http://stackoverflow.com/comment/89426024
has comment: http://stackoverflow.com/comment/89425945
answers question: http://stackoverflow.com/q/51221465
type: Answer
has body: You might want to make your C program easier to deal with readline() methods of expect by adding \n after all printf() outputs #include "stdio.h" #include "stdlib.h" int main(int argc, char **argv) { int x; printf("hello\n"); scanf("%d", &amp;x); printf("x=%d\n",x); } Then you can write Python program like this. import pexpect x = pexpect.spawn('./a.out') print(x.readline()) # reads 'hello' x.sendline('6') # sends 6 with \n print(x.readline()) # reads 6 print(x.readline()) # reads x=6 Output b'hello\r\n' b'6\r\n' b'x=6\r\n' Output can be converted from bytes to string using str() or decode() functions For your purpose, using cmd module would be more hepful. Here is just sample example of how it works. import cmd, os class MyCli(cmd.Cmd): intro = "Welcome to my shell" prompt = '&gt;' def emptyline(self): # Do nothing for empty line pass def do_mycmd(self, user_cmd): # When user enters mycmd execute a.out os.system("./a.out") def default(self, user_cmd): # When user gives input that is not command print message print("Unknown command") def do_exit(self, user_cmd): # Exit command print("goodbye") return True ins1 = MyCli() ins1.cmdloop() Output Welcome to my shell &gt; &gt;mycmd hello 25 x=25 &gt; &gt;exit goodbye
score: 3

http://stackoverflow.com/q/51310762
tagged with: python
has comment: http://stackoverflow.com/comment/89598738
has answer: http://stackoverflow.com/a/51311187
has title: Run python 3.6 on 2.7
has comment: http://stackoverflow.com/comment/89598274
has comment: http://stackoverflow.com/comment/89598494
type: Question
has comment: http://stackoverflow.com/comment/89598910
has comment: http://stackoverflow.com/comment/89598303
has comment: http://stackoverflow.com/comment/89598184
answer count: 1
score: 0
has comment: http://stackoverflow.com/comment/89598973
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/89598640
favorite count: 0
tagged with: python-3.x
has body: We have python scripts developed using py3.6, but while deploying we found that liunx machines are on 2.7. Is there any way we still execute our 3.6 version scripts on 2.7 ? I found the other way of running , but not getting the leads for 3.6 on 2.7.
has comment: http://stackoverflow.com/comment/89598839
type: UnansweredQuestion

http://stackoverflow.com/comment/89432636
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51219779
type: Comment
has text: how would you have a class utilise both list() and dict() when they both use the __itter__() data model? is that possible?

http://stackoverflow.com/q/51202439
answer count: 1
favorite count: 0
tagged with: python
has title: numpy min() between two vectors?
linked to: http://stackoverflow.com/q/46558114
score: 2
upvote count: 3
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/46558114
downvote count: 1
has answer: http://stackoverflow.com/a/51202524
has body: Any idea how to do intersection between two vectors with numpy. F.e.: np.random.randint(0,10,3) array([5, 6, 7]) np.random.randint(0,10,3) array([6, 6, 3]) [5,6,3] i.e. select the minimum numbers.
tagged with: intersection
type: Question
tagged with: numpy
tagged with: min

http://stackoverflow.com/comment/89485242
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/51248813
has text: It [seems to be a bug in Tensorflow v1.2](https://github.com/openai/pixel-cnn/issues/17). If you can, upgrade the tensorflow and see if it is resolved.
type: Comment

http://stackoverflow.com/q/51294105
has comment: http://stackoverflow.com/comment/89566911
type: Question
tagged with: urllib2
has title: Convert cURL request to Python2 urllib2 request
tagged with: python-2.6
score: 0
has body: I am trying to convert the below code in curl to python2 urllib2 request call for performing a "PUT" operation, it works fine with cURL but i am clueless on getting this converted to python2 code. cURL curl -X PUT -u myUser:myPassword -T test.txt “http://localhost:8081/artifactory/libs-release-local/test/test.txt” The problem i face is with the "-T" flag i am not sure how set this in urllib2 call. I tried using Postman for help by adding file to Body->form-data->file But the code is converted as below which i suspect is not the transfer file call. curl -X PUT \ http://localhost:8081/artifactory/my-repository/my/new/artifact/directory/file.txt \ -H 'Cache-Control: no-cache' \ -H 'Postman-Token: 4ffbfca4-a4be-09de-c8ab-0731a2d67009' \ -H 'content-type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW' \ -F '=@C:\Devops\file.txt' I tried looking at documentations specified here under -T/--upload-file it does not help. Any suggestions. https://www.computerhope.com/unix/curl.html https://curl.haxx.se/libcurl/c/options-in-examples.html
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89566940
has comment: http://stackoverflow.com/comment/89566103
tagged with: curl
has comment: http://stackoverflow.com/comment/89566943
answer count: 0
tagged with: artifactory

http://stackoverflow.com/comment/89523281
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51272531
has text: Ntrain is equal to 774. Shape of Xtrain is (774, 12) and Ytrain (774, )

http://stackoverflow.com/a/51240381
type: Answer
answers question: http://stackoverflow.com/q/51238873
upvote count: 1
score: 1
downvote count: 0
has body: go with pandorable, my_dictionary={} for k, v in df.groupby('user'): my_dictionary[k]=[len(v),v.iloc[-1]['speed']] print(my_dictionary) {'Anna': [3, 1.1], 'Bell': [2, 1.4], 'Chad': [1, 1.5]}

http://stackoverflow.com/q/51209020
tagged with: python
upvote count: 4
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/89399638
type: Question
accepted answer: http://stackoverflow.com/a/51209368
has answer: http://stackoverflow.com/a/51209267
score: 4
has title: epoch nanoseconds to normal time
tagged with: python-2.7
has answer: http://stackoverflow.com/a/51209368
answer count: 2
tagged with: pandas
favorite count: 0
possible better answer: http://stackoverflow.com/a/51209267
tagged with: epoch
tagged with: datetime
has body: i have a data as name time 0 acn 1530677359000000000 1 acn 1530677363000000000 2 acn 1530681023000000000 3 acn 1530681053000000000 4 acn 1530681531000000000 5 acn 1530681561000000000 So I would like to change the time column to datetime format. I tried doing this by executing: df['time'] = pd.to_datetime(df['time']) but it gives improper output as : Out[70]: 0 2078-09-01 09:55:28.826007552 1 2078-10-17 17:02:08.826007552 2 2194-10-10 19:42:08.826007552 3 2195-09-23 01:02:08.826007552 4 2210-11-16 10:48:48.826007552 5 2211-10-29 16:08:48.826007552 I am on python 2.7. kindly take a look.

http://stackoverflow.com/q/51212795
upvote count: 3
tagged with: exception
answer count: 3
has answer: http://stackoverflow.com/a/51963175
tagged with: pylint
tagged with: python
has answer: http://stackoverflow.com/a/51716089
tagged with: python-3.x
downvote count: 0
type: UnansweredQuestion
has body: Been trying to use Pylint 1.9.2 with Python 3.7 and Flask 1.0.2 in visual studio code 1.25, I keep getting the following error on Pylint on the first line of my code. F0002:: generator raised StopIteration { "resource": "/d:/social network/models.py", "owner": "python", "code": "F0002", "severity": 8, "message": "F0002:&lt;class 'RuntimeError'&gt;: generator raised StopIteration", "source": "pylint", "startLineNumber": 1, "startColumn": 1, "endLineNumber": 1, "endColumn": 1 } I have no clue at all what is the cause of this error as it seems. appear regardless of the content of my code(I tried "import datetime" and from peewee import *, both have the same error) only appear in one file of the whole project. other files have module importation but see no errors of this one. Please help if you have any idea what is causing this error! Thank you!
score: 3
has title: Strange Pylint Error on Python 3.7 import command
type: Question
tagged with: visual-studio-code
has answer: http://stackoverflow.com/a/51212881
favorite count: 0

http://stackoverflow.com/comment/90356237
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51274872
has text: Hey Daniel - I know it's been a while but I had a question. For using (None,7) for variable frame counts, would all 50 videos need to have the same variable frame count, or could they all be different? For example, one video could have 100 frames and the next video could have 150?
type: AnswerComment

http://stackoverflow.com/q/51202867
accepted answer: http://stackoverflow.com/a/51202985
has body: I need to scrape some text from a table, using selenium. I'm a complete novice, but thanks to Stack overflow, I was able to get to get pretty far. Now I am getting an error when using text() to copy text. Here are my codes. from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from selenium import webdriver driver = webdriver.Chrome('C:/Users/User/Downloads/chromedriver') url = "https://aca.tampagov.net/citizenaccess/Default.aspx#" driver.get(url) # The website I need to check # Click "search" at the top menu driver.find_element_by_xpath('//*[@id="main_menu"]/ul/li[2]/a').click() # Click "building permits" in the menu that follows below driver.find_element_by_xpath('//[@id="main_menu"]/ul/li[2]/ul/li[1]/a').click() #change iframes driver.switch_to.frame("ACAFrame") # When changing iframes, I was recommended that I should use this, # WebDriverWait(driver, 20).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,"//*[@id='ACAFrame']"))) # but I'm now having troubles running this line so I changed it to the line like above Now you can find that there's a table below. I want to copy text using a code such as: driver.find_element_by_xpath('//tbody/tr[3]/td[4]').text() But I get, instead: Traceback (most recent call last): File "&lt;ipython-input-117-2a4c7f9321b5&gt;", line 1, in &lt;module&gt; driver.find_element_by_xpath('//tbody/tr[3]/td[4]').text() TypeError: 'str' object is not callable What am I doing wrong here?
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/89405481
has title: copying text selenium using .text()
tagged with: python
has answer: http://stackoverflow.com/a/51202985
tagged with: selenium
type: Question
type: AnsweredQuestion

http://stackoverflow.com/q/51284161
favorite count: 0
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89545657
has body: I have a table in pandas df1 id value 1 1500 2 -1000 3 0 4 50000 5 50 also I have another table in dataframe df2, that contains upper boundaries of groups, so essentially every row represents an interval from the previous boundary to the current one (the first interval is "&lt;0"): group upper 0 0 1 1000 2 NaN How should I get the relevant groups for value from df, using intervals from df2? I can't use join, merge etc., because the rules for this join should be like "if value is between previous upper and current upper" and not "if value equals something". The only way that I've found is using predefined function with df.apply() (also there is a case of categorical values in it with interval_flag==False): def values_to_group(x, interval_flag, groups_def): if interval_flag==True: for ind, gr in groups_def.sort_values(by='group').iterrows(): if x&lt;gr[1]: return gr[0] elif math.isnan(gr[1]) == True: return gr[0] else: for ind, gr in groups_def.sort_values(by='group').iterrows(): if x in gr[1]: return gr[0] Is there an easier/more optimal way to do it? The expected output should be this: id value group 1 1500 2 2 -1000 0 3 0 1 4 50000 2 5 50 1
downvote count: 0
score: 1
accepted answer: http://stackoverflow.com/a/51284406
type: Question
possible better answer: http://stackoverflow.com/a/51284755
tagged with: binning
has answer: http://stackoverflow.com/a/51284406
has answer: http://stackoverflow.com/a/51284755
has title: coding values in DataFrame using table with interval description in python
answer count: 2
tagged with: pandas
upvote count: 1

http://stackoverflow.com/comment/89589394
type: Comment
has text: thanks for the help... been trying to work my way through it, Tried following the 2nd link but kinda confusing as our code is quite different.
comment on: http://stackoverflow.com/a/51305149
type: AnswerComment
score: 0

http://stackoverflow.com/q/51228843
type: Question
has comment: http://stackoverflow.com/comment/89437512
possible better answer: http://stackoverflow.com/a/51228909
has comment: http://stackoverflow.com/comment/89437522
has comment: http://stackoverflow.com/comment/89437515
answer count: 2
has comment: http://stackoverflow.com/comment/89437503
downvote count: 0
favorite count: 0
tagged with: python
has body: When I import a module in my python file, I expect execution of the imported code to be executed when I execute the file that is importing the module. Here is the code: I have few simple lines in test_2.py file: x = 10 y = 20 c = x-y print c def func1(): return x+y This is imported in another file test_2_test.py: import test_2 x = test_2.func1() print x Here is the output when I execute test_2_test: %run "D:/Projects/Initiatives/machine learning/programs/test_2_test.py" 30 I cannot figure out why "print c" statement is not executed
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51228911
upvote count: 2
has answer: http://stackoverflow.com/a/51228909
has title: code execution upon import in Python
accepted answer: http://stackoverflow.com/a/51228911

http://stackoverflow.com/comment/89564452
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51276906
has text: also, if youre knowledgeable when it comes to Scrapy and Selenium, would you mind taking a look at my other question?? [Using and Randomizing Proxies](https://stackoverflow.com/questions/51276893/using-and-randomizing-proxies)
type: AnswerComment

http://stackoverflow.com/comment/89416925
type: Comment
type: QuestionComment
has text: Can you please tell me what the method is that is launched when the tab is pressed? Note: I'm using PyQt 4.7
score: 0
comment on: http://stackoverflow.com/q/51215635

http://stackoverflow.com/q/51252281
type: Question
has answer: http://stackoverflow.com/a/51252345
has comment: http://stackoverflow.com/comment/89483581
has title: How are my previous Python values being overwritten in this dictionary?
answer count: 3
has answer: http://stackoverflow.com/a/51252358
score: -1
favorite count: 0
accepted answer: http://stackoverflow.com/a/51252345
upvote count: 2
possible better answer: http://stackoverflow.com/a/51252358
has answer: http://stackoverflow.com/a/51252710
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/89483505
type: AnsweredQuestion
has body: I'm trying to update a dictionary, but the previous values keep getting overwritten. Here's a shortened version of the code I'm using. selected_session = "" encounters_to_add = [] session_encounters = {} selected_session = "Session 1: Paint it Black" encounters_to_add.append("Meet the Town (Narrative)") session_encounters[selected_session] = encounters_to_add encounters_to_add.append("Barn Bandits (Structured)") session_encounters[selected_session] = encounters_to_add encounters_to_add.clear() selected_session = "Session 2: Myster Man" encounters_to_add.append("A Crime Most Foul (Social)") session_encounters[selected_session] = encounters_to_add print(session_encounters) I'm trying to return {'Session 1: Paint it Black': ['Meet the Town (Narrative)', 'Barn Bandits (Structured)'], 'Session 2: Mystery Man': ['A Crime Most Foul (Social)']} Instead, I get back {'Session 1: Paint it Black': ['A Crime Most Foul (Social)'], 'Session 2: Myster Man': ['A Crime Most Foul (Social)']} I don't understand how the previous value is being overwritten. Since I'm using a new key, the values should just be added to that key in my mind.
downvote count: 3

http://stackoverflow.com/q/51308774
has comment: http://stackoverflow.com/comment/89594323
has body: I'm trying to make a multiple label classifier. It has 5 labels. I train in via ImageDataGenerators and then I want to test the system manually, which I cannot do because the system gives me weird answers, which do not look like probabilities. They can be negative or more than 1. I don't know how to correct it or where did I make a mistake. xception = Xception(include_top=False, weights='imagenet', pooling='avg') x = Dense(5, name='prediction')(xception.output) model = Model(xception.inputs, x) model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) # # Creating Image Generators # Based on ImageDataGenerator class. train_dir = 'processed_dataset/train' val_dir = 'processed_dataset/val' test_dir = 'processed_dataset/test' img_width, img_height = 300, 300 input_shape = (img_width, img_height, 3) epochs = 40 batch_size = 8 nb_train_samples = 442 nb_validation_samples = 23 nb_test_samples = 23 datagen = ImageDataGenerator( rotation_range=40, width_shift_range=0.2, height_shift_range=0.2, rescale=1./255, shear_range=0.2, zoom_range=0.2, horizontal_flip=True, fill_mode='nearest') # Generator for training train_generator = datagen.flow_from_directory( train_dir, target_size=(img_width, img_height), batch_size=batch_size, class_mode='categorical') # Generator for validation val_generator = datagen.flow_from_directory( val_dir, target_size=(img_width, img_height), batch_size=batch_size, class_mode='categorical') # Generator for testing test_generator = datagen.flow_from_directory( test_dir, target_size=(img_width, img_height), batch_size=batch_size, class_mode='categorical') # Learning the model using generators model.fit_generator( train_generator, steps_per_epoch=nb_train_samples // batch_size, epochs=epochs, validation_data=val_generator, validation_steps=nb_validation_samples // batch_size) # Evaluating the accuracy score of the system scores = model.evaluate_generator(test_generator, nb_test_samples // batch_size) print("Accuracy on the te…
tagged with: machine-learning
tagged with: tensorflow
type: Question
score: 2
has answer: http://stackoverflow.com/a/51308931
downvote count: 0
answer count: 1
tagged with: keras
favorite count: 0
has title: Predictions more than 1 or negative in Keras
tagged with: python
tagged with: generator
upvote count: 2
type: UnansweredQuestion

http://stackoverflow.com/comment/107725981
has text: This works, but I found some environment variables that also seem to work, which also is portable to other programming languages.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/51267131
score: 0

http://stackoverflow.com/a/51522155
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51306500
has body: Not really ans answer but eneded up using a list box to select the multiple items

http://stackoverflow.com/a/51292288
score: 4
upvote count: 4
answers question: http://stackoverflow.com/q/51272055
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51272055
type: Answer
has body: Answer to Question 2 I found what the problem was -- The 3D point coordinates matter! I assumed that no matter what 3D coordinate points I choose, the reconstruction would take care of it. However, I noticed something strange: when using a range of 3D points, only a subset of those points were reconstructed correctly. After further investigation, I found out that only the images that are in the field of view of the camera would be properly reconstructed. The field-of-view is the function of the intrinsic parameters (and vice-versa). For the above codes to work, try setting the parameters as follows (intrinsics are from my camera): ... const double f_x = 2746.; const double f_y = 2748.; const double c_x = 991.; const double c_y = 619.; ... const cv::Point3d point_single(10.0, -2.0, 30.0); ... Also, don't forget that in camera coordinates negative y coordinates is UP :) Answer to Question 1: There was a bug where I was trying to access the intrinsics using ... double f_x = intrinsic.at&lt;double&gt;(0, 0); double f_y = intrinsic.at&lt;double&gt;(1, 1); double c_x = intrinsic.at&lt;double&gt;(0, 3); double c_y = intrinsic.at&lt;double&gt;(1, 3); ... But intrinsic was a 3x3 matrix. Moral of the story Write unit tests!!!

http://stackoverflow.com/q/51283811
has comment: http://stackoverflow.com/comment/89545151
tagged with: if-statement
has title: Return value as bool from text file
has answer: http://stackoverflow.com/a/51284229
accepted answer: http://stackoverflow.com/a/51283927
tagged with: boolean
downvote count: 0
score: 1
favorite count: 0
has answer: http://stackoverflow.com/a/51283982
has body: Trying to write multi scripts that would access one text file to retrieve their toggle values from the said text file and then return with a value as false and change it to true and vice versa. Value always comes back as false, not sure what I'm missing but here is the text file: 1 False 3 True 5 6 7 8 9 Here is the source code: def append(): with open('values', 'r') as file: # read a list of lines into data data = file.readlines() # now change the line re_value = value data[1] = re_value+"\n" # and write everything back with open('values', 'w') as file: file.writelines(data) print("value changed to "+re_value) def read() -&gt; bool: #opens the value file to find the value of the toggle f=open("values", "r") for x, line in enumerate(f): if x == 1: toggle = line print(toggle) return toggle f.close() toggle = read() if toggle: print("Light is on turn it off") #runs command to turn off the light #runs command to change value for light value = "False" append() else: print("Light is off turn it on") #runs command to turn on the light #runs command to change value for light value = "True" append()
tagged with: python
has answer: http://stackoverflow.com/a/51284204
possible better answer: http://stackoverflow.com/a/51283982
answer count: 4
type: AnsweredQuestion
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89545008
has answer: http://stackoverflow.com/a/51283927
has comment: http://stackoverflow.com/comment/89545227
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/89544926

http://stackoverflow.com/comment/89464991
score: 3
comment on: http://stackoverflow.com/q/51243094
has text: Websockets, server-sent events or long-polling with ajax. I usually stick with websockets and [`django-channels`](http://channels.readthedocs.io/en/latest/) for that matter.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51172439
answer count: 1
has answer: http://stackoverflow.com/a/51176027
has comment: http://stackoverflow.com/comment/89327513
favorite count: 0
linked to: http://stackoverflow.com/q/41808951
accepted answer: http://stackoverflow.com/a/51176027
tagged with: python
has comment: http://stackoverflow.com/comment/89327575
downvote count: 2
has title: Python groupby ID and increment the associated column
type: Question
type: AnsweredQuestion
score: -2
has comment: http://stackoverflow.com/comment/89327662
has body: I have the following data in a pandas data frame. The data is sampled at 50khz hence the 'microsec' filed has to incremented for each ID group by 50. Data ----ID ---- microsec 0.304 ----1 ---- 1530348553000 0.276 ----1 ----15303485530000 0.276 ----1 ----15303485530000 0.276 ----2 ----15303490090000 0.276 ----2 ----15303490090000 0.304 ----2 ----15303490090000 0.276 ----3 ----15303553530000 1.359 ----3 ----15303753680000 1.443 ----3 ----15303753680000 Output Required Data ----ID ---- microsec 0.304 ----1 ---- 1530348553000 0.276 ----1 ----15303485530050 0.276 ----1 ----15303485530100 0.276 ----2 ----15303490090000 0.276 ----2 ----15303490090050 0.304 ----2 ----15303490090100 0.276 ----3 ----15303553530000 1.359 ----3 ----15303753680050 1.443 ----3 ----15303753680100 CODE import numpy as np from itertools import chain lens = list(map(len, df['Data'].str.split('|'))) df['microsec'] = pd.DatetimeIndex ( df['DateTime'] ).astype ( np.int64 )// 10 ** 9 df['Data'] = df['Data'].str.replace(',','.') res = pd.DataFrame({'ID': np.repeat(df['ID'], lens), 'microsec': np.repeat(df['microsec']*10000, lens), 'Data': list(chain.from_iterable(df['Data'].str.split('|'))) }) res'Data' = res'Data'.astype(float) res.to_csv('samplefile.txt', index=False) What I tried df_groups = res.groupby('MeasurementID') for MeasurementID,microsec in df_groups: microsec = microsec*50 print(microsec) But I did not achieve my desired output. Please let me know where I am doing wrong.
tagged with: pandas
has comment: http://stackoverflow.com/comment/89328356
upvote count: 0

http://stackoverflow.com/q/51317311
tagged with: linear-regression
score: 1
type: Question
has body: I wonder if there is a way to add a range to the predictions prior to fitting the model. The variable in question in my train data is technically a percentage score, but when I predict my test set, I get negative values or values >100. For now, I am manually normalizing the predictions list. I also used to cut off negatives and >100 and assign then a 0 and 100. However, it only makes sense if the fit function could be made aware of this constraint, right? Here is a sample row of the data: test_df = pd.DataFrame([[0, 40, 28, 30, 40, 22, 60, 40, 21, 0, 85, 29, 180, 85, 36, 741, 25.0]], columns=['theta_1', 'phi_1', 'value_1', 'theta_2', 'phi_2', 'value_2', 'theta_3', 'phi_3', 'value_3', 'theta_4', 'phi_4', 'value_4', 'theta_5', 'phi_5', 'value_5', 'sum_readings', 'estimated_volume']) I have been reading and a lot of people consider this not a linear regression problem but their logic is not sound. Also, some say that one can apply a log scale but that only works in the case of comparison against a threshold, i.e., manual classification, i.e., using linear regression for a logistic regression problem! In my case, I need the percentages as they are the required output. Your feedbacks/thought are much appreciated.
upvote count: 1
has comment: http://stackoverflow.com/comment/89627558
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/51320729
has comment: http://stackoverflow.com/comment/89611734
tagged with: scikit-learn
favorite count: 0
has title: How to add a range to sklearn's linear regression predictions
tagged with: python
has comment: http://stackoverflow.com/comment/89613657
linked to: http://stackoverflow.com/q/20109391
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89610965
tagged with: machine-learning

http://stackoverflow.com/comment/89529261
has text: Is it failing on the `edit_role` line? [It looks like you can edit roles that are *less than* (and presumably not equal to) your own level of permissions.](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_roles). Can your bot manage roles with no associated permissions?
type: Comment
score: 0
comment on: http://stackoverflow.com/a/51263991
type: AnswerComment

http://stackoverflow.com/q/51193759
tagged with: pip
type: Question
score: 1
tagged with: ssl
upvote count: 1
has comment: http://stackoverflow.com/comment/89372744
favorite count: 0
has comment: http://stackoverflow.com/comment/89372494
tagged with: python
has body: On 7/4 I started to get this error from pip on OSX Could not fetch URL https://pypi.org/simple/pytest/: There was a problem confirming the ssl certificate: HTTPSConnectionPool(host='pypi.org', port=443): Max retries exceeded with url: /simple/pytest/ (Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain (_ssl.c:1045)'))) - skipping I get this with any and every module I try to install with pip. This happens on python 3.6 and 3.7, in virtual and non virtual environments. I have looked at previous stackoverflow issues relating to certs and pip, and tried the various suggestions to no avail. Openssl reports version LibreSSL 2.2.7 OSX 10.13.5. And pip is 10.0.1
answer count: 0
downvote count: 0
has title: PIP certificate issues OSX
type: UnansweredQuestion

http://stackoverflow.com/comment/89446584
has text: Your code reads: `class Privilegis: def __init__(self, privilegis_type):`. So yeah, the `__init__` method needs one more argument.
comment on: http://stackoverflow.com/q/51233767
score: 0
type: Comment
type: QuestionComment

list
tags question: http://stackoverflow.com/q/51225456
type: Tag
tags question: http://stackoverflow.com/q/51226468
tags question: http://stackoverflow.com/q/51208208
tags question: http://stackoverflow.com/q/51180949
tags question: http://stackoverflow.com/q/51213451
tags question: http://stackoverflow.com/q/51217902
tags question: http://stackoverflow.com/q/51178497
tags question: http://stackoverflow.com/q/51210929
tags question: http://stackoverflow.com/q/51314292
tags question: http://stackoverflow.com/q/51233730
tags question: http://stackoverflow.com/q/51178613
tags question: http://stackoverflow.com/q/51314424
tags question: http://stackoverflow.com/q/51204963
tags question: http://stackoverflow.com/q/51293795
tags question: http://stackoverflow.com/q/51209547
tags question: http://stackoverflow.com/q/51186586
tags question: http://stackoverflow.com/q/51293905
tags question: http://stackoverflow.com/q/51249479
tags question: http://stackoverflow.com/q/51173443
tags question: http://stackoverflow.com/q/51179203
tags question: http://stackoverflow.com/q/51292725
tags question: http://stackoverflow.com/q/51180460
tags question: http://stackoverflow.com/q/51255395
tags question: http://stackoverflow.com/q/51251574
tags question: http://stackoverflow.com/q/51308999
tags question: http://stackoverflow.com/q/51252245
tags question: http://stackoverflow.com/q/51186125
tags question: http://stackoverflow.com/q/51180293
tags question: http://stackoverflow.com/q/51213110
tags question: http://stackoverflow.com/q/51302157
tags question: http://stackoverflow.com/q/51206172
tags question: http://stackoverflow.com/q/51222981
tags question: http://stackoverflow.com/q/51283416
tags question: http://stackoverflow.com/q/51204017
tags question: http://stackoverflow.com/q/51227185
tags question: http://stackoverflow.com/q/51245163
tags question: http://stackoverflow.com/q/51235041
tags question: http://stackoverflow.com/q/51261969
tags question: http://stackoverflow.com/q/51299087
tags question: http://stackoverflow.com/q/51297805
tags question: http://stackoverflow.com/q/51201390
tags question: http://stackoverflow.com/q/51217432
tags question: http://stackoverflow.com/q/51232485
tags question: http://stackoverflow.com/q/51240548
tags question: http://stackoverflow.com/q/51295832
tags question: http://stackoverflow.com/q/51300877
tags question: http://stackoverflow.com/q/51310619
tags question: http://stackoverflow.com/q/51304581
tags question: http://stackoverflow.com/q/51193743
tags question: http://stackoverflow.com/q/51206553
tags question: http://stackoverflow.com/q/51222460
tags question: http://stackoverflow.com/q/51188003
tags question: http://stackoverflow.com/q/51276796
tags question: http://stackoverflow.com/q/51193920
tags question: http://stackoverflow.com/q/51248718
tag name: list
tags question: http://stackoverflow.com/q/51185748
tags question: http://stackoverflow.com/q/51247307
tags question: http://stackoverflow.com/q/51316310
tags question: http://stackoverflow.com/q/51219859
tags question: http://stackoverflow.com/q/51211463
tags question: http://stackoverflow.com/q/51200805
tags question: http://stackoverflow.com/q/51228828
tags question: http://stackoverflow.com/q/51321774
tags question: http://stackoverflow.com/q/51241844
tags question: http://stackoverflow.com/q/51198845
tags question: http://stackoverflow.com/q/51188221
tags question: http://stackoverflow.com/q/51218054
tags question: http://stackoverflow.com/q/51250881
tags question: http://stackoverflow.com/q/51289736
tags question: http://stackoverflow.com/q/51220389
tags question: http://stackoverflow.com/q/51227101
tags question: http://stackoverflow.com/q/51298879
tags question: http://stackoverflow.com/q/51308824
tags question: http://stackoverflow.com/q/51220018
tags question: http://stackoverflow.com/q/51235622
tags question: http://stackoverflow.com/q/51228644
tags question: http://stackoverflow.com/q/51310139
tags question: http://stackoverflow.com/q/51204336

http://stackoverflow.com/a/51177578
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/51177493
has body: You don't even need to use the inspect module. You can easily achieve this by checking the __bases__ attribute of a class: class Foo(object): pass class Bar(Foo): pass print('Bar is child of Foo?', Foo in Bar.__bases__) __bases__ however, only shows the direct parent of the given class, and not the whole ancestry. You can actually implement this yourself by iterating over the whole chain of base clases and merging them together in one single tuple: def get_all_bases(cls, bases=None): bases = bases or [] bases.append(cls) for c in cls.__bases__: get_all_bases(c, bases) return tuple(bases) Then you'd just: class Foo(object): pass class Bar(Foo): pass class FooBar(Bar): pass print('FooBar is child of Foo?', Foo in get_all_bases(FooBar))
upvote count: 2
has comment: http://stackoverflow.com/comment/89338099
type: Answer

http://stackoverflow.com/q/51233335
downvote count: 0
has body: allowed_domains = ["textfiles.com/100"] start_urls = ['http://textfiles.com/100/'] def parse(self,response): link=response.css('a::attr(href)').extract() for i in link: temp="http://www.textfiles.com/100/"+i data=scrapy.Request(temp,callback=self.parsetwo) The 'parsetwo' function does not get called. def parsetwo(self,response): print(response.text)
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51233660
type: UnansweredQuestion
upvote count: 1
tagged with: python
has title: Scrapy doesn't callback a different function other than default 'parse'
score: 1
tagged with: scrapy
type: Question
answer count: 1

web-scraping
tags question: http://stackoverflow.com/q/51276426
tags question: http://stackoverflow.com/q/51178693
tags question: http://stackoverflow.com/q/51261926
tags question: http://stackoverflow.com/q/51271691
tags question: http://stackoverflow.com/q/51286702
tags question: http://stackoverflow.com/q/51264436
tags question: http://stackoverflow.com/q/51199996
tags question: http://stackoverflow.com/q/51235730
tags question: http://stackoverflow.com/q/51277605
tags question: http://stackoverflow.com/q/51238064
tags question: http://stackoverflow.com/q/51176193
tags question: http://stackoverflow.com/q/51217618
tags question: http://stackoverflow.com/q/51221607
tags question: http://stackoverflow.com/q/51206639
tags question: http://stackoverflow.com/q/51286404
tags question: http://stackoverflow.com/q/51272768
tags question: http://stackoverflow.com/q/51231660
tags question: http://stackoverflow.com/q/51181721
tags question: http://stackoverflow.com/q/51223025
tags question: http://stackoverflow.com/q/51258013
tags question: http://stackoverflow.com/q/51206143
tags question: http://stackoverflow.com/q/51223809
tags question: http://stackoverflow.com/q/51182812
tags question: http://stackoverflow.com/q/51280078
tags question: http://stackoverflow.com/q/51180443
tags question: http://stackoverflow.com/q/51313195
tags question: http://stackoverflow.com/q/51236556
tags question: http://stackoverflow.com/q/51238622
tags question: http://stackoverflow.com/q/51188630
tags question: http://stackoverflow.com/q/51318839
tags question: http://stackoverflow.com/q/51202820
tags question: http://stackoverflow.com/q/51223953
tags question: http://stackoverflow.com/q/51180439
tags question: http://stackoverflow.com/q/51244373
tags question: http://stackoverflow.com/q/51249722
tags question: http://stackoverflow.com/q/51188365
tags question: http://stackoverflow.com/q/51199698
tags question: http://stackoverflow.com/q/51223048
tags question: http://stackoverflow.com/q/51233325
tags question: http://stackoverflow.com/q/51276197
tags question: http://stackoverflow.com/q/51236461
tags question: http://stackoverflow.com/q/51215411
tags question: http://stackoverflow.com/q/51269596
tags question: http://stackoverflow.com/q/51232748
tags question: http://stackoverflow.com/q/51188598
tags question: http://stackoverflow.com/q/51185110
tags question: http://stackoverflow.com/q/51319079
tags question: http://stackoverflow.com/q/51256032
tags question: http://stackoverflow.com/q/51263516
tags question: http://stackoverflow.com/q/51309506
tags question: http://stackoverflow.com/q/51322250
tags question: http://stackoverflow.com/q/51284741
tag name: web-scraping
tags question: http://stackoverflow.com/q/51196874
tags question: http://stackoverflow.com/q/51200951
tags question: http://stackoverflow.com/q/51172489
tags question: http://stackoverflow.com/q/51299572
tags question: http://stackoverflow.com/q/51228824
tags question: http://stackoverflow.com/q/51225357
tags question: http://stackoverflow.com/q/51171256
tags question: http://stackoverflow.com/q/51235304
tags question: http://stackoverflow.com/q/51287953
type: Tag
tags question: http://stackoverflow.com/q/51231743
tags question: http://stackoverflow.com/q/51249975
tags question: http://stackoverflow.com/q/51230307
tags question: http://stackoverflow.com/q/51214853
tags question: http://stackoverflow.com/q/51182418
tags question: http://stackoverflow.com/q/51192294
tags question: http://stackoverflow.com/q/51243849
tags question: http://stackoverflow.com/q/51293574
tags question: http://stackoverflow.com/q/51253538
tags question: http://stackoverflow.com/q/51179320
tags question: http://stackoverflow.com/q/51230824
tags question: http://stackoverflow.com/q/51252236
tags question: http://stackoverflow.com/q/51286037
tags question: http://stackoverflow.com/q/51276635
tags question: http://stackoverflow.com/q/51276179
tags question: http://stackoverflow.com/q/51320294
tags question: http://stackoverflow.com/q/51226138

http://stackoverflow.com/comment/89427728
type: QuestionComment
comment on: http://stackoverflow.com/q/51223640
score: 2
type: Comment
has text: You need to change your algorithm. Nothing you do in Python or C or whatever language will make this tractable.

http://stackoverflow.com/q/51193747
tagged with: numpy
has comment: http://stackoverflow.com/comment/89369296
score: 0
answer count: 2
tagged with: arrays
has title: conditional row and column selection in pandas
possible better answer: http://stackoverflow.com/a/51194500
has comment: http://stackoverflow.com/comment/89369945
tagged with: pandas
has body: I have a dataframe like this: (c_in_node) 0 1791 0.1 1792 0.3 1793 0.2 1794 0.1 ... 3611 0.1 And an array like this: (q_flowline) [0.1 0.2 -0.1 ... -0.3] and two more arrays like this: [1907 2343 2344 ... 3604 1845 2179] (fl_from_node) [2343 2344 2050 ... 1918 3600 3611] (fl_to_node) I want to calculate my mass in my flow but it needs to select the from_node when the q_flowline is positive and it needs to select the to_node when q_flowline is negative. I tried: m_in_flow = pd.DataFrame(c_in_node[fl_from_node if q_flowline &gt;= 0 else fl_to_node]*q_flowline) But this doesn't work. I need a DataFrame with the selection: 0 0.01 0.03 .... 0.01 All these numbers should be positive.
tagged with: python
accepted answer: http://stackoverflow.com/a/51194315
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89369827
has answer: http://stackoverflow.com/a/51194500
has answer: http://stackoverflow.com/a/51194315
type: Question
tagged with: dataframe
has comment: http://stackoverflow.com/comment/89369785

http://stackoverflow.com/q/51272748
has answer: http://stackoverflow.com/a/51272788
has answer: http://stackoverflow.com/a/51272822
has answer: http://stackoverflow.com/a/51273062
has comment: http://stackoverflow.com/comment/89523648
has comment: http://stackoverflow.com/comment/89523614
upvote count: 0
has comment: http://stackoverflow.com/comment/89523603
has comment: http://stackoverflow.com/comment/89523569
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51272788
favorite count: 0
score: -1
has comment: http://stackoverflow.com/comment/89523623
has body: I wrote a menu function that loops until the user presses 3 to exit. But when the user asks for the other options by pressing 1 or 2 I want it to print something. Here is my code: def Menu(): return("\n" + "Menu:\n-------------" + "\n1 - Does This" + "\n2 - Does That" + "\n3 - Quit" + "\n") if option == 1: return "\nThis" if option == 2: return "\nThat" option = None while True: print(Menu()) option = int(input("Please choose an option: ")) if option == 3: print("\nBye!") break if option &lt; 1 or option &gt; 3: print("\nIncorrect input!") Instead of getting "This" when pressing 1 or "That" when pressing 2, it just loops the menu again until I press 3 to exit. This is my current output: Menu: ------------- 1 - Does This 2 - Does That 3 - Quit Please choose an option: 1 Menu: ------------- 1 - Does This 2 - Does That 3 - Quit Please choose an option: 2 Menu: ------------- 1 - Does This 2 - Does That 3 - Quit Please choose an option: 3 Bye! My desired outcome is just for it to print "This" or "That" then loop the menu again until I exit.
has comment: http://stackoverflow.com/comment/89523590
type: Question
tagged with: python
has title: Function not returning any values - Python
answer count: 3
possible better answer: http://stackoverflow.com/a/51272822
downvote count: 1

http://stackoverflow.com/q/51242646
has answer: http://stackoverflow.com/a/51256456
score: 0
has body: I would like to refresh a python Tkinter window every 1 seconds : animation=TFS(test) #animation is a list, each item in the list is a table with drawing input information. for item in animation: Display(item) #display function is creating a Tkinter window with a mainloop time.sleep(1) The only solution about closing a mainloop for Tkinter that i found on the internet, is by using .quit() or .destroy() in a button. But I don't want the user to close the window manually, the window should be closed automatically every x second in order to be able to display a new window with updated information. Note : the display is made of about 2 hundreds rectangles and labels.
has title: Closing Python Tkinter window mainloop without a button
tagged with: tkinter
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51243747
tagged with: python
has comment: http://stackoverflow.com/comment/89464753
type: Question
answer count: 2

http://stackoverflow.com/q/51278257
tagged with: heroku
tagged with: amazon-s3
type: Question
has body: I am a newbie to DevOps and deployment. I have created a CMS in Django which has an image upload option. The application is already deployed on Heroku and it uses Postgres database. I then got to know that Heroku is an ephemeral filesystem and all my images uploaded will be lost. So I need to connect it with S3 for image storage. Can anyone give the exact minimal code specifics? I have searched and tried many tutorials but none of it seem to work completely. This might be silly question but please help. I'm a newbie.
has title: Amazon S3 connection with Django Heroku for image upload
has answer: http://stackoverflow.com/a/51278695
score: 0
answer count: 3
tagged with: python
has answer: http://stackoverflow.com/a/62279131
favorite count: 0
tagged with: image-uploading
has answer: http://stackoverflow.com/a/51279937
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/15085864
upvote count: 1
tagged with: django
downvote count: 1

http://stackoverflow.com/comment/89411015
type: AnswerComment
has text: @zero298 all of the above. The documentation was complex, but the solution was trivial
type: Comment
comment on: http://stackoverflow.com/a/51213254
score: 0

http://stackoverflow.com/comment/89473404
has text: Does this help: https://stackoverflow.com/questions/42190783/what-does-three-dots-in-python-mean-when-indexing-what-looks-like-a-number?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51241068
score: 0

http://stackoverflow.com/q/51216020
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51216139
type: Question
has comment: http://stackoverflow.com/comment/89413812
accepted answer: http://stackoverflow.com/a/51216139
score: 0
has title: sklearn KNeighborsClassifier "ValueError: Found array with dim 4. Estimator expected <= 2."
answer count: 1
tagged with: scikit-learn
linked to: http://stackoverflow.com/q/34972142
tagged with: knn
has body: I am trying to train a simple model with sklearn kneighborsclassifier on wine quality data. This is my code: from sklearn.neighbors import KNeighborsClassifier import pandas as pd import numpy as np dataframe = pd.read_csv("winequality-white.csv") dataframe = dataframe.drop(["fixed acidity", "pH", "sulphates"], axis=1) test = dataframe[110:128] train = dataframe[15:40] Y = train["quality"] X = train.drop(["quality"], axis=1) #print(X) #print(Y) knn = KNeighborsClassifier() knn.fit(X, Y) testvals = np.array(test.loc[110, :]) testvals = testvals.reshape(1, -1) print(knn.predict(testvals)) I get the error "ValueError: Found array with dim 4. Estimator expected &lt;= 2." I'm fairly certain it has something to do with the shape of my array and I have tried to reshape it, but had no luck. What should I do?
has comment: http://stackoverflow.com/comment/89413355

http://stackoverflow.com/comment/89344290
comment on: http://stackoverflow.com/q/51180906
score: 0
type: Comment
type: QuestionComment
has text: Show us a sample list in python.

http://stackoverflow.com/comment/89488497
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51254726
has text: Python uses a low level keyboard hook? This makes me sad :(
score: 0

http://stackoverflow.com/q/51181275
has answer: http://stackoverflow.com/a/51184773
type: Question
has body: Is there anyone who could help figure out what the double greater-than symbol (i.e. Drug &gt;&gt; float in line 10 and Drug &gt;&gt; int in line 13) means in the following python scripts? 1 from owlready2 import * 2 3 onto = get_ontology("http://test.org/onto.owl") 4 5 with onto: 6 class Drug(Thing): 7 def get_per_tablet_cost(self): 8 return self.cost / self.number_of_tablets 9 10 class has_for_cost(Drug &gt;&gt; float, FunctionalProperty): 11 python_name = "cost" 12 13 class has_for_number_of_tablets(Drug &gt;&gt; int, FunctionalProperty): 14 python_name = "number_of_tablets" 15 16 my_drug = Drug(cost = 10.0, number_of_tablets = 5) 17 print(my_drug.get_per_tablet_cost()) --- Below is the printing outcome. --- 2.0 The code is copied from here and runs in python 3. The &gt;&gt; symbol here is not bitwise operator. Python's bitwise operation, say x &gt;&gt; y, requires y to be an integer. It is clear that the code here (Drug &gt;&gt; float) is not shifting Drug right by float bits. Although similar questions were asked before (see here and here), their answers mostly pointed to the so-called "print chevron" in python 2, where the &gt;&gt; redirects the to-be-printed messages to the file-like object specified right after the &gt;&gt;. They do not apply to my question because here is not a case of print statement. To trace the &gt;&gt; in the code above, I revised the script in line 10 as class has_for_cost(Drug &gt;&gt; list, FunctionalProperty) (namely replace &gt;&gt; float with &gt;&gt; list) and ran the code again. It raised an AttributeError as follows: AttributeError Traceback (most recent call last) &lt;ipython-input-1-1be374b27b04&gt; in &lt;module&gt;() 8 return self.cost / self.number_of_tablets 9 ---&gt; 10 class has_for_cost(Drug &gt;&gt; list, FunctionalProperty): 11 python_name = "cost" 12 ~/anaconda3/lib/python3.6/site-packages/owlready2/prop.py in __init__(Prop, name, bases, obj_dict) 254 class ReasoningPropertyClass(PropertyClass): 255 def __init__(Pro…
answer count: 2
linked to: http://stackoverflow.com/q/34385674
possible better answer: http://stackoverflow.com/a/51184773
has comment: http://stackoverflow.com/comment/89345099
has answer: http://stackoverflow.com/a/51181373
has comment: http://stackoverflow.com/comment/89351602
downvote count: 0
score: 1
tagged with: operators
favorite count: 0
has title: What does >> do if it is neither bitwise operation nor print chevron?
tagged with: arguments
upvote count: 1
tagged with: python
linked to: http://stackoverflow.com/q/22832615
accepted answer: http://stackoverflow.com/a/51181373
type: AnsweredQuestion
tagged with: syntax

http://stackoverflow.com/q/51275590
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
has title: What is the real result of an sklearn analysis?
tagged with: machine-learning
has answer: http://stackoverflow.com/a/51277124
has comment: http://stackoverflow.com/comment/89529250
type: Question
answer count: 1
tagged with: scikit-learn
upvote count: 1
has body: I am trying to get the result of a sklearn analysis, not the accuracy. I mean, I want to see the what my model is resulting. clf = RandomForestClassifier() # train the classifier using the training data clf.fit(features_train, labels_train) acc_test = clf.score(features_test, labels_test) acc_train = clf.score(features_train, labels_train) print ("Train Accuracy:", acc_train) All i have here is the accuracy, I tried so far(i found this solution on stack, perhaps I've missed something), but it is not working: labels = clf.fit(features_train, labels_train) print (labels.dtype) I have two possible outputs (0 or 1), and then I want to see by my self the proper results, a csv file. How could I do that?
downvote count: 7
tagged with: python
score: -6

http://stackoverflow.com/q/51310599
has comment: http://stackoverflow.com/comment/89598363
favorite count: 0
has comment: http://stackoverflow.com/comment/89598044
tagged with: python
has body: My Dataframe: pd.DataFrame({'company':['Chipotle','Branchburg Chipotle','Chipotle NJ','Chipotle 8853','The Home Depot','Home Depot','28211 Home Depot','Wendys','BJs','Buffalo wings'], 'address':['123 Main Street Branchburg NJ 08853' ,'123 Main Street Branchburg NJ 08853' ,'123 Main Street Branchburg NJ 08853' ,'123 Main Street Branchburg NJ 08853' ,'1220 N Wendover Rd Charlotte NC 28211' ,'1220 N Wendover Rd Charlotte NC 28211' ,'1220 N Wendover Rd Charlotte NC 28211' ,'2805 Whitson St Selma CA 93662' ,'2805 Whitson St Selma CA 93662' ,'2805 Whitson St Selma CA 93662']}) company address 0 Chipotle 123 Main Street Branchburg NJ 08853 1 Branchburg Chipotle 123 Main Street Branchburg NJ 08853 2 Chipotle NJ 123 Main Street Branchburg NJ 08853 3 Chipotle 8853 123 Main Street Branchburg NJ 08853 4 The Home Depot 1220 N Wendover Rd Charlotte NC 28211 5 Home Depot 1220 N Wendover Rd Charlotte NC 28211 6 28211 Home Depot 1220 N Wendover Rd Charlotte NC 28211 7 Wendy's 2805 Whitson St Selma CA 93662 8 BJ's 2805 Whitson St Selma CA 93662 9 Buffalo wings 2805 Whitson St Selma CA 93662 I have to groupby Address and find the common word in the company column and write that to a new column 'count'. so for first address the common word is chipotle so count is 1 and for second address common word is home depot so count 2 and for third address no common words so count 0 Expected Ouput company address count 0 Chipotle 123 Main Street Branchburg NJ 08853 1 1 The Home Depot 1220 N Wendover Rd Charlotte NC 28211 2 2 Wendy's 2805 Whitson St Selma CA 93662 0 I can think of iterating through the dataframe and using set intersection but that's too slow process. Is there any pandas way to achieve this?
upvote count: 2
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89598872
has title: Pandas Group by and find count of common strings
has answer: http://stackoverflow.com/a/51310999
has comment: http://stackoverflow.com/comment/89598458
accepted answer: http://stackoverflow.com/a/51310999
tagged with: pandas-groupby
has comment: http://stackoverflow.com/comment/89598588
tagged with: pandas
score: 2
answer count: 1
downvote count: 0

http://stackoverflow.com/comment/89455097
comment on: http://stackoverflow.com/q/51237956
score: 0
type: QuestionComment
has text: @Peter Gibson is there not a way to input the password in plain text within the python script so that it autofills the password prompt without using key authentication?
type: Comment

http://stackoverflow.com/comment/89562168
type: Comment
comment on: http://stackoverflow.com/a/51273274
type: AnswerComment
has text: i used this method, its not printing
score: 0

http://stackoverflow.com/a/51313628
type: Answer
answers question: http://stackoverflow.com/q/51312237
has body: If you are going to add a path for your system variables do not include the ending of the file such as ".exe" in this case you only want the path leading to the ".exe" such as "C:\Users[username]\Anaconda3\pkgs\python-3.6.5-h0c2934d_0\" Then restart your computer and try again
score: 0

http://stackoverflow.com/comment/89433004
score: 0
comment on: http://stackoverflow.com/q/51226450
type: Comment
type: QuestionComment
has text: Could you post a short snippet of your code and data? You question seems unclear to me.

http://stackoverflow.com/q/51311988
has comment: http://stackoverflow.com/comment/89627608
has comment: http://stackoverflow.com/comment/89630417
answer count: 1
downvote count: 0
has body: I have a project that defines testing support modules, including py.test plugins in a package subdirectory like this: bokeh/_testing ├── __init__.py ├── plugins │ ├── __init__.py │ ├── bokeh_server.py │ ├── examples_report.jinja │ ├── examples_report.py │ ├── file_server.py │ ├── implicit_mark.py │ ├── integration_tests.py │ ├── jupyter_notebook.py │ ├── log_file.py │ └── pandas.py └── util ├── __init__.py ├── api.py ├── examples.py ├── filesystem.py ├── git.py └── travis.py Several of the plugins need to define new options with parser.addoption. I would like these calls to be made inside the respective plugin modules. However, if I do that, and include those plugins in a test file with, e.g. # test_examples.py pytest_plugins = ( "bokeh.testing.plugins.bokeh_server", "bokeh.testing.plugins.examples_report", ) # pytest.mark.examples test code here Then pytest complains that any custom command line options are undefined: (base) ❯ py.test -s -v -m examples --diff-ref FETCH_HEAD --report-path=examples.html usage: py.test [options] [file_or_dir] [file_or_dir] [...] py.test: error: unrecognized arguments: --diff-ref --report-path=examples.html inifile: /Users/bryanv/work/bokeh/setup.cfg rootdir: /Users/bryanv/work/bokeh The only way I have found around this, is to collect ALL custom options in a single pytest_addoption in the top-level conftest.py: # conftest.py pytest_plugins = ( "bokeh.testing.plugins.implicit_mark", "bokeh.testing.plugins.pandas", ) # Unfortunately these seem to all need to be centrally defined at the top level def pytest_addoption(parser): parser.addoption( "--upload", dest="upload", action="store_true", default=False, help="..." ) # ... ALL other addoptions calls for all plugins here ... As I said, this works, but is very inflexible in terms of code organization. It would be preferable to have a way for the options for the examples.py plugin to in the examples.py module, with the code it relates to. Another possibility would presumably be to bring in…
favorite count: 0
has title: Way to add pytest options outside top level conftest?
has comment: http://stackoverflow.com/comment/89630857
has comment: http://stackoverflow.com/comment/89619414
tagged with: python
has answer: http://stackoverflow.com/a/51733980
score: 2
type: AnsweredQuestion
upvote count: 2
accepted answer: http://stackoverflow.com/a/51733980
has comment: http://stackoverflow.com/comment/89619795
type: Question
tagged with: testing
tagged with: pytest

http://stackoverflow.com/comment/96776106
comment on: http://stackoverflow.com/a/54946522
type: AnswerComment
score: 0
has text: It's been a while since I studied this in school and since the question remained unanswered I settled with this alleged limitation of sklearn for the sake of completing the assignment, but a far as I remember, LSA will try to group the terms in higher level terms that will describe you documents in a way that it will reduce the feature space, similarly to PCA, but I don't remember hearing about a limit for the number of high level concepts beeing set on the number of documents/data points. I'd love to hear from someone who really understand LSA
type: Comment

http://stackoverflow.com/q/51197496
tagged with: jupyter-notebook
has comment: http://stackoverflow.com/comment/89377017
answer count: 0
type: UnansweredQuestion
score: 0
tagged with: coremltools
type: Question
tagged with: coreml
has body: I've trained a model using scikit-learn's DecisionTreeClassifier on a dataset with >3,000,000 rows and 15 features (binary encoding of categories.) It runs nicely and does what I want it to do. When I try to convert it to a CoreML model, it doesn't work. I get "The kernel appears to have died. It will restart automatically." I dropped the size of my data down, and for really small batches, it works fine. It seems to break around 500 rows. I'm new to using CoreML, and this may be a misunderstanding of how it works, but I'm not sure. I feel like given its purpose, CoreML should be able to handle bigger models with a large number of class labels (I'm looking at around 40,000.) Any idea on how to fix this issue or work around it? A simplified idea of what I'm doing: import pandas as pd import numpy as np import sklearn import coremltools import random import string from sklearn.tree import DecisionTreeClassifier X = np.random.choice([0, 1], size=(15*1000,), p=[1./3, 2./3]) X = np.split(X,1000) y = [] for i in range(0,1000): x = ''.join(random.choice(string.lowercase) for x in range(5)) y.append(x) clf = DecisionTreeClassifier() clf.fit(X,y) d = {'arr': X, 'str': y} df = pd.DataFrame(data=d) coreml_model = coremltools.converters.sklearn.convert(clf, "arr", "str") ## kernel dies here for larger data coreml_model.save('mymodel.mlmodel') Update: It's a memory issue (probably.) Once I get past about 2 mb, I get malloc: *** error for object 0x7fb096a0f738: incorrect checksum for freed object - object was probably modified after being freed. *** set a breakpoint in malloc_error_break to debug Debugging just gives Segmentation fault: 11
tagged with: scikit-learn
has title: Jupyter kernel dies using coremltools for large decision trees
tagged with: python
has comment: http://stackoverflow.com/comment/89376817

http://stackoverflow.com/a/51305099
upvote count: 2
score: 2
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51302638
answers question: http://stackoverflow.com/q/51302638
type: Answer
has body: Here is an example with nested call to quad performing the integration giving 1/8th of the sphere volume: import numpy as np from scipy.integrate import quad def fz(x, y): return quad( lambda z:1, 0, np.sqrt(x**2+y**2) )[0] def fy(x): return quad( fz, 0, np.sqrt(1-x**2), args=(x, ) )[0] def fx(): return quad( fy, 0, 1 )[0] fx() &gt;&gt;&gt; 0.5235987755981053 4/3*np.pi/8 &gt;&gt;&gt; 0.5235987755982988

http://stackoverflow.com/q/51295880
answer count: 0
has title: QTableView unexpectedly shifts left after inserting row to data using pandas
type: UnansweredQuestion
upvote count: 1
tagged with: qtableview
downvote count: 1
type: Question
tagged with: pyqt
favorite count: 0
score: 0
tagged with: pandas
has body: ----How The Problem Looks Like---- after I clicked on the Record button, it becomes this As you can see, the table just shifted to the left, hiding the vertical headers. ----Related Codes---- My tableivew is called tableViewTransaction, it uses a model to link to data in pandas' dataframe format. Here is how I connected them together inside the __init__ function of a QMainWindow. self.data = pd.read_csv('transactions.txt', sep='\t', header=None) self.data.columns = ["Name", "Price", "Action"] self.model = PandasModel(self.data) self.tableViewTransaction.setModel(self.model) Here is my Model for the TableView class PandasModel(QtCore.QAbstractTableModel): def __init__(self, df = pd.DataFrame(), parent=None): QtCore.QAbstractTableModel.__init__(self, parent=parent) self._df = df def headerData(self, section, orientation, role=QtCore.Qt.DisplayRole): if role != QtCore.Qt.DisplayRole: return QtCore.QVariant() if orientation == QtCore.Qt.Horizontal: try: return self._df.columns.tolist()[section] except (IndexError, ): return QtCore.QVariant() elif orientation == QtCore.Qt.Vertical: try: # return self.df.index.tolist() return self._df.index.tolist()[section] except (IndexError, ): return QtCore.QVariant() def data(self, index, role=QtCore.Qt.DisplayRole): if role != QtCore.Qt.DisplayRole: return QtCore.QVariant() if not index.isValid(): return QtCore.QVariant() return QtCore.QVariant(str(self._df.ix[index.row(), index.column()])) def setData(self, index, value, role): row = self._df.index[index.row()] col = self._df.columns[index.column()] if hasattr(value, 'toPyObject'): # PyQt4 gets a QVariant value = value.toPyObject() else: # PySide gets an unicode dtype = self._df[col].dtype if dtype != object: value = None if value == '' else dtype.type(value) self._df.set_value(row, col, value) return True def rowCount(self, parent=QtCore.QModelIndex()): return len(self._df.index) def columnCount(self, parent=QtCore.QModelIndex()): return len(self._df.columns) def sort(self, column…
has comment: http://stackoverflow.com/comment/89569425
tagged with: python
has comment: http://stackoverflow.com/comment/89569866

http://stackoverflow.com/comment/89598924
comment on: http://stackoverflow.com/a/51294937
type: AnswerComment
score: 0
has text: @ZhangXianhan Yes, right. That's only the last dimension. If you read Dense layer documentation you will see that the input shape of Dense layer is `(batch_size, ..., input_dim)` and the output shape is `(batch_size, ..., units)` where `units` refers to the number of units you specify for the layer.
type: Comment

http://stackoverflow.com/q/51278897
downvote count: 0
has answer: http://stackoverflow.com/a/51278957
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89535312
has answer: http://stackoverflow.com/a/51279040
has comment: http://stackoverflow.com/comment/89535331
score: 1
tagged with: dataframe
has title: ffill not filling data in pandas dataframe
type: Question
tagged with: pandas
upvote count: 1
tagged with: nan
favorite count: 0
has comment: http://stackoverflow.com/comment/89535247
answer count: 3
tagged with: python
has body: I have a dataframe like this : A B C E D --------------- 0 a r g g 1 x 2 x f f r 3 t 3 y I am trying for forward filling using ffill. It is not working cols = df.columns[:4].tolist() df[cols] = df[cols].ffill() I also tried : df[cols] = df[cols].fillna(method='ffill') But it is not getting filled. Is it the empty columns in data causing this issue? Data is mocked. Exact data is different (contains strings,numbers and empty columns) desired o/p: A B C E D --------------- 0 a r g g 1 a r g x 2 x f f r 3 x f f t 3 x f f y
has answer: http://stackoverflow.com/a/51279007

http://stackoverflow.com/comment/89498984
has text: @Aran-Fey, The output will be `1|A|2017-12-19`.
score: 0
comment on: http://stackoverflow.com/q/51260383
type: Comment
type: QuestionComment

http://stackoverflow.com/a/77437440
has body: i just downgraded my pyhton version to 3.8 and it worked perfectly
type: Answer
score: -1
downvote count: 1
has comment: http://stackoverflow.com/comment/136518704
upvote count: 0
answers question: http://stackoverflow.com/q/51294268

http://stackoverflow.com/comment/89543766
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51283207
has text: You should store `word` somewhere. In the while loop, each time it runs you are overwritting the value
score: 0

http://stackoverflow.com/comment/89486304
type: Comment
has text: I've edited and it works perfectly. You have no idea how much you've helped! Thank you again!
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/51253183

http://stackoverflow.com/comment/89523659
type: Comment
type: QuestionComment
has text: Please post the full error trace.
comment on: http://stackoverflow.com/q/51264020
score: 1

http://stackoverflow.com/a/51317427
has comment: http://stackoverflow.com/comment/89610892
score: 3
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/51317270
has comment: http://stackoverflow.com/comment/89610912
has body: A way to access python address is to use id(). &gt;&gt;&gt; a=['aaa', 'bbb'] &gt;&gt;&gt; id(a) 62954056 &gt;&gt;&gt; id(a[0]) 62748912 &gt;&gt;&gt; id(a[1]) 61749544 Further reading is here [understanding-python-variables and memory management].
upvote count: 3

http://stackoverflow.com/comment/89505239
type: Comment
comment on: http://stackoverflow.com/a/51263614
type: AnswerComment
score: 0
has text: @DenverDang, ok I will try to fix it

http://stackoverflow.com/a/51212865
has comment: http://stackoverflow.com/comment/89406735
downvote count: 0
answers question: http://stackoverflow.com/q/51212813
has comment: http://stackoverflow.com/comment/89406698
type: Answer
has body: You don't need to return anything, because your operations are done in place. You can do the in-place changes in your function: def rename_n_index(data, col_in='tempus_interval_time', col_out='Timestamp'): data.rename(index=str, columns={col_in: col_out}, inplace=True) data.set_index('Timestamp', inplace=True) and any other references to the dataframe you pass into the function will see the changes made: &gt;&gt;&gt; import pandas as pd &gt;&gt;&gt; df = pd.DataFrame({'interval_time': pd.to_datetime(['2010-11-01 00:00:00', '2010-11-01 00:05:00', '2010-11-01 00:10:00', '2010-11-01 00:15:00']), ... 'A': [0.0] * 4}, index=range(4)) &gt;&gt;&gt; df A interval_time 0 0.0 2010-11-01 00:00:00 1 0.0 2010-11-01 00:05:00 2 0.0 2010-11-01 00:10:00 3 0.0 2010-11-01 00:15:00 &gt;&gt;&gt; def rename_n_index(data, col_in='tempus_interval_time', col_out='Timestamp'): ... data.rename(index=str, columns={col_in: col_out}, inplace=True) ... data.set_index('Timestamp', inplace=True) ... &gt;&gt;&gt; rename_n_index(df, 'interval_time') &gt;&gt;&gt; df A Timestamp 2010-11-01 00:00:00 0.0 2010-11-01 00:05:00 0.0 2010-11-01 00:10:00 0.0 2010-11-01 00:15:00 0.0 In the above example, the df reference to the dataframe shows the changes made by the function. If you remove the inplace=True arguments, the method calls return a new dataframe object. You can store an intermediate result as a local variable, then apply the second method to the dataframe referenced in that local variable: def rename_n_index(data, col_in='tempus_interval_time', col_out='Timestamp'): renamed = data.rename(index=str, columns={col_in: col_out}) return renamed.set_index('Timestamp') or you can chain the method calls directly to the returned object: def rename_n_index(data, col_in='tempus_interval_time', col_out='Timestamp'): return data.rename(index=str, columns={col_in: col_out})\ .set_index('Timestamp')) Because renamed is already a new dataframe, you can apply the set_index() call in-place to that object, then return …
score: 4
upvote count: 4

http://stackoverflow.com/q/51248923
has title: Filter pandas dataframe with SequenceMatcher
answer count: 1
has answer: http://stackoverflow.com/a/51249270
has body: When I filter the data frame using the the code below, it works fine my_df.loc[lambda x:x["name"]=="space"] When I filter using the following code, it gives an error my_df.loc[lambda x: difflib.SequenceMatcher(None,"email",x["name"]).ratio()&gt;0.8] I want to filter using SequenceMatcher and maybe using more complex condition than the above one Here is the full code: import pandas as pd import difflib my_df=pd.DataFrame({"name":["space","mapp","eemail","daata"],"id":[9,12,13,14]}) my_df.loc[lambda x:x["name"]=="space"] #this line works my_df.loc[lambda x: difflib.SequenceMatcher(None,"email",x["name"]).ratio()&gt;0.8] #this doesn't
accepted answer: http://stackoverflow.com/a/51249270
tagged with: dataframe
tagged with: pandas
type: AnsweredQuestion
tagged with: difflib
downvote count: 0
score: 1
favorite count: 0
type: Question
upvote count: 1
tagged with: python

http://stackoverflow.com/q/51322554
score: 6
favorite count: 0
type: Question
has title: SMOTE with missing values
tagged with: python
upvote count: 6
has body: I am trying to use SMOTE from imblearn package in Python, but my data has a lot of missing values and I got the following error: ValueError: Input contains NaN, infinity or a value too large for dtype('float64'). I checked the parameters here, and it seems that there is not one dealing with missing value. Is there a way to generate synthetic samples with missing values?
has answer: http://stackoverflow.com/a/51340756
answer count: 2
linked to: http://stackoverflow.com/q/25017626
type: UnansweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/51325203
tagged with: imblearn
tagged with: scikit-learn

http://stackoverflow.com/q/51257041
has answer: http://stackoverflow.com/a/51257154
has answer: http://stackoverflow.com/a/51257337
upvote count: 8
accepted answer: http://stackoverflow.com/a/51257337
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/51257107
favorite count: 0
possible better answer: http://stackoverflow.com/a/51257137
has answer: http://stackoverflow.com/a/51257137
has answer: http://stackoverflow.com/a/51257209
score: 8
answer count: 5
tagged with: python
has body: Now I have a numpy array, [[1 2] [3 4] [2 5]] and a vector. [2, 5, 2] I want to perform a contain operation between the array and the vector row wise. In other words, I want to check whether the first row [1, 2]contain 2, whether the second row [3, 4] contain 5. The expected output would look like: [True, False, True] How could I implement this function? Many thanks in advance.
has title: How to perform contain operation between a numpy array and a vector row-wise?
type: AnsweredQuestion
downvote count: 0

http://stackoverflow.com/a/51205506
has comment: http://stackoverflow.com/comment/89391992
has comment: http://stackoverflow.com/comment/89395853
has comment: http://stackoverflow.com/comment/89463502
downvote count: 0
answers question: http://stackoverflow.com/q/51188584
upvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/89392080
has body: # open the file with open('testDataFile.txt', 'r') as original: # get all file content into a variable allLines = original.readlines() # modify first line of the data allLines[0] = allLines[0].rstrip() + "I\n" # open the the same file in write mode modifyFile = open('testDataFile.txt', 'w') # Iterate all lines and write into the file for i in allLines: modifyFile.write(i) modifyFile.close()
has comment: http://stackoverflow.com/comment/89405150
score: 1

http://stackoverflow.com/q/51219981
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51262647
tagged with: pyqt5
upvote count: 1
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/89447818
tagged with: raspberry-pi
has title: Simple python GUI for raspberry pi development
score: 0
tagged with: pyqt
has answer: http://stackoverflow.com/a/51262647
answer count: 1
has body: I need some help getting my gui to function how I intend to. So for my GUI I need two push buttons and a timer. The timer counts down on the press of start/pause, then pauses when pressed again. The other button reset should be easy as just resetting the Qtimer. I tried to use qtdesigner to confiure the layout of my gui and while that worked, I cannot seem to add the timer in/vice versa. (it just will not show based on which one is located higher up on the .py file). For the timer I've been messing around with a modified version of the answer in this question PyQt - showing countdown timer. Any assistance on helping me get a countdown timer working with button interfacing would be very helpful. I made some changes to my code adding fixing my button slots I still cannot get the timer to display i get the error 'Ui_Form' object has no attribute 'setCentralWidget' which i cannot fix for the life of me. Please someone help me get the timer just on the gui I can configure where it goes latter. import sys from PyQt5 import QtCore, QtWidgets #import pymongo #import socket #import json #from time import sleep DURATION_INT = 300 state = "stopped" #connection = pymongo.MongoClient(host='192.168.4.2', port=27017) #db = connection.restdb class Ui_Form(object): def setupUi(self, Form): global state super().__init__() Form.setObjectName("Form") Form.resize(648, 561) self.pushButton_2 = QtWidgets.QPushButton(Form) self.pushButton_2.setGeometry(QtCore.QRect(170, 460, 93, 28)) self.pushButton_2.setObjectName("pushButton_2") self.lineEdit = QtWidgets.QLineEdit(Form) self.lineEdit.setGeometry(QtCore.QRect(190, 110, 231, 101)) self.lineEdit.setObjectName("lineEdit") self.lineEdit_2 = QtWidgets.QLineEdit(Form) self.lineEdit_2.setGeometry(QtCore.QRect(230, 270, 61, 51)) self.lineEdit_2.setObjectName("lineEdit_2") self.textEdit = QtWidgets.QTextEdit(Form) self.textEdit.setGeometry(QtCore.QRect(290, 270, 21, 51)) self.textEdit.setObjectName("textEdit") self.lineEdit_3 = QtWidgets.QLineEdit…
favorite count: 0
linked to: http://stackoverflow.com/q/40994187
has comment: http://stackoverflow.com/comment/89422979
has comment: http://stackoverflow.com/comment/89436102
tagged with: python
tagged with: qt
has comment: http://stackoverflow.com/comment/89431073

beautifulsoup
tags question: http://stackoverflow.com/q/51226635
tags question: http://stackoverflow.com/q/51219203
tags question: http://stackoverflow.com/q/51179961
tags question: http://stackoverflow.com/q/51256334
tags question: http://stackoverflow.com/q/51185110
tags question: http://stackoverflow.com/q/51238622
tags question: http://stackoverflow.com/q/51315550
tags question: http://stackoverflow.com/q/51229885
tags question: http://stackoverflow.com/q/51284741
tags question: http://stackoverflow.com/q/51214794
tags question: http://stackoverflow.com/q/51318839
tags question: http://stackoverflow.com/q/51171107
tags question: http://stackoverflow.com/q/51202820
tags question: http://stackoverflow.com/q/51228465
tags question: http://stackoverflow.com/q/51249722
tag name: beautifulsoup
tags question: http://stackoverflow.com/q/51242503
tags question: http://stackoverflow.com/q/51302839
tags question: http://stackoverflow.com/q/51172098
tags question: http://stackoverflow.com/q/51198549
tags question: http://stackoverflow.com/q/51276790
tags question: http://stackoverflow.com/q/51256851
tags question: http://stackoverflow.com/q/51269596
tags question: http://stackoverflow.com/q/51256960
tags question: http://stackoverflow.com/q/51243341
tags question: http://stackoverflow.com/q/51249975
tags question: http://stackoverflow.com/q/51185613
tags question: http://stackoverflow.com/q/51191740
tags question: http://stackoverflow.com/q/51323376
tags question: http://stackoverflow.com/q/51243849
tags question: http://stackoverflow.com/q/51322535
tags question: http://stackoverflow.com/q/51322250
tags question: http://stackoverflow.com/q/51234758
tags question: http://stackoverflow.com/q/51196874
tags question: http://stackoverflow.com/q/51299572
tags question: http://stackoverflow.com/q/51217764
tags question: http://stackoverflow.com/q/51213717
tags question: http://stackoverflow.com/q/51256948
tags question: http://stackoverflow.com/q/51208397
tags question: http://stackoverflow.com/q/51182153
type: Tag
tags question: http://stackoverflow.com/q/51317160
tags question: http://stackoverflow.com/q/51219664
tags question: http://stackoverflow.com/q/51272054
tags question: http://stackoverflow.com/q/51214853
tags question: http://stackoverflow.com/q/51224609
tags question: http://stackoverflow.com/q/51255494
tags question: http://stackoverflow.com/q/51240720
tags question: http://stackoverflow.com/q/51277605
tags question: http://stackoverflow.com/q/51219088
tags question: http://stackoverflow.com/q/51181637
tags question: http://stackoverflow.com/q/51280742
tags question: http://stackoverflow.com/q/51319019
tags question: http://stackoverflow.com/q/51179320
tags question: http://stackoverflow.com/q/51181721
tags question: http://stackoverflow.com/q/51252236
tags question: http://stackoverflow.com/q/51276635
tags question: http://stackoverflow.com/q/51226138
tags question: http://stackoverflow.com/q/51309325
tags question: http://stackoverflow.com/q/51182812
tags question: http://stackoverflow.com/q/51278332
tags question: http://stackoverflow.com/q/51257808
tags question: http://stackoverflow.com/q/51220732
tags question: http://stackoverflow.com/q/51276426
tags question: http://stackoverflow.com/q/51182467
tags question: http://stackoverflow.com/q/51189822
tags question: http://stackoverflow.com/q/51271691
tags question: http://stackoverflow.com/q/51288957
tags question: http://stackoverflow.com/q/51201020
tags question: http://stackoverflow.com/q/51253916
tags question: http://stackoverflow.com/q/51223953
tags question: http://stackoverflow.com/q/51306039
tags question: http://stackoverflow.com/q/51244373
tags question: http://stackoverflow.com/q/51221190
tags question: http://stackoverflow.com/q/51238064
tags question: http://stackoverflow.com/q/51188365
tags question: http://stackoverflow.com/q/51231660
tags question: http://stackoverflow.com/q/51253164
tags question: http://stackoverflow.com/q/51236461

http://stackoverflow.com/comment/89328263
has text: ...Above solution is giving me errors like `AttributeError: instance has no attribute '__getitem__'`. I am using `python 2.7`. Do I need to add extra things in the above solution ??
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/51172494
score: 0

http://stackoverflow.com/a/51213809
downvote count: 0
type: Answer
has body: Because you are using histogram2contour the color-bar on the right is not a legend but actually an object called colorbar. To update it you can configure it's properties in your trace. I have an example below where I make the tick marks orange and the title red. I used Jupyter Notebooks to create the example so I had to configure it to offline but you don't have too. Here is the documentation for the color-bar object. import plotly.graph_objs as go from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot init_notebook_mode(connected=True) import numpy as np x = np.random.uniform(-1, 1, size=500) y = np.random.uniform(-1, 1, size=500) trace = [go.Histogram2dContour( x = x, y = y, colorbar=dict( title='Colorbar', tickfont={'color':'#E90' }, titlefont={"color":'#FF0000'} ), )] iplot(trace, filename = "Basic Histogram2dContour")
answers question: http://stackoverflow.com/q/51210306
accepted answer of: http://stackoverflow.com/q/51210306
score: 4
upvote count: 4
has comment: http://stackoverflow.com/comment/89411981
type: AcceptedAnswer

http://stackoverflow.com/q/51184931
type: Question
has answer: http://stackoverflow.com/a/51184951
score: 0
answer count: 1
has title: How to refer to foreign key linked table
has body: I have two models: class Incident(models.Model): iid = models.IntegerField(primary_key=True) class Source(models.Model): sid = models.IntegerField(primary_key=True) incident = models.ForeignKey('Incident', on_delete=models.SET_NULL, null=True) url = models.TextField(validators=[URLValidator()]) I want to display every source linked to an incident, but this doesn't work: {% for source in incident.source.all %} {{ source.url }} {% if not forloop.last %}, {% endif %}{% endfor %}
type: UnansweredQuestion
tagged with: python
tagged with: django

http://stackoverflow.com/comment/89422362
has text: This is the output from netstat: Active Internet connections (only servers) Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name tcp 0 0 0.0.0.0:5555 0.0.0.0:* LISTEN 3971/python3
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51199475

http://stackoverflow.com/a/51242901
type: Answer
accepted answer of: http://stackoverflow.com/q/51242815
score: 0
answers question: http://stackoverflow.com/q/51242815
type: AcceptedAnswer
has body: The solution to your problem goes as follows : suppose your label is 'a' and entry is 'b' def changet(): a.configure(text=b.get()) root=Tk() a=Label(root,text='')#initial text is empty b=Entry(root) a.pack_forget() b.pack() Button(root,text="click here", commmand=changet).pack()

http://stackoverflow.com/q/51263477
type: Question
tagged with: apache-spark-sql
tagged with: pyspark
tagged with: hadoop
has comment: http://stackoverflow.com/comment/89506153
has comment: http://stackoverflow.com/comment/89505328
score: 0
tagged with: apache-spark
has body: We have 40 million resume document and 1 million job titles. we are using dataframe for both and then cross joining both documents. Then we are using finaldata.rdd.map(lambda row: process_row(row)) the function is taking too much time. It is not executing in parallel. sc = SparkContext() collection_file = sc.textFile("hdfs://ip:port/user/Mongo_11July") sqlContext = SQLContext(sc) collection_df = sqlContext.read.json(collection_file) collection_df.createOrReplaceTempView("temp1") jobtitle_file = sc.textFile("hdfs://ip:port/user/Jobtitle_11July") jobtitle_df = sqlContext.read.json(jobtitle_file) jobtitle_df.createOrReplaceTempView("jobtitle") df_cases = sqlContext.sql("SELECT _id,HTMLtext FROM temp1 ") df_job_titles = sqlContext.sql("SELECT distinct(Name) FROM jobtitle") schema = StructType([ StructField("_id", StructType([StructField("$oid",StringType(),True)]), True), StructField("HTMLtext", StringType(), True), StructField("Name", StringType(), True), StructField("Tags_Add", ArrayType(StringType()), True)]) finaldata = df_cases.crossJoin(df_job_titles) new_rdd = finaldata.rdd.map(lambda row: process_row(row)) new_df = sqlContext.createDataFrame(new_rdd,schema) final_new_df = new_df.groupBy("_id").agg(collect_list("Tags_Add").alias("Tags_Add")) flattenUdf = F.udf(fudf, ArrayType(StringType())) outputdataframe=final_new_df.select("_id", flattenUdf("Tags_Add").alias("Tags_Add"))
tagged with: python
favorite count: 0
has title: Apache spark python two dataframe rdd map not executing in parallel
answer count: 0
has comment: http://stackoverflow.com/comment/89506923
type: UnansweredQuestion
upvote count: 1
downvote count: 1

http://stackoverflow.com/q/51211870
type: UnansweredQuestion
tagged with: memory
answer count: 0
has title: delete matplotlib Line2D object from address
type: Question
has body: I'm currently trying to improve the memory usage of a script, that produces figures which are very "heavy" over time. before creating the figures : ('Before: heap:', Partition of a set of 337 objects. Total size = 82832 bytes. Index Count % Size % Cumulative % Kind (class / dict of class) 0 75 22 32520 39 32520 39 dict (no owner) 1 39 12 20904 25 53424 64 dict of guppy.etc.Glue.Interface 2 8 2 8384 10 61808 75 dict of guppy.etc.Glue.Share 3 16 5 4480 5 66288 80 dict of guppy.etc.Glue.Owner 4 84 25 4280 5 70568 85 str 5 23 7 3128 4 73696 89 list 6 39 12 2496 3 76192 92 guppy.etc.Glue.Interface 7 16 5 1152 1 77344 93 guppy.etc.Glue.Owner 8 1 0 1048 1 78392 95 dict of guppy.heapy.Classifiers.ByUnity 9 1 0 1048 1 79440 96 dict of guppy.heapy.Use._GLUECLAMP_ &lt;15 more rows. Type e.g. '_.more' to view.>) And after creating them : ('After : heap:', Partition of a set of 89339 objects. Total size = 32584064 bytes. Index Count % Size % Cumulative % Kind (class / dict of class) 0 2340 3 7843680 24 7843680 24 dict of matplotlib.lines.Line2D 1 1569 2 5259288 16 13102968 40 dict of matplotlib.text.Text 2 10137 11 3208536 10 16311504 50 dict (no owner) 3 2340 3 2452320 8 18763824 58 dict of matplotlib.markers.MarkerStyle 4 2261 3 2369528 7 21133352 65 dict of matplotlib.path.Path 5 662 1 2219024 7 23352376 72 dict of matplotlib.axis.XTick 6 1569 2 1644312 5 24996688 77 dict of matplotlib.font_manager.FontProperties 7 10806 12 856816 3 25853504 79 list 8 8861 10 708880 2 26562384 82 numpy.ndarray 9 1703 2 476840 1 27039224 83 dict of matplotlib.transforms.Affine2D &lt;181 more rows. Type e.g. '_.more' to view.>) then, I do : figures=[manager.canvas.figure for manager in matplotlib._pylab_helpers.Gcf.get_all_fig_managers()] for i, figure in enumerate(figures): figure.clf(); plt.close(figure) figures=[manager.canvas.figure for manager in matplotlib._pylab_helpers.Gcf.get_all_fig_managers()]#here, figures==[] del figures hp.heap() This prints : Partition of a set of 71966 objects. …
tagged with: python
score: 0
tagged with: garbage-collection
has comment: http://stackoverflow.com/comment/89417651
has comment: http://stackoverflow.com/comment/89482795
tagged with: matplotlib

http://stackoverflow.com/a/51206984
downvote count: 0
has comment: http://stackoverflow.com/comment/112238093
type: Answer
has comment: http://stackoverflow.com/comment/89398410
answers question: http://stackoverflow.com/q/51206941
has body: You can do it simpler using list comprehension. values = [14, 5, 53, "Mercedes", 5, 66, 5, 4, "BMW", 5, 4, 6, "Tesla", 111, 333, 22, 33, 44] newlist = [value for value in values if type(value) != int] PS: Don't save list as as variable as it 's a python class
score: 4
upvote count: 4

http://stackoverflow.com/comment/89470636
type: Comment
type: QuestionComment
has text: @RafaL try just `import sklearn`
score: 0
comment on: http://stackoverflow.com/q/51245311

http://stackoverflow.com/a/51245369
accepted answer of: http://stackoverflow.com/q/51243965
type: AcceptedAnswer
score: 8
type: Answer
downvote count: 0
has body: As stated in the Customizing test collection section: You can easily instruct pytest to discover tests from every Python file: # content of pytest.ini [pytest] python_files = *.py However, many projects will have a setup.py which they don’t want to be imported. Moreover, there may files only importable by a specific python version. For such cases you can dynamically define files to be ignored by listing them in a conftest.py file: # content of conftest.py import sys collect_ignore = ["setup.py"] if sys.version_info[0] > 2: collect_ignore.append("pkg/module_py2.py")
answers question: http://stackoverflow.com/q/51243965
upvote count: 8

http://stackoverflow.com/comment/89495697
score: 0
comment on: http://stackoverflow.com/q/51239715
type: QuestionComment
type: Comment
has text: I updated my question. Please review it. I explained about the method I used to generate textures and my question now.

http://stackoverflow.com/comment/89346203
type: Comment
comment on: http://stackoverflow.com/a/51175791
score: 0
has text: Thanks for the answer, unfortunately for me, it still returns this error `'One or more row labels was not found'`
type: AnswerComment

http://stackoverflow.com/a/51263958
has comment: http://stackoverflow.com/comment/89590030
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51263888
answers question: http://stackoverflow.com/q/51263888
has body: In both your __init__ and registration methods, participants is a variable that is local to each method. This means that after the methods finish running, those variable vanish. If you want to store participants as part of the Competition class, you can attach it to the instantiated objects using self class Competition(object): def __init__(self, place, date, start_place, start_time): self.place = place self.date = date self.start_place = start_place self.start_time = start_time self.participants = [] def registration(self, name): self.name = name self.participants.append(self.name)
type: Answer
upvote count: 1
score: 1

http://stackoverflow.com/q/51268386
score: 6
possible better answer: http://stackoverflow.com/a/51268854
type: Question
has body: I have two matrix (same row and column): one with float values, which are grouped by indices in the other matrix. As a result, I want a dictionary or a list with the sums of the elements for each index. Indices always start at 0. A = np.array([[0.52,0.25,-0.45,0.13],[-0.14,-0.41,0.31,-0.41]]) B = np.array([[1,3,1,2],[3,0,2,2]]) RESULT = {0: -0.41, 1: 0.07, 2: 0.03, 3: 0.11} I found this solution, but I'm searching for a faster one. I'm working with matrix with 784 x 300 cells and this algorithm takes ~28ms to complete. import numpy as np def matrix_sum_by_indices(indices,matrix): a = np.hstack(indices) b = np.hstack(matrix) sidx = a.argsort() split_idx = np.flatnonzero(np.diff(a[sidx])&gt;0)+1 out = np.split(b[sidx], split_idx) return [sum(x) for x in out] If you can help me find a better and plain solution to this problem, I'll be grateful! EDIT: I made a mistake, time to complete is ~8ms in a 300*10 matrix, but ~28ms in a 784x300. EDIT2: My A elements are float64, so bincount give me ValueError.
has answer: http://stackoverflow.com/a/51268861
accepted answer: http://stackoverflow.com/a/51268861
tagged with: sum
upvote count: 6
tagged with: numpy
has answer: http://stackoverflow.com/a/51269358
answer count: 3
tagged with: matrix
has answer: http://stackoverflow.com/a/51268854
has comment: http://stackoverflow.com/comment/89515500
has title: Sum matrix elements group by indices in Python
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/89515287
tagged with: indices
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89515330
downvote count: 0

http://stackoverflow.com/comment/89535984
comment on: http://stackoverflow.com/q/51277247
type: QuestionComment
has text: How exactly are you making these experiments? It could just be differences due to random initialization or shuffling of the dataset (as you set shuffle to True).
score: 0
type: Comment

http://stackoverflow.com/q/51255395
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/51255403
tagged with: list
has answer: http://stackoverflow.com/a/51255403
type: Question
answer count: 2
upvote count: 0
score: -2
has title: unsupported operand type(s) for /: 'list' and 'int' Python
favorite count: 0
tagged with: int
has comment: http://stackoverflow.com/comment/89489922
tagged with: python
has body: I got the below error: unsupported operand type(s) for /: 'list' and 'int' How do I solve this problem? Any idea? Here is the part of my code in which there is an error(in cons_frac): sun_x = list(np.logspace(0, np.log10(46050), 100)) cons_frac = (sun_x / 46050) i tried this but it didn't work: sun_x = list(np.logspace(0, np.log10(46050), 100)) cons_frac = [] cons_frac.append(sun_x / 46050)
has answer: http://stackoverflow.com/a/51255415
downvote count: 2
accepted answer: http://stackoverflow.com/a/51255415

http://stackoverflow.com/a/77671003
answers question: http://stackoverflow.com/q/51255947
type: Answer
has body: I would suggest to use python3.5 -m pip install torch==1.6.0 (change to the python version you have and the package you need) after entering the environment with pipenv shell, especially if you have slow internet connection, because pipenv doesn't show the progress of downloading the package but pip does pipenv stops downloading a package after a certain time and outputs an error message but pip doesn't and waits for the package to download
score: 0

http://stackoverflow.com/comment/89604845
type: Comment
has text: What if you want to add more specific keys like the Pubmed one? @Arno-Nymous I would like to add a "vol" key (volume_s), but also a second author key named "nom2" which has an index: `nom = art.get('authFullName_s', None)[1]` Like "pmd", these 2 keys might not always be in the JSON dictionary.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51301740

http://stackoverflow.com/q/51201642
type: Question
has body: First let me say I've tried everything I could think of, after checking pretty much everywhere I could think of. Here is an example of the type of program I'm writing: from sympy.ntheory import factorint x = 10 ** 10 while True: print(str(factorint(x))) x += 1 No amount of clear_cache(), environ["SYMPY_USE_CACHE"]="no", or environ["SYMPY_TRACE_INT"]="no", (the three solutions I could find) make any dent in the gigantic amount of RAM that SymPy's factoring takes up, and what's worse is that it seems like after each number, the cached whatever just...stays there, hogging space, resulting in RAM ballooning to Gigabytes within minutes. Is there anything I can do? What other factorization functions out there exist for use with Python? I couldn't find much else out there...Thanks in advance.
tagged with: sympy
downvote count: 0
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
answer count: 0
score: 1
has title: Why does SymPy's factorint function take up so much RAM and why doesn't turning off cache fix it?
upvote count: 1

http://stackoverflow.com/comment/89369945
has text: I need the mass in the flowline, the flowline connects to two nodes, a from_node and a to_node. If the flow (q_flowline) is positive i need the concentration in the from_node but if the flow is negative I need the concentration in the to_node.
score: 0
comment on: http://stackoverflow.com/q/51193747
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89617145
comment on: http://stackoverflow.com/q/51320802
score: 1
has text: Side question: is there any particular reason you need version 2.7.3 instead of 2.7.15? The latter is exactly the same, just with a lot more bug fixes.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51190740
has comment: http://stackoverflow.com/comment/89372026
tagged with: python
has title: Reduce multi-dimensional array of strings along axis in Numpy
type: AnsweredQuestion
score: 4
has comment: http://stackoverflow.com/comment/89363234
has answer: http://stackoverflow.com/a/51192426
type: Question
tagged with: numpy
has body: Does Numpy implement some function for reducing multi-dimensional array of strings? I know it offers some features for string concatenation of multiple arrays, but I haven't found anything about string reduction. Let's say I have a 2-D array of strings: np.array([['a', 'b', 'c'],['e','f','g']]) And I want to convert it to: np.array(['a b c','e f g']) Is there better way, than using a for loop, such as: old_strings = np.array([['a', 'b', 'c'],['e','f','g']]) new_strings = np.array([]) for s in old_strings: new_strings = np.append(new_strings, (' '.join(s)))
tagged with: arrays
accepted answer: http://stackoverflow.com/a/51192426
has comment: http://stackoverflow.com/comment/89367138
upvote count: 4
has comment: http://stackoverflow.com/comment/89372062
answer count: 2
possible better answer: http://stackoverflow.com/a/51190951
downvote count: 0
has answer: http://stackoverflow.com/a/51190951
favorite count: 0

http://stackoverflow.com/a/51262379
score: 0
has comment: http://stackoverflow.com/comment/89504094
type: Answer
answers question: http://stackoverflow.com/q/51262226
has body: If you return a three arguments from func(), that it have to work: def func(a): return a + 1, a + 2, a + 3 d = {} for i in range(1, 4): df_a_i, df_b_i, df_c_i = func(i) d['df_a_%i' % i] = df_a_i d['df_b_%i' % i] = df_b_i d['df_c_%i' % i] = df_c_i print(d['df_a_1'])
has comment: http://stackoverflow.com/comment/89502825

http://stackoverflow.com/a/51201544
accepted answer of: http://stackoverflow.com/q/51201461
has comment: http://stackoverflow.com/comment/89384427
answers question: http://stackoverflow.com/q/51201461
type: Answer
has comment: http://stackoverflow.com/comment/89384509
upvote count: 2
score: 2
has body: Depends on what you mean by "proper". As far as PEP 8 is concerned, both styles are valid… Yes # Aligned with opening delimiter. foo = long_function_name(var_one, var_two, var_three, var_four) # More indentation included to distinguish this from the rest. def long_function_name( var_one, var_two, var_three, var_four): print(var_one) # Hanging indents should add a level. foo = long_function_name( var_one, var_two, var_three, var_four) … but both of your examples are invalid for other reasons. The second one is indented 2 spaces, while the first one is indented 19 spaces, but: Use 4 spaces per indentation level. (It isn't entirely clear that "more indentation" should be a fixed number of indent levels, but I'm pretty sure that's the intention.) However, it also says that: The 4-space rule is optional for continuation lines. Of course all of PEP 8 is optional, and especially so for code that isn't meant for the stdlib, but this is apparently especially optional. And both of them go way beyond the right edge of the window: Limit all lines to a maximum of 79 characters. For flowing long blocks of text with fewer structural restrictions (docstrings or comments), the line length should be limited to 72 characters. And the first one puts the closing paren in the wrong place: The closing brace/bracket/parenthesis on multiline constructs may either line up under the first non-whitespace character of the last line of list, as in: my_list = [ 1, 2, 3, 4, 5, 6, ] … or it may be lined up under the first character of the line that starts the multiline construct, as in: my_list = [ 1, 2, 3, 4, 5, 6, ] Your second example does the second version right; your first example does the first version wrong. However, there is an obvious advantage to the second style (properly fixed to use a 4-space indent) here: The whole reason you're splitting this onto multiple lines is to make it easier to fit the text into the window (even if you haven't succeeded). The first style wastes an extra 14 c…
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/51313079
answers question: http://stackoverflow.com/q/51313055
upvote count: 2
type: AcceptedAnswer
type: Answer
has body: You loop over text by making consecutive copies of characters into c. You only ever change c. c = "2" There is nothing which changes text before you return it.
score: 2
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51313055

http://stackoverflow.com/a/51193391
score: 1
has comment: http://stackoverflow.com/comment/89369097
upvote count: 1
has comment: http://stackoverflow.com/comment/89369211
has body: You can try like this to get the information you would like to grab. I used selenium in combination with BeautifulSoup (not necessary though). The main problem was that the Product information in the first url is within id name productDetails_detailBullets_sections1 whereas the Product information in the second url is within id name productDetails_techSpec_section_1. I had to write selectors in such a way so that the script can get information from the two links. This is the modified code: import csv from selenium import webdriver from bs4 import BeautifulSoup links = [ 'https://www.amazon.com/Instant-Pot-Multi-Use-Programmable-Packaging/dp/B00FLYWNYQ/ref=sr_1_1?s=home-garden&amp;ie=UTF8&amp;qid=1520264922&amp;sr=1-1&amp;keywords=-gggh', 'https://www.amazon.com/Amagle-Flexible-Batteries-Operated-Included/dp/B01NGTKTDK/ref=sr_1_2?s=furniture&amp;ie=UTF8&amp;qid=1520353343&amp;sr=1-2&amp;keywords=-jhgf' ] def get_information(driver,urls): with open("productDetails.csv","w",newline="") as infile: writer = csv.writer(infile) writer.writerow(['Title','Dimension','Weight','ASIN']) for url in urls: driver.get(url) soup = BeautifulSoup(driver.page_source,"lxml") title = soup.select_one("#productTitle").get_text(strip=True) dimension = ([item.select_one("td").get_text(strip=True) for item in soup.select("#prodDetails [id^='productDetails_'] tr") if "Product Dimensions" in item.text]+["N\A"])[0] weight = ([item.select_one("td").get_text(strip=True) for item in soup.select("#prodDetails [id^='productDetails_'] tr") if "Item Weight" in item.text]+["N\A"])[0] ASIN = ([item.select_one("td").get_text(strip=True) for item in soup.select("#prodDetails [id^='productDetails_'] tr") if "ASIN" in item.text]+["N\A"])[0] writer.writerow([title,dimension,weight,ASIN]) print(f'{title}\n{dimension}\n{weight}\n{ASIN}\n') if __name__ == '__main__': driver = webdriver.Chrome() try: get_information(driver,links) finally: driver.quit() I skipped the proxy part. However, you can include them as re…
accepted answer of: http://stackoverflow.com/q/51188630
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51188630
has comment: http://stackoverflow.com/comment/89368924
type: Answer

http://stackoverflow.com/q/51310767
answer count: 1
downvote count: 0
tagged with: virtualenv
favorite count: 0
accepted answer: http://stackoverflow.com/a/51311074
has body: Does conda provide for a way to activate an environment from within a running Python program? For instance, each virtual environment (venv) created with virtualenv has a script venv/bin/activate_this.py (assuming you are on Linux), that can be used to activate venv within a running Python program as follows: activate_this = '/full/path/to/venv/bin/activate_this.py' with open(activate_this) as file_: exec(file_.read(), dict(__file__=activate_this)) I am just wondering if I need to adapt virtualenv's activate_this.py for this job (virtualenv and conda environments are structured slightly differently, so wouldn't work as is) or there's an existing way.
has comment: http://stackoverflow.com/comment/89609006
tagged with: python
has title: Activating conda environment within Python
tagged with: miniconda
type: AnsweredQuestion
type: Question
has answer: http://stackoverflow.com/a/51311074
score: 4
has comment: http://stackoverflow.com/comment/89608474
tagged with: conda
upvote count: 4
has comment: http://stackoverflow.com/comment/89609091
has comment: http://stackoverflow.com/comment/89608461

http://stackoverflow.com/a/51237719
type: Answer
answers question: http://stackoverflow.com/q/51237582
has body: To elaborate on ManKind_008's answer: Your explicit line numbers are the problem. Pandas interprets these as valid data. Using ManKinds solution does properly set the index column, but since your line numbers start at zero you end up with a DataFrame like: pd.read_fwf('test.csv', header=None, index_col=0, skiprows=6) 1 2 0 1 22 23 2 44 44 3 55 55 4 66 66 5 77 77 Instead I suggest you read in all of your data using: pd.read_fwf('test.csv', header=None, skiprows=6).iloc[:, 1:] 1 2 0 22 23 1 44 44 2 55 55 3 66 66 4 77 77 This leaves you with what you seem to need. The iloc call is ignoring the first row of data (your line numbers). From here the df.values command will give you: array([[22, 23], [44, 44], [55, 55], [66, 66], [77, 77]]) If you don't want a np.array, you can explicitly cast this to a list using the list() function.
has comment: http://stackoverflow.com/comment/89454560
score: 0

http://stackoverflow.com/comment/89319512
type: QuestionComment
score: 1
has text: If black is 0 and white is 1, you can invert with `image=1-image`. If black is 0 and white is 255, you can invert with image=255-image.
comment on: http://stackoverflow.com/q/51168268
type: Comment

http://stackoverflow.com/a/51290343
type: AcceptedAnswer
has body: You can use the num_workers parameter to specify the number of processes for the compute method. results = compute(*delayed_values, scheduler='processes', num_workers=5)
answers question: http://stackoverflow.com/q/51285420
type: Answer
score: 16
upvote count: 16
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51285420

http://stackoverflow.com/comment/89488920
type: Comment
type: AnswerComment
has text: You should only call `__init__` if `isinstance(self, something)`
score: 0
comment on: http://stackoverflow.com/a/51254931

http://stackoverflow.com/comment/89353680
comment on: http://stackoverflow.com/q/51169958
has text: I tried QSpinBox. the code is: self.B_value = QtGui.QSpinBox(self) checkBox = QtGui.QCheckBox('Test', self) checkBox.stateChanged.connect(lambda:self.run4('Calculation.py',self.B_value.text())) def run4(self, path, B_value): B_value = int(self.B_value.text()) print(type(B_value)) print(B_value) subprocess.call(['python3', path, 'Calculation.py', B_value], shell=True) Second file "Calculation.py": Value=sys.argv[0] x=0xD0 y=0x00 a = Value print(a) b = int(((a*255)/100)+1) c = b>>4 B_d = c+x print(B_d). error:unsupported operand type(s) for /:'str' and 'int'
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51327158
has comment: http://stackoverflow.com/comment/89632811
has comment: http://stackoverflow.com/comment/89633024
has comment: http://stackoverflow.com/comment/89633519
score: 0
has comment: http://stackoverflow.com/comment/89633199
type: Answer
has comment: http://stackoverflow.com/comment/89632714
has comment: http://stackoverflow.com/comment/89633869
has comment: http://stackoverflow.com/comment/89633099
has body: Matches may have the same start. Matches may see their start changed while existing in the set. This violates the constraints that containers use to track their elements. You can't change the sort order of an element while it is in a container. The container has no way of knowing that the sort order has changed. Objects must be different. If you read the documentation for sortedset, it clearly states: The hash and total ordering of values must not change while they are stored in the sorted set. There doesn't even exist a total ordering for your elements, because there exist x != y where it is neither true that x &lt; y or x &gt; y. You haven't mentioned __hash__ at all. I am not sure how you would expect to solve these problems, since I am not familiar with your code, and solving them may require some redesign work. However, these problems are what is causing the unexpected behavior in your program.
has comment: http://stackoverflow.com/comment/89633142
answers question: http://stackoverflow.com/q/51322672
has comment: http://stackoverflow.com/comment/89635036
accepted answer of: http://stackoverflow.com/q/51322672
has comment: http://stackoverflow.com/comment/89631111
type: AcceptedAnswer

http://stackoverflow.com/comment/117303928
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/58624309
has text: THANK YOU for this! At the moment they offer 1.000 calls for free, and then there is an undisclosed fee to be paid. Anyway, I got stuck at the "Generating personalized code samples" step. This is how I solved it: https://medium.com/@netpalantir/adobe-document-services-stuck-on-creating-credentials-4ef3e1d3a614
type: Comment

http://stackoverflow.com/comment/89812162
has text: What is your operating system? Have you enabled SELinux or AppArmor?
type: QuestionComment
comment on: http://stackoverflow.com/q/51311793
score: 0
type: Comment

http://stackoverflow.com/comment/89368600
comment on: http://stackoverflow.com/q/51193444
score: 0
type: Comment
type: QuestionComment
has text: Edit the question to include this info please

http://stackoverflow.com/comment/89576730
type: Comment
type: QuestionComment
has text: I have provided a solution
comment on: http://stackoverflow.com/q/51299581
score: 0

command-line-interface
tags question: http://stackoverflow.com/q/51267814
tags question: http://stackoverflow.com/q/51263436
tag name: command-line-interface
type: Tag
tags question: http://stackoverflow.com/q/51241718

http://stackoverflow.com/a/51177831
score: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/89346840
answers question: http://stackoverflow.com/q/51177453
type: Answer
has comment: http://stackoverflow.com/comment/89343909
has body: This is all I had to change. Basically, because the block was still out of the screen, hence the gameover() used to get executed again, so when I brought the block back onto the screen, it worked. else: #continue self.x=display_height/2 self.y=display_width/2 self.events()
upvote count: 1

http://stackoverflow.com/q/51290827
tagged with: instantiation
tagged with: object
possible better answer: http://stackoverflow.com/a/51290884
has comment: http://stackoverflow.com/comment/89559383
answer count: 2
upvote count: 0
has comment: http://stackoverflow.com/comment/89559348
has body: I am a Java programmer struggling to learn Python, and almost certainly about to ask a duplicate question. In my Python code, I need to create an object that basically holds a list. When an object is instantiated, the list is to be empty. Later in the code, I want to add items: 1 #!/usr/bin/python 2 3 class objWithList: 4 # myList # define a global variable here? 5 def __init__(self): 6 print "New Object created!" 7 myList = list() # tell Python "myList" is a list? 8 def addSomething(cls, x): 9 myList.append(x) 10 11 myObj = objWithList() # create the object 12 str1 = "Add me" 13 myObj.addSomething(str1) # add item to obj's list When I run the above code, I get this error message: me@myBox/python_Sandbox# ./test1.py New Object created! Traceback (most recent call last): File "./test1.py", line 13, in &lt;module&gt; myObj.addSomething(str1) # add item to obj's list File "./test1.py", line 9, in addSomething myList.append(x) NameError: global name 'myList' is not defined me@myBox/python_Sandbox# So it looks like the object is successfully created, but when I call addSomething(), the list is not defined. Is that because the myList created in __init__() goes out of scope once the object constructor is completed? I get the same error message when I move the myList = list() command to the top of the class definition: 3 class objWithList: 4 myList = list() # moved list creation here 5 def __init__(self): 6 print "New Object created!" 7 def addSomething(cls, x): 8 myList.append(x) So how do I create an empty list which is available after the object is created? I should also add that I am writing on Python 2.7. My company likes this version, so I'm stuck with it. Don't ask. Thanks
has comment: http://stackoverflow.com/comment/89559439
has title: How to create a Python object that holds an empty list
favorite count: 0
score: -3
has answer: http://stackoverflow.com/a/51290924
accepted answer: http://stackoverflow.com/a/51290924
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51290884
tagged with: list
has comment: http://stackoverflow.com/comment/89559448
downvote count: 3
has comment: http://stackoverflow.com/comment/89559379
type: Question

http://stackoverflow.com/q/51302203
has title: change index while looping through file in python
tagged with: file
tagged with: loops
type: Question
linked to: http://stackoverflow.com/q/6475328
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/51303903
has answer: http://stackoverflow.com/a/51302332
has body: Supposed i have to read a file (quite big, about 20.000 lines). I have to loop through the lines and look for a keyword e.g. STACKOVERFLOW. Once the keyword is found, i know that i will have to process the next 10 lines. Currently i am doing like: with open(filepath) as f: for line_idx, line in enumerate(f): if re.match(my_keyword, line): # do something here from line_idx to line_idx + 9 # can i jump directly to line_idx + 10 ??? Is there a way to skip the process (loop + search) for the next 10 lines when the keyword is found and continue to loop and search at e.g. line_index + 10 further? Thank you! UPDATE I would like to add that what i wanted is a way which i don't have to temporarily save the file into a list. With this method i had a solution of myself already.
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/a/51248915
answers question: http://stackoverflow.com/q/51247247
type: AcceptedAnswer
downvote count: 0
upvote count: 2
type: Answer
accepted answer of: http://stackoverflow.com/q/51247247
score: 2
has body: In pyspark when/otherwise are equivalent of if/else. If df is your actual dataframe then: new_df = df.withColumn('banding', when(col('numb_of_count') &lt;3,col('numb_of_count')).when(col('numb_of_count') &lt;=5 , '3-5').when(col('numb_of_count') &lt;= 10, '6-10').otherwise('+11')) df.withColumn df.withColumn adds a new column to the frame with first argument as name of new column. more info here when/otherwise analogous to if/else, more info here This is an excellent answer to learn more about when/otherwise.

http://stackoverflow.com/a/51289675
accepted answer of: http://stackoverflow.com/q/51289453
type: Answer
answers question: http://stackoverflow.com/q/51289453
score: 0
type: AcceptedAnswer
has body: '''&lt;input type="text" name="firstname"&gt; &lt;input type="text" name="firstname1"&gt; &lt;input type="text" name="firstname2"&gt; &lt;input type="text" name="txt" onchange="myFunction()"&gt; &lt;input type="submit" value="Submit"&gt; &lt;script&gt; function myFunction() { {} } &lt;/script&gt;'''.format(THE PYTHON CODE THAT EVALUATE TO TEXT)

http://stackoverflow.com/comment/89465028
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51241520
has text: If newer versions don't make them publicly available then it won't work.
score: 0

http://stackoverflow.com/comment/89351370
has text: @DyZ Unfortunately it doesn't work because my file path contains \f which needs to be escaped (hence attempting to use the 'r' prefix to have it read as raw).
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51184260

http://stackoverflow.com/q/51310263
has answer: http://stackoverflow.com/a/51310373
linked to: http://stackoverflow.com/q/75851273
favorite count: 0
has answer: http://stackoverflow.com/a/51310378
has comment: http://stackoverflow.com/comment/133792905
has title: pandas apply updates inplace but returns None
tagged with: python
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/133794523
has comment: http://stackoverflow.com/comment/89597205
upvote count: 3
downvote count: 1
accepted answer: http://stackoverflow.com/a/51310378
type: Question
tagged with: data-manipulation
tagged with: dataframe
has body: I do not understand this apply behavior .. pandas apply updates inplace but returns None &gt;&gt;&gt;import pandas as pd &gt;&gt;&gt;df_test = pd.Series({0: {'A', 'E'}, 1: {'A', 'C', 'E', 'S'}, 2: {'A', 'C', 'E'}, 3: {'A', 'C', 'E', 'S'}, 4: {'A', 'E'}}) &gt;&gt;&gt;df_test 0 {A, E} 1 {A, S, E, C} 2 {A, C, E} 3 {A, S, E, C} 4 {A, E} dtype: object &gt;&gt;&gt;df_test.apply(lambda x: x.add("X")) 0 None 1 None 2 None 3 None 4 None dtype: object but, &gt;&gt;&gt;df_test 0 {A, X, E} 1 {A, X, S, E, C} 2 {A, X, C, E} 3 {A, X, S, E, C} 4 {A, X, E} dtype: object so df_test is updated. but then if I do this: &gt;&gt;&gt; df_test = df_test.apply(lambda x: x.add("X")) &gt;&gt;&gt; df_test 0 None 1 None 2 None 3 None 4 None dtype: object what is the explanation for thisbehavior - the apply is updating the dataframe in place but returned type is None.
possible better answer: http://stackoverflow.com/a/51310373
answer count: 2
tagged with: pandas

http://stackoverflow.com/comment/89468545
has text: Does it have to be a dictionary? Take a look at `OrderedDict`. Maybe a list of tuples would be sufficient for your needs.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51244920
score: 1

http://stackoverflow.com/comment/89464475
score: 1
has text: @DGMS89 Your code created a generator object, so that`s probably why it didn`t work ;)
type: AnswerComment
comment on: http://stackoverflow.com/a/51242754
type: Comment

http://stackoverflow.com/q/51259599
has title: Can I release a 1.x update if my package is on 2.x? (PyPi)
type: Question
score: 1
has comment: http://stackoverflow.com/comment/89497803
has comment: http://stackoverflow.com/comment/89498765
has body: Example: PackageX on PyPi has major version 2, but a lot of users are still using 1.x and in need of a security patch. Can a 1.x update be released even if the package is currently released on 2.x?
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/89497575
has comment: http://stackoverflow.com/comment/89497706
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89499166
has comment: http://stackoverflow.com/comment/89497838
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/89498924
upvote count: 1
tagged with: pypi

neural-network
tags question: http://stackoverflow.com/q/51190032
tags question: http://stackoverflow.com/q/51210210
tags question: http://stackoverflow.com/q/51193952
tags question: http://stackoverflow.com/q/51185079
tags question: http://stackoverflow.com/q/51207093
tags question: http://stackoverflow.com/q/51270927
tags question: http://stackoverflow.com/q/51181393
tags question: http://stackoverflow.com/q/51210686
tags question: http://stackoverflow.com/q/51235068
tags question: http://stackoverflow.com/q/51267029
tags question: http://stackoverflow.com/q/51181152
tags question: http://stackoverflow.com/q/51272531
tags question: http://stackoverflow.com/q/51288213
tags question: http://stackoverflow.com/q/51321826
tags question: http://stackoverflow.com/q/51221312
tags question: http://stackoverflow.com/q/51192752
type: Tag
tags question: http://stackoverflow.com/q/51255290
tags question: http://stackoverflow.com/q/51167682
tags question: http://stackoverflow.com/q/51273695
tags question: http://stackoverflow.com/q/51232008
tags question: http://stackoverflow.com/q/51189573
tags question: http://stackoverflow.com/q/51248889
tags question: http://stackoverflow.com/q/51200361
tags question: http://stackoverflow.com/q/51229932
tags question: http://stackoverflow.com/q/51236338
tags question: http://stackoverflow.com/q/51232301
tags question: http://stackoverflow.com/q/51294885
tag name: neural-network
tags question: http://stackoverflow.com/q/51182300
tags question: http://stackoverflow.com/q/51180234
tags question: http://stackoverflow.com/q/51287109
tags question: http://stackoverflow.com/q/51321610
tags question: http://stackoverflow.com/q/51272258
tags question: http://stackoverflow.com/q/51212755

http://stackoverflow.com/a/51213375
has body: Solution Since source is a StringProperty, assign an empty string to it. kivy_image_widget.source = '' Image »source source Filename / source of your image. source is a StringProperty and defaults to None. Example main.py from kivy.app import App from kivy.uix.boxlayout import BoxLayout class RootWidget(BoxLayout): def clear_image(self): self.ids.img2.source = '' self.ids.img2.reload() class TestApp(App): def build(self): return RootWidget() if __name__ == "__main__": TestApp().run() test.kv #:kivy 1.11.0 &lt;RootWidget&gt;: orientation: 'vertical' Image: id: img1 source: 'kivyLogo.png' Image: id: img2 source: 'raspberrypi.png' Button: text: 'Clear Image 2' size_hint_y: 0.1 on_release: root.clear_image() Output
downvote count: 0
answers question: http://stackoverflow.com/q/51209264
type: Answer
upvote count: 2
score: 2

http://stackoverflow.com/a/51212823
answers question: http://stackoverflow.com/q/51212690
score: 0
has body: In the example you give, there is no x ... by the time you get back to try to print it. Its gone out of scope. You do have some options, one of which is to return it: foo.py = def main(): x = 1 return x And then elsewhere: import foo x = foo.main() print(x)
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/51212690

http://stackoverflow.com/comment/89620671
comment on: http://stackoverflow.com/q/51319769
type: QuestionComment
type: Comment
has text: I think it is as @user2357112 said, it is only a rounding errors because your error are all values that tend towards zero. This is very possible because you are doing exponent of a trigonometric function of a fraction, while we during testing copy the values of `xi` as `2.51325641-2.34963293j ...` inside your machine it is probably `2.51325641.... - 2.34963293...j ...` some more values that are not printed that would only show up for when an a mathematical operation is suppose to tend to zero.
score: 0

http://stackoverflow.com/comment/89475661
comment on: http://stackoverflow.com/q/51248322
has text: Please make sure what you post here is pastable into an interpreter. I don't want to add quotes for you.
type: Comment
type: QuestionComment
score: 2

http://stackoverflow.com/comment/89516093
type: Comment
type: QuestionComment
has text: @usr2564301 I will reframe my question, thank you
comment on: http://stackoverflow.com/q/51252872
score: 0

http://stackoverflow.com/comment/89594318
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51308220
has text: Not the the main widget, no. The only fixed size I have used is the one applied to the height of the table.

http://stackoverflow.com/comment/89448489
type: QuestionComment
comment on: http://stackoverflow.com/q/51234746
score: 2
has text: I'm sorry, but by only looking at your code, I seriously have no idea what you're trying to do.. `for len in s` (looping the string by each character), `if len(s) <= 70` (if length of the string less than or equal to 70), `len(s) + 70 - len(s)` (does nothing), `return s` (returns the orginal input string).
type: Comment

http://stackoverflow.com/q/51236909
has answer: http://stackoverflow.com/a/51244452
tagged with: python
has answer: http://stackoverflow.com/a/51239090
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/51244452
score: 1
upvote count: 1
type: Question
has title: Spark window function per time
tagged with: apache-spark-sql
tagged with: pyspark
accepted answer: http://stackoverflow.com/a/51239090
has body: I have some dataframe with the following structure: ID| Page | User | Timestamp | |1|Page 1 |Ericd |2002-09-07 19:39:55| |1|Page 1 |Liir |2002-10-12 03:01:42| |1|Page 1 |Tubby |2002-10-12 03:02:23| |1|Page 1 |Mojo |2002-10-12 03:18:24| |1|Page 1 |Kirf |2002-10-12 03:19:03| |2|Page 2 |The Epopt |2001-11-28 22:27:37| |2|Page 2 |Conversion script|2002-02-03 01:49:16| |2|Page 2 |Bryan Derksen |2002-02-25 16:51:15| |2|Page 2 |Gear |2002-10-04 12:46:06| |2|Page 2 |Tim Starling |2002-10-06 08:13:42| |2|Page 2 |Tim Starling |2002-10-07 03:00:54| |2|Page 2 |Salsa Shark |2003-03-18 01:45:32| and I would like to find the number of users which were visited the pages for some time period (per each month for example). For example for 10th month of 2002 the result will be |1|Page 1 |Liir |2002-10-12 03:01:42| |1|Page 1 |Tubby |2002-10-12 03:02:23| |1|Page 1 |Mojo |2002-10-12 03:18:24| |1|Page 1 |Kirf |2002-10-12 03:19:03| |2|Page 2 |Gear |2002-10-04 12:46:06| |2|Page 2 |Tim Starling |2002-10-06 08:13:42| |2|Page 2 |Tim Starling |2002-10-07 03:00:54| and the count of pages: numberOfUsers (in October 2002) |1|Page 1 | 4 |2|Page 2 | 3 The question is also how to apply this logic for the every month for each year. I figured out how to find for example occurences for the last n-days days = lambda i: i * 86400 window = (Window().partitionBy(col("page")) .orderBy(col("timestamp").cast("timestamp").cast("long")).rangeBetween(-days(30), 0)) df = df.withColumn("monthly_occurrences", func.count("user").over(window)) df.show() some suggestions I'll appreciate
has comment: http://stackoverflow.com/comment/89613707
answer count: 2
tagged with: apache-spark
downvote count: 0
favorite count: 0

http://stackoverflow.com/comment/89470951
type: QuestionComment
has text: So, do you need to solve by MongoDB aggregation only?
score: 0
comment on: http://stackoverflow.com/q/51246163
type: Comment

http://stackoverflow.com/comment/89413183
type: QuestionComment
has text: Hi Bryan ...I tried replacing the For loop with the separated lines of code, but then I get an error in show_frame : line 34, in show_frame frame = self.frames[name] KeyError: <class '__main__.ScreenOne'>
score: 0
comment on: http://stackoverflow.com/q/51203784
type: Comment

http://stackoverflow.com/comment/89365472
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51180696
type: Comment
has text: Thanks Steffen, this was my guess as well. However, I tried exporting the certificate in all available formats and used it with requests as per documentation: `cert=cert_path`, but I get `Error: [('PEM routines', 'PEM_read_bio', 'no start line'), ('SSL routines', 'SSL_CTX_use_PrivateKey_file', 'PEM lib')]. ` Do you possibly know why?

http://stackoverflow.com/comment/89332954
comment on: http://stackoverflow.com/a/51174909
type: AnswerComment
score: 0
type: Comment
has text: If I type `x = input()` and then `1 2`, `x` is a string with the value `'1 2'`. Moreover, `x.split()` yields `['1', '2']`. The format seems correct for what @VijayaKrishnan wants. Does the result of `input` vary between python2 and python3 (I used python 3.5 for this test)?

http://stackoverflow.com/q/51172555
possible better answer: http://stackoverflow.com/a/63040799
has answer: http://stackoverflow.com/a/63040799
favorite count: 0
type: Question
score: 1
has body: I am trying to find contrast in an image using greycomatrix here is the code: import cv2 import numpy as np from scipy import misc from skimage.feature import greycomatrix, greycoprops img=cv2.imread('leaf2.jpg') g=greycomatrix(img, [1], [0, np.pi/4, np.pi/2, 3*np.pi/4]) print (g) contrast = greycoprops(g, 'contrast') print(contrast) Here is the error: "The image must be a 2-D array" How to convert the image to a 2-D array, suitable for the function?
upvote count: 2
tagged with: glcm
answer count: 2
tagged with: python
has answer: http://stackoverflow.com/a/51172894
has comment: http://stackoverflow.com/comment/89350447
downvote count: 1
tagged with: opencv
tagged with: scikit-image
tagged with: image-processing
has title: greycomatrix for RGB image
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51172894

http://stackoverflow.com/comment/89477967
score: 0
type: Comment
type: QuestionComment
has text: So people will use matplotlib to zoom in? Or what interface are you thinking about?
comment on: http://stackoverflow.com/q/51237359

http://stackoverflow.com/q/51175154
downvote count: 2
upvote count: 1
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51175261
has answer: http://stackoverflow.com/a/51175196
score: -1
has answer: http://stackoverflow.com/a/51175403
type: Question
tagged with: python-2.7
possible better answer: http://stackoverflow.com/a/51175196
has answer: http://stackoverflow.com/a/51175341
has body: I have a question about how to get the average of every 2 elements in a list in python. Ex: a = [1, 3, 4, 1, 5, 2] In this case, as it needs to compute (1 + 4 + 5)/3 and the next one (3 + 1 + 2)/3. The new list would have the following values: amean = [3.3333,2] So far I have managed to average, but I have no idea how to create a loop for it to return and start the average on the second element (3 + 1 + 2)/3. Here's a piece of what I have done so far: import numpy as np a = [1.,3.,4.,1., 5., 2.] def altElement(my_list): b = my_list[:len(my_list):2] print b return np.mean(b) print altElement(a) Does anyone have any idea how to create this loop? Here's a link for the code that I have done so far: code
has answer: http://stackoverflow.com/a/51175367
favorite count: 0
has title: Average every 2 values in a list using a loop
accepted answer: http://stackoverflow.com/a/51175261
answer count: 5
linked to: http://stackoverflow.com/q/30245397
tagged with: python

http://stackoverflow.com/comment/89324964
type: QuestionComment
comment on: http://stackoverflow.com/q/51169926
score: 0
type: Comment
has text: I use ibm_db 2.0.8, I connect to DB2 server from RIDE editor, don't know about DB2 client. My python is intalled on remote machine (windows 8)

http://stackoverflow.com/q/51185970
type: Question
has title: IOError: FileNotFound when trying to use jython in java
tagged with: python
tagged with: java
has body: So I have this file located in a specific directory. Here I am trying to get access to my file: public static void main(String[] args) { try { PythonInterpreter interpreter = new PythonInterpreter(); interpreter.execfile("C:/Users/schueler/Desktop/TestForPhyton/testPython.py"); } catch (Exception ex) { System.out.println(""+ex); } } I get this error: IOError: (2, 'File not found - C:\\Users\\schueler\\Desktop\\TestForPhyton\\testPython.py (Das System kann die angegebene Datei nicht finden)')
upvote count: 1
has answer: http://stackoverflow.com/a/51186294
answer count: 1
tagged with: filenotfoundexception
tagged with: jython
accepted answer: http://stackoverflow.com/a/51186294
type: AnsweredQuestion
downvote count: 0
score: 1
favorite count: 0
tagged with: pythoninterpreter

http://stackoverflow.com/comment/89328799
has text: @desertnaut sorry they we're ment to just be my X & y. i have updated this.
comment on: http://stackoverflow.com/q/51172889
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/comment/89342546
score: 0
type: AnswerComment
has text: My main goal was replacing the time.sleep() with the loading animation. So first off I replaced the time.sleep() with test.animate(), but now I replaced time.sleep() with test.start(). The animation in the second file is not executing
comment on: http://stackoverflow.com/a/51179488
type: Comment

http://stackoverflow.com/comment/89607274
comment on: http://stackoverflow.com/q/51315264
has text: then you have `list` as a global variable, otherwise both python 2 and 3 will raise the TypeError.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89332290
type: QuestionComment
comment on: http://stackoverflow.com/q/51174199
has text: I edited the code section and had given the complete code.@roganjosh
score: 0
type: Comment

http://stackoverflow.com/a/51185956
answers question: http://stackoverflow.com/q/51185303
has comment: http://stackoverflow.com/comment/89354245
has comment: http://stackoverflow.com/comment/89357386
downvote count: 0
has comment: http://stackoverflow.com/comment/89354852
has comment: http://stackoverflow.com/comment/89358837
has comment: http://stackoverflow.com/comment/89392536
upvote count: 2
type: Answer
has body: You can obtain the schema by evaluating the string that you get from reading the json: import json from pyspark.sql.types import StructField, StringType, IntegerType, StructType with open('test.json') as f: data = json.load(f) df = sqlContext.createDataFrame([], schema = eval(data['tediasessionclose_schema'])) print(df.schema) outputs: StructType(List(StructField(@timestamp,StringType,true),StructField(message,StructType(List(StructField(componentAddress,StringType,true),StructField(values,StructType(List(StructField(confNum,StringType,true),StructField(day,IntegerType,true))),true))),true))) where test.json is: {"tediasessionclose_schema" : "StructType([ StructField('@timestamp', StringType()), StructField('message' , StructType([ StructField('componentAddress', StringType()), StructField('values', StructType([ StructField('confNum', StringType()), StructField('day', IntegerType())]))]))])"} Hope this helps!
has comment: http://stackoverflow.com/comment/89355444
score: 2
has comment: http://stackoverflow.com/comment/89695669

http://stackoverflow.com/q/51179446
has comment: http://stackoverflow.com/comment/89352271
answer count: 3
tagged with: python
has answer: http://stackoverflow.com/a/51196744
tagged with: turtle-graphics
type: UnansweredQuestion
has body: I'm new to the Python turtle library and I have a problem that confuses me a lot. I can work with turtle in real time, but when I write a program and I save it to a file, I can't run it. The code I have written follows below: from turtle import * turtle.Pen(9999999) penup() for i in range(16): write(i,align='center') forward(25) goto(0,-5) x=0 right(90) for i in range(16): pendown() forward(400) penup() x+=25 goto(x,-5) but it didn't work at all. It gave me this error: Traceback (most recent call last): File "C:\Users\Nobody\Desktop\main.py", line 3, in <module> turtle.Pen(9999999) NameError: name 'turtle' is not defined I think it doesn't import turtle at all.
score: 1
has answer: http://stackoverflow.com/a/51179460
type: Question
upvote count: 2
has answer: http://stackoverflow.com/a/51179538
has comment: http://stackoverflow.com/comment/89341373
has title: Python3 turtle save code to file
has comment: http://stackoverflow.com/comment/89352578
downvote count: 1
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89352228

http://stackoverflow.com/comment/89474094
type: Comment
comment on: http://stackoverflow.com/a/51247060
score: 3
has text: Always no reason , I really tired of downvote without reason : -(
type: AnswerComment

http://stackoverflow.com/q/51201122
tagged with: python
has comment: http://stackoverflow.com/comment/89383939
score: 0
has comment: http://stackoverflow.com/comment/89384532
has comment: http://stackoverflow.com/comment/89384290
type: Question
has title: min not working in python pivot_table
has comment: http://stackoverflow.com/comment/89384574
tagged with: pandas
answer count: 1
has answer: http://stackoverflow.com/a/56269491
has body: I have tried the following code: pivot = pd.pivot_table(pct, values=['CERT'], index=['ST'], aggfunc={'CERT': [min, max, np.mean]}) and received the following error: sort_values() got an unexpected keyword argument 'by' However, when I ran the following code and it worked: pivot = pd.pivot_table(pct, values=['CERT'], index=['ST'], aggfunc={'CERT': [max, np.mean]}) The only difference being I have removed the min function. I find this really puzzling and would appreciate any help. Thanks. Also, if anyone does know how to perform this analysis only on the states with two or more entries, that would also be helpful. Thanks.
has comment: http://stackoverflow.com/comment/89383920
tagged with: pivot-table
type: UnansweredQuestion

http://stackoverflow.com/a/51252186
has body: You have to first populate a list to use it's indices, change the foldx[i]=X[j:j+143,:] line to foldx.append(X[j:j+143,:]) Similarly for foldy foldy.append(y[foldx[j]])
accepted answer of: http://stackoverflow.com/q/51251845
type: Answer
has comment: http://stackoverflow.com/comment/89483620
answers question: http://stackoverflow.com/q/51251845
score: 0
type: AcceptedAnswer

http://stackoverflow.com/q/51303908
has comment: http://stackoverflow.com/comment/89585137
favorite count: 0
has comment: http://stackoverflow.com/comment/89584924
has answer: http://stackoverflow.com/a/51305275
upvote count: 2
type: AnsweredQuestion
score: 2
tagged with: filtering
has comment: http://stackoverflow.com/comment/89584868
has title: Python: Filtering numpy values based on certain columns
has comment: http://stackoverflow.com/comment/89584631
type: Question
tagged with: search
tagged with: numpy
answer count: 2
possible better answer: http://stackoverflow.com/a/51305275
downvote count: 0
has answer: http://stackoverflow.com/a/51304317
accepted answer: http://stackoverflow.com/a/51304317
has body: I'm trying to create a method for evaluating co-ordinates for a project that's due in about a week. Assuming that I'm working in a 3D cartesian co-ordinate system - whose values are stored as rows in a numpy array. I am trying to read if 'z' (n[i, 2]) values exist given the corresponding, predetermined 'x' (n[i,0]) and 'y' (n[i,1]) values. In the case where the values that are assigned are scalars, I am content to think that: # Given that n is some numpy array x, y = 2,3 out = [] for i in range(0,n.shape[0]): if n[i, 0] == x and n[i,1] == y: out.append(n[i,2]) However, where the sorrow comes in is having to check if the values in another numpy array are in the original numpy array 'n'. # Given that n is the numpy array that is to be searched # Given that x contains the 'search elements' out = [] for i in range(0,n.shape[0]): for j in range(0, x.shape[0]): if n[i, 0] == x[j,0] and n[i,1] == x[j,1]: out.append(n[i,2]) The issue with doing it this way is that the 'n' matrix in my application may well be in excess of 100 000 lines long. Is there a more efficient way of performing this function?
has comment: http://stackoverflow.com/comment/89585448
tagged with: python

http://stackoverflow.com/a/51197765
type: Answer
answers question: http://stackoverflow.com/q/51197551
has body: As you can see in python-shell documentation you can use pyshell.send() to send data to python stdin - that would not have the limitation.
score: 0

http://stackoverflow.com/comment/89345960
score: 0
has text: Do you have experience with C? If not, I can also look into writing something up for you on that front.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51176438

http://stackoverflow.com/comment/89420296
comment on: http://stackoverflow.com/q/51219660
has text: show your code as text
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51315922
has comment: http://stackoverflow.com/comment/89608742
score: 0
has answer: http://stackoverflow.com/a/51316021
tagged with: string
answer count: 5
type: UnansweredQuestion
tagged with: range
tagged with: python
has comment: http://stackoverflow.com/comment/89608532
has answer: http://stackoverflow.com/a/51316226
has answer: http://stackoverflow.com/a/51315984
has comment: http://stackoverflow.com/comment/89608553
type: Question
tagged with: indexing
has body: I´ve searched for other "string index out of range" cases, but they were not useful for me, so I wanted to search for help here. The program has to do this: "Write a function kth_word(s, k) that given a string s and an integer k≥ 1 returns the kth word in string s. If s has less than k words it returns the empty string. We assume all characters of s are letters and spaces. Warning: do not use the split string method." Here is my code: def kth_word(s, k): new ="" word_count = 0 for i in range(0, len(s)): if s[i] == " " and s[i+1] != " ": word_count+=1 #try to find how many characters to print until the space if word_count == k-1: while i!= " " and i&lt;=len(s): #if it is changed to i&lt;len(s), the output is strange and wrong new+=s[i] i=i+1 print(new) #check how new is doing, normally works good return new print(kth_word('Alea iacta est', 2)) (I tried my best to implement the code in a right way, but i do not know how) And depending on the place where you live return new it gives or an error or just an empty answer
has title: A "string index out if range" Python error
has comment: http://stackoverflow.com/comment/89608536
has answer: http://stackoverflow.com/a/51316290
has answer: http://stackoverflow.com/a/51316062

supervised-learning
type: Tag
tag name: supervised-learning
tags question: http://stackoverflow.com/q/51252324

http://stackoverflow.com/comment/89380149
type: Comment
has text: Almost, but I didnt want to order the A's by title, I want to order them by the top B.time's for each A
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51198753

http://stackoverflow.com/comment/89490387
comment on: http://stackoverflow.com/q/51255058
type: Comment
type: QuestionComment
score: 1
has text: Can you show me how you're running it (with an actual example that doesn't work.)

http://stackoverflow.com/q/51203760
downvote count: 0
favorite count: 0
tagged with: python-3.x
has title: Python: Storing a dictionary in more than one json file
has answer: http://stackoverflow.com/a/51204415
tagged with: python
tagged with: dictionary
has body: I have a dictionary like this: {'ahik': [2, 1, 3, 1, 4, 1, 5, 1], 'tyeo': [5, 4, 3, 5, 3, 3, 2], 'abc': [1, 2, 3, 4, 5, 2, 1]....} As the dictionary is very large I want to store it in two json file both having a part of the dictionary(lets say 50%). Also, How to retrieve it once I store it?
score: 1
upvote count: 1
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51204458
accepted answer: http://stackoverflow.com/a/51204415
possible better answer: http://stackoverflow.com/a/51204458
answer count: 2

http://stackoverflow.com/q/51194784
tagged with: pywin32
downvote count: 0
tagged with: windows-10
has answer: http://stackoverflow.com/a/51196240
accepted answer: http://stackoverflow.com/a/51196240
favorite count: 0
has answer: http://stackoverflow.com/a/68377574
has comment: http://stackoverflow.com/comment/89372740
tagged with: python
has title: How to debug a Python program running as a service?
score: 2
has comment: http://stackoverflow.com/comment/89371169
type: AnsweredQuestion
has body: I have a python script which works well when run in the console. However, when using pywin32 in order to let it run as a service, the service gets installed and starts okay but the desired output is not produced. So something must be going wrong -- but I can't see what's happening to find out the reason. The script does the following: Searches for *.csv files in a given input dir If no such files are found it waits 1 minute. If one is found it uses it as input for step 3. If multiple csv files are found it uses the first one. Does some transformation on the order of the columns Writes the transformed content into an output csv Moves the input csv into a subdirectory and renames it. Let me first show you the code of the version that is implemented as a service: #!/usr/bin/env python3 import sys import os import csv from pathlib import Path import time import win32service import win32serviceutil import win32event def reorder_AT_csv(ifile, ofile): "Öffnet die CSV Datei, überführt sie in das neue Format und exportiert sie." print('[i] Lese aus ' + ifile.name + ' und schreibe in ' + ofile.name) with open( ifile, mode='r') as infile, open( ofile, mode='w') as outfile: reader = csv.DictReader( infile, fieldnames=[ 'Post Nummer', 'Sendungsnummer', 'Referenz1', 'Referenz2', 'Gewicht', 'Empf.Name1', 'Empf.Adresse', 'Empf.PLZ', 'Empf.Ort', 'Kostenstelle', 'Produkt' ], delimiter=';') fn = [ 'Post Nummer', 'Referenz1', 'Referenz2', 'Sendungsnummer', 'Gewicht', 'Empf.Name1', 'Empf.Adresse', 'Empf.PLZ', 'Empf.Ort', 'Kostenstelle', 'Produkt' ] writer = csv.DictWriter( outfile, extrasaction='ignore', fieldnames=fn, delimiter=';') # reorder the header first try: for row in reader: # writes the reordered rows to the new file writer.writerow(row) except Exception as e: print('[!] Fehler bei der Bearbeitung der CSV Datei:') print('[!] ' + str(e)) print( '[!] Bitte ueberpruefen, ob es sich um eine korrekte CSV Datei handelt!' ) sys.exit(1) def checkInputFromUser(path): "Überprüfe ob das …
type: Question
upvote count: 2
answer count: 2
has comment: http://stackoverflow.com/comment/89372902
possible better answer: http://stackoverflow.com/a/68377574
has comment: http://stackoverflow.com/comment/89396145
has comment: http://stackoverflow.com/comment/89390170
has comment: http://stackoverflow.com/comment/89371486
has comment: http://stackoverflow.com/comment/89374543
linked to: http://stackoverflow.com/q/47008036
has comment: http://stackoverflow.com/comment/89373587

http://stackoverflow.com/comment/89504623
type: Comment
has text: @Mufeed how can we customize it? I mean can we pass the values without hardcoding them? For example, if I want to print RAJ by inputting it dynamically. how can i do that using this code?
comment on: http://stackoverflow.com/a/51221928
type: AnswerComment
score: 0

http://stackoverflow.com/q/51248297
has body: I wanted to share a value between the main and a class. How to do it? I am calling a class from main. This class executes a function and if it fails wanted to proceed with other functions. At the end, wanted to pass the status 'False' if any of the function fails and 'True' if all the functions have executed successfully. I wanted to pass the status back to main. I tried globals()[status] = True in class and def name = '__main': after calling the class methods. if globals()[status]: print 'all methods executed successfully.' Is it possible to share a variable between class and main? The globals didn't work for me.
score: -1
type: Question
has title: python - globals to access the variables between __main__ and class
answer count: 2
upvote count: 0
has comment: http://stackoverflow.com/comment/89475725
has comment: http://stackoverflow.com/comment/89475506
tagged with: class
tagged with: python-2.7
tagged with: python
favorite count: 0
has answer: http://stackoverflow.com/a/51249247
has answer: http://stackoverflow.com/a/51343533
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89476151
downvote count: 1

http://stackoverflow.com/q/51210773
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89403407
has comment: http://stackoverflow.com/comment/89402440
has comment: http://stackoverflow.com/comment/89402852
tagged with: fileoutputstream
has comment: http://stackoverflow.com/comment/89402301
has comment: http://stackoverflow.com/comment/89403113
type: Question
has title: Python3 - Class and simulation outputs in a txt. file
answer count: 2
has comment: http://stackoverflow.com/comment/89404269
downvote count: 0
has comment: http://stackoverflow.com/comment/89402255
linked to: http://stackoverflow.com/q/4675728
tagged with: class
has answer: http://stackoverflow.com/a/51211565
tagged with: simulation
favorite count: 0
has comment: http://stackoverflow.com/comment/89402269
accepted answer: http://stackoverflow.com/a/51211565
has body: I'm new working with Python3 and can't figure out how to save my outputs in a file. I know from other discussion that you can do: f = open(filename, 'w') print('whatever', file = f) but in my case the outputs I want to save are not written in a "print". As you can see below, I'm calling the class "TruieGest" in another file to run a simulation for my different animals (sows['ID']): def simulation(): for sows['ID'] in sows['ID']: SowGest = TruieGest(sows['ID'], sows['Age'], sows['Portee']) SowGest.data_lactation() return simulation simulation() sorties.close() Any idea on how i can get my outputs in a file ? Thanks !
upvote count: 2
possible better answer: http://stackoverflow.com/a/51210829
tagged with: file
has answer: http://stackoverflow.com/a/51210829
tagged with: python
has comment: http://stackoverflow.com/comment/89402258
score: 2

http://stackoverflow.com/a/51244162
has comment: http://stackoverflow.com/comment/89467356
has comment: http://stackoverflow.com/comment/89467944
score: 0
type: Answer
has body: How about trying to match 4 digit numbers at the end of line, on lines that doesn't contain date (that is line beginning with number)? import re re.findall(r'^[^\d].*?\s+(\d{4})\s*$', data, re.MULTILINE) # ['1234']
answers question: http://stackoverflow.com/q/51244034

http://stackoverflow.com/q/51222622
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/51222720
type: Question
accepted answer: http://stackoverflow.com/a/51222779
has answer: http://stackoverflow.com/a/51222779
score: 0
has answer: http://stackoverflow.com/a/51222720
has comment: http://stackoverflow.com/comment/89425743
upvote count: 1
downvote count: 1
tagged with: python
has title: Remove line from txt file if it endswith xyz
answer count: 4
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51222762
has answer: http://stackoverflow.com/a/51222978
has body: I am trying to write a python code to check each line in a .txt file and delete that line if it ends with A/ or Z/. This is what I have written, please help me take it forward. f = open('test.txt', 'r') for line in f.readlines(): if (line.endswith("A/") or line.endswith("Z/")): Remove that line in test.txt

pyopencl
tags question: http://stackoverflow.com/q/51238079
tag name: pyopencl
type: Tag

http://stackoverflow.com/a/51298329
type: Answer
upvote count: 4
has body: A list comprehension on the dict values will do: print({k + 'a': [i + 'b' for i in v] for k, v in mydict.items()}) This outputs: {'1a': ['4b', '3b', '8b'], '2a': ['3b', '7b', '5b']}
downvote count: 0
type: AcceptedAnswer
score: 4
accepted answer of: http://stackoverflow.com/q/51298258
answers question: http://stackoverflow.com/q/51298258

database
tags question: http://stackoverflow.com/q/51243386
tags question: http://stackoverflow.com/q/51191198
tags question: http://stackoverflow.com/q/51305905
tags question: http://stackoverflow.com/q/51306393
tags question: http://stackoverflow.com/q/51206480
tags question: http://stackoverflow.com/q/51213159
tags question: http://stackoverflow.com/q/51178941
tags question: http://stackoverflow.com/q/51244350
tags question: http://stackoverflow.com/q/51278841
tags question: http://stackoverflow.com/q/51289210
type: Tag
tags question: http://stackoverflow.com/q/51312891
tags question: http://stackoverflow.com/q/51205031
tags question: http://stackoverflow.com/q/51270810
tags question: http://stackoverflow.com/q/51254282
tags question: http://stackoverflow.com/q/51186723
tags question: http://stackoverflow.com/q/51278016
tag name: database
tags question: http://stackoverflow.com/q/51227403
tags question: http://stackoverflow.com/q/51194938
tags question: http://stackoverflow.com/q/51168210
tags question: http://stackoverflow.com/q/51286264
tags question: http://stackoverflow.com/q/51240265
tags question: http://stackoverflow.com/q/51205248
tags question: http://stackoverflow.com/q/51297271
tags question: http://stackoverflow.com/q/51318547
tags question: http://stackoverflow.com/q/51316973
tags question: http://stackoverflow.com/q/51270479
tags question: http://stackoverflow.com/q/51290513

http://stackoverflow.com/q/51300181
tagged with: flush
tagged with: python
linked to: http://stackoverflow.com/q/7127075
accepted answer: http://stackoverflow.com/a/51300280
type: AnsweredQuestion
has title: is it necessary to call flush method of file handler in python
tagged with: file
type: Question
score: 4
possible better answer: http://stackoverflow.com/a/51300256
has body: I saw a code where they were using file.flush(). so, i searched around and found This SO post. I kind of understood why there's a flush method. In the answer which was marked as answer the following was written Typically you don't need to bother with either method, but if you're in a scenario where paranoia about what actually ends up on disk is a good thing, you should make both calls as instructed. So, i was wondering, when we open a file using context manager and write some text, and then when the code exits from this context manager, there might be a chance that the text might not have been written to the file? if yes, why not python does this internally when file.close() is called? is it being done already?
has answer: http://stackoverflow.com/a/51300256
upvote count: 4
answer count: 2
has answer: http://stackoverflow.com/a/51300280
downvote count: 0
favorite count: 0

http://stackoverflow.com/comment/89444498
type: Comment
type: QuestionComment
score: 1
has text: That looks like a great start! What issue are you running into?
comment on: http://stackoverflow.com/q/51232692

http://stackoverflow.com/a/51284068
has body: From https://intellij-support.jetbrains.com/hc/en-us/community/posts/115000062344-How-to-move-complete-Python-environment-to-new-PC-with-virtual-environment Normally environments are tied to a specific path. That means that you cannot move an environment around or copy it to another computer. You can fix up an environment to make it relocatable with the command: $ virtualenv --relocatable ENV The --relocatable option currently has a number of issues, and is not guaranteed to work in all circumstances. It is possible that the option will be deprecated in a future version of virtualenv
upvote count: 2
accepted answer of: http://stackoverflow.com/q/51283494
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51283494
type: Answer
score: 2
downvote count: 0

http://stackoverflow.com/q/51203043
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/89387829
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/89390412
type: UnansweredQuestion
has title: Matplotlib commands not working
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/89389647
tagged with: python
has comment: http://stackoverflow.com/comment/89394331
has body: Whenever I run any matplotlib commands that plots/scatters a graph, it stops working, and the python console will run forever. If that line is in some script then the script runs forever. Even simple code like plt.plot([1,2,3,4]) doesn't work. The backend is also set as 'TkAgg' I'm using Ubuntu 16.04 and Python version is 3.5.2
score: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/89412355
has answer: http://stackoverflow.com/a/51223782

http://stackoverflow.com/comment/89525200
score: 0
type: Comment
has text: Simply disable the auto-reload feature with `./manage.py runserver --noreload`.
type: AnswerComment
comment on: http://stackoverflow.com/a/51251729

http://stackoverflow.com/a/65388955
answers question: http://stackoverflow.com/q/51320667
type: Answer
has body: if __name__ == '__main__': s = input() print (any([c.isalnum() for c in s])) print (any([c.isalpha() for c in s])) print (any([c.isdigit() for c in s])) print (any([c.islower() for c in s])) print (any([c.isupper() for c in s])) Use of the any keyword, checks all the letters of the alphabet and returns true I any one of the letter satisfies it.
score: 0

http://stackoverflow.com/comment/89912539
type: Comment
has text: @jason Complexity. `[0123456789]{8}` == `\d{8}` == `\d{7,}` == `\d{6,}` == `\d{5,}` == `\d{4,}` == `\d{3,}` == `\d{2,}` == `\d{,8}` == `\d{,9}` - all match strings of 8 digits. some better, some worse (`==` : matches ) - but if you want, try it.
type: AnswerComment
comment on: http://stackoverflow.com/a/51232917
score: 0

http://stackoverflow.com/q/51248994
upvote count: 1
has comment: http://stackoverflow.com/comment/89476899
downvote count: 1
type: Question
tagged with: method-signature
has body: I have a function: def report(start=1, quantity=100, days_left=7, min_app_version=None): I want to get argument names and default values, something like {'start':1, 'quantity':100, 'days_left':7, 'min_app_version':None} (or at least two lists) from outside this function when I do import inspect print(inspect.signature(report)) I get (*args, **kwargs) Why doesn't 'inspect.signature' see function arguments? SOLVED: THE PROBLEM WAS BECAUSE OF A DECORATOR
has comment: http://stackoverflow.com/comment/89476970
has comment: http://stackoverflow.com/comment/89477232
tagged with: inspect
score: 0
answer count: 2
possible better answer: http://stackoverflow.com/a/51249208
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89476916
has answer: http://stackoverflow.com/a/51249433
accepted answer: http://stackoverflow.com/a/51249433
tagged with: python
has comment: http://stackoverflow.com/comment/89477135
type: AnsweredQuestion
has title: Python 3.6 inspect.signature() doesn't show arguments
has answer: http://stackoverflow.com/a/51249208
linked to: http://stackoverflow.com/q/1166118

http://stackoverflow.com/comment/89640785
type: AnswerComment
type: Comment
has text: So your target is to make the code looking much nicer? Than you might have to add this also to your question ;-)
comment on: http://stackoverflow.com/a/51311197
score: 0

http://stackoverflow.com/a/51207862
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/51202202
score: 1
downvote count: 0
has body: The exception is raised because the variable player is a reference to the class Ball, and not an instance of it. Look at this line: player = Ball This does not create a new instance, since you don't call the class with (...). Other than that, if you use the Sprite class, better use it like intended. There's no point in storing the coordiantes in a x and y attribute in your classes when there's already the rect attribute. Also, you don't need a render method when there's already the Group class that does this for you. Here's an example where I changed your code to use the intended pygame features (shorted for brevity): import pygame class Ball(pygame.sprite.Sprite): def __init__(self, x, y): pygame.sprite.Sprite.__init__(self) image = pygame.image.load('basketball.png').convert_alpha() self.image = pygame.transform.scale(image, (100, 100)) self.rect = self.image.get_rect(topleft=(x,y)) self.speed_x = 5 self.speed_y = 5 self.mask = pygame.mask.from_surface(self.image) def update(self, screen_rect): self.rect.move_ip(self.speed_x, self.speed_y) self.rect.clamp_ip(screen_rect) def main(): # basics width = 1200 height = 722 pygame.init() screen = pygame.display.set_mode((width, height)) screen_rect = screen.get_rect() pygame.display.set_caption('Basketball Shootout') basketball = Ball(50, 50) stop_game = False sprites = pygame.sprite.Group(basketball) #main game logic while not stop_game: badtimer -= 1 for event in pygame.event.get(): pressed = pygame.key.get_pressed() if pressed[pygame.K_UP]: basketball.speed_y = -5 elif pressed[pygame.K_DOWN]: basketball.speed_y = 5 elif pressed[pygame.K_LEFT]: basketball.speed_x = -5 elif pressed[pygame.K_RIGHT]: basketball.speed_x = 5 if event.type == pygame.QUIT: stop_game = True screen.fill(pygame.color.THECOLORS['white']) sprites.update(screen_rect) sprites.draw(screen) pygame.display.update() pygame.quit() if __name__ == '__main__': main()

http://stackoverflow.com/comment/89474237
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51247670
has text: Perfect! Exactly the function I was missing! thanks a lot
score: 1

http://stackoverflow.com/comment/89522889
has text: There is a confusion in your question. how did you exactly arrive with error values corresponding to each of 20 observations for eg. `A_err`, `B_err` for `A`, `B` ??
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51254777

http://stackoverflow.com/comment/89549284
comment on: http://stackoverflow.com/a/51278197
has text: use skimage.io.imsave(pathtoimage)
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/51204913
favorite count: 0
has answer: http://stackoverflow.com/a/51206610
accepted answer: http://stackoverflow.com/a/51206610
has body: I can't seem to get the labels on the x-axis to rotate 90 degrees. Example df: import pandas as pd import matplotlib.pyplot as plt d = ({ 'A' : ['1','1','2','2','3','3','3'], 'B' : ['A','B','C','C','D','B','C'], 'C' : ['Foo','Bar','Foo','Bar','Cat','Bar','Cat'], }) df = pd.DataFrame(data=d) fig,ax = plt.subplots(figsize = (9,4)) df.assign(A=df.A.astype(int)).pivot_table(index="C", columns="B", values="A",aggfunc='count').rename_axis(None).rename_axis(None,1).plot(kind='bar') plt.show() I have tried the basic: plt.xticks(rotation = 90) Also tried this but it returns an Attribute Error: df.assign(A=df.A.astype(int)).pivot_table(index="C", columns="B", values="A",aggfunc='count').rename_axis(None).rename_axis(None,1).plot(kind='bar', rotation = 90) I have got the labels to rotate through this: xticklabels = df.C.unique() ax.set_xticklabels(xticklabels, rotation = 0) But it returns incorrect ordering. It just takes the values as they appear. Rather than determining the appropriate label
duplicate of: http://stackoverflow.com/q/10998621
score: 0
downvote count: 1
tagged with: xticks
linked to: http://stackoverflow.com/q/10998621
possible better answer: http://stackoverflow.com/a/51206705
has answer: http://stackoverflow.com/a/51206705
tagged with: python
has comment: http://stackoverflow.com/comment/89391767
type: AnsweredQuestion
has title: Rotation x-ticks matplotlib
tagged with: matplotlib
duplicate of: http://stackoverflow.com/q/32244019
type: Question
answer count: 2
upvote count: 1

http://stackoverflow.com/q/51302760
score: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/89610162
tagged with: django
upvote count: 1
tagged with: python
has title: SECURE_SSL_REDIRECT does nothing
tagged with: http
tagged with: https
has body: I have set SECURE_SSL_REDIRECT in my settings to True. If True, the SecurityMiddleware redirects all non-HTTPS requests to HTTPS (except for those URLs matching a regular expression listed in SECURE_REDIRECT_EXEMPT). I've also set PREPEND_WWW = True and BASE_URL = "https://www.******.com" My site is usually HTTPS: But I've purposely embedded a HTTP image in a page which has turned it to this: However when I go on that page, it doesn't redirect to HTTPS. Why is this and how can I fix it? PS: Here is my middleware if that matters: MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ]
answer count: 0
type: UnansweredQuestion
tagged with: security
downvote count: 0

http://stackoverflow.com/q/51254118
has comment: http://stackoverflow.com/comment/89487708
tagged with: python
has comment: http://stackoverflow.com/comment/89487253
has title: Using Tkinter to make a file chooser GUI to display both input and output file
has answer: http://stackoverflow.com/a/51291092
tagged with: tkinter
accepted answer: http://stackoverflow.com/a/51291092
tagged with: opencv
has comment: http://stackoverflow.com/comment/89487296
has comment: http://stackoverflow.com/comment/89487979
tagged with: image
score: 2
possible better answer: http://stackoverflow.com/a/51275277
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89488078
downvote count: 0
has answer: http://stackoverflow.com/a/51275277
has body: I am using python 3, opencv, and tkinter to create a GUI where I can upload an image and then display the image in a panel next to the final image which is the stacked version of all images in the same folder as the inputted image. The stacker() function simply stacks the images in the folder. For some reason, when running this program, the image that is supposed to be in the panelA is displaying, while the image from panelB is not. How can I display both images- the input and the output? Also is there any way to speed up this code? def select_image(): # grab a reference to the image panels global panelA, panelB # open a file chooser dialog and allow the user to select an input # image path = tkinter.filedialog.askopenfilename() # ensure a file path was selected if len(path) &gt; 0: # load the image from disk, convert it to grayscale, and detect # edges in it image = cv2.imread(path) edged = stacker(os.path.dirname(os.path.dirname(path))) # OpenCV represents images in BGR order; however PIL represents # images in RGB order, so we need to swap the channels image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) # convert the images to PIL format... image = Image.fromarray(image) edged = Image.fromarray(edged) # ...and then to ImageTk format image = ImageTk.PhotoImage(image) edged = ImageTk.PhotoImage(edged) # if the panels are None, initialize them if panelA is None or panelB is None: # the first panel will store our original image panelA = tk.Label(image=image) panelA.image = image panelA.pack(side="left", padx=10, pady=10) # while the second panel will store the edge map panelB = tk.Label(image=edged) panelB.image = edged panelB.pack(side="right", padx=10, pady=10) # otherwise, update the image panels else: # update the pannels panelA.configure(image=image) panelB.configure(image=edged) panelA.image = image panelB.image = edged # initialize the window toolkit along with the two image panels root = tk.Tk() panelA = None panelB = None print("done") # create a button, then whe…
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89487871
type: Question
upvote count: 2
answer count: 2

http://stackoverflow.com/comment/89437026
has text: Did you consider fixing the `/etc/sudoers` file with `visudo` to suppress the password prompt? Also, have you looked into `pexpect` instead of subprocess since pexpect is meant to deal with interactive CLI (https://stackoverflow.com/questions/39907546/how-to-perform-a-root-command-with-pexpect)?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51224674
score: 0

http://stackoverflow.com/comment/89443852
score: 0
type: Comment
type: AnswerComment
has text: Thank yuva but im not using copy command. Im using a python script in AWS GLue.
comment on: http://stackoverflow.com/a/51215278

http://stackoverflow.com/comment/89522602
score: 0
has text: Please have a minimal and complete example of your code, as well as the full text of your traceback. Without these, we don't have enough information to help you.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51271812

http://stackoverflow.com/q/51237770
has comment: http://stackoverflow.com/comment/89454544
tagged with: java
tagged with: http://stackoverflow.com/tag/json
has answer: http://stackoverflow.com/a/51296783
downvote count: 4
answer count: 2
accepted answer: http://stackoverflow.com/a/51296783
has title: Find Regex for Given Format that matches specific key value pair(s) in JSON
favorite count: 0
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/89454480
possible better answer: http://stackoverflow.com/a/51240412
has answer: http://stackoverflow.com/a/51240412
score: -3
upvote count: 1
has body: '{"id":1,"last":"Doe","first":"John","location":{"city":"Oakland","state":"CA","postalCode":"94607"},"active":true}', '{"id":2,"last":"Doe","first":"Jane","location":{"city":"San Francisco","state":"WA","postalCode":"94105"},"active":false}', '{"id":3,"last":"Doe","first":"Jane","location":{"city":"San Francisco","state":"CA","postalCode":"94105"},"active":true}' I am looking for getting json contain which includes '{"id":1}'. OR I am looking for getting json contain which includes '{"location":{"state":"CA"},"active":true}' Likewise... So for '{"id":1}' it should return {{"id":1,"last":"Doe","first":"John","location":{"city":"Oakland","state":"CA","postalCode":"94607"},"active":true} and for '{"location":{"state":"CA"},"active":true}' it should return {"id":1,"last":"Doe","first":"John","location":{"city":"Oakland","state":"CA","postalCode":"94607"},"active":true} {"id":3,"last":"Doe","first":"Jane","location":{"city":"San Francisco","state":"CA","postalCode":"94105"},"active":true}
type: Question
type: AnsweredQuestion

http://stackoverflow.com/a/51197682
type: Answer
answers question: http://stackoverflow.com/q/51193819
has body: This is not the ideal way to do this but you said you are not a programmer. So, I believe this method will be the easiest for you to work with both now, and in the future. payload = "{\"name\":\"madefrompostman\",\"description\":\"\",\"context\":\"\",\"status\":-1,\"createdTime\":0,\"modifiedTime\":0,\"groups\":[],\"repository\":{\"id\":233},\"schedule\":{\"start\":\"TZID=America/New_York:20180705T083000\",\"repeatRule\":\"FREQ=TEMPLATE;INTERVAL=1\",\"type\":\"template\"},\"dhcpTracking\":\"true\",\"emailOnLaunch\":\"false\",\"emailOnFinish\":\"false\",\"reports\":[],\"type\":\"policy\",\"policy\":{\"id\":1002387},\"zone\":{\"id\":-1},\"timeoutAction\":\"import\",\"rolloverType\":\"template\",\"scanningVirtualHosts\":\"false\",\"classifyMitigatedAge\":365,\"assets\":[],\"ipList\":\"" payload += IPs payload += ",\"credentials\":[],\"maxScanTime\":\"unlimited\"}" What's happening: The payload object starts as the beginning of your string. Then your IPs variable is concatenated(attached). Then the end of the string is concatenated. A shorter and probably better way of writing this is payload = "Beginning of string" + IPs + "end of string."
score: 0

http://stackoverflow.com/a/51302666
downvote count: 0
has body: I think the error is pretty clear, but there are ways to avoid it. 1/ You could convert the NetCDF files from NetCDF4 to the classic format using e.g. nccopy: nccopy -k classic nc4_file.nc ncclassic_file.nc 2/ xarray has a similar method (called open_mfdataset) which is able to handle NetCDF4 files. A quick test: import netCDF4 as nc4 test = nc4.MFDataset(['test0.nc','test1.nc']) This gives me the same error as you get ("MFNetCDF4 only works with..."), the same with xarray works without any problems: import xarray as xr test = xr.open_mfdataset(['test0.nc', 'test1.nc'])
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51290858
type: Answer
answers question: http://stackoverflow.com/q/51290858
score: 4
upvote count: 4

http://stackoverflow.com/q/51313190
downvote count: 1
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/51313563
has answer: http://stackoverflow.com/a/51313782
accepted answer: http://stackoverflow.com/a/51313782
has comment: http://stackoverflow.com/comment/89603664
tagged with: nodes
type: Question
answer count: 2
tagged with: binary-tree
tagged with: class
has answer: http://stackoverflow.com/a/51313563
score: 0
has comment: http://stackoverflow.com/comment/89603260
has title: How do I traverse binary tree made up of nodes? (code inside)
favorite count: 0
has body: I am given a class that creates a binary tree filled with nodes.each node is given a parent and a pointer to its left or right child. Binary tree node class: class BTNode(): ''' a class that represents a binary tree node''' def __init__(self, data, parent=None, left_child=None, right_child=None): '''(BTNode, obj, BTNode, BTNode, BTNode) -&gt; NoneType Constructs a binary tree nodes with the given data''' self._parent = parent self._left = left_child self._data = data self._right = right_child def set_parent(self, parent): '''(BTNode, BTNode) -&gt; NoneType set the parent to the given node''' self._parent = parent def set_left(self, left_child): '''(BTNode, BTNode) -&gt; NoneType set the left child to the given node''' self._left = left_child def set_right(self, right_child): '''(BTNode, BTNode) -&gt; NoneType set the right child to the given node''' self._right = right_child def set_data(self, data): '''(BTNode, obj) -&gt; NoneType set the data at this node to the given data''' self._data = data def get_parent(self): '''(BTNode) -&gt; BTNode return the pointer to the parent of this node''' return self._parent def get_left(self): '''(BTNode) -&gt; BTNode return the pointer to the left child''' return self._left def get_right(self): '''(BTNode) -&gt; BTNode return the pointer to the right child''' return self._right def get_data(self): '''(BTNode) -&gt; obj return the data stored in this node''' return self._data def has_left(self): '''(BTNode) -&gt; bool returns true if this node has a left child''' return (self.get_left() is not None) def has_right(self): '''(BTNode) -&gt; bool returns true if this node has a right child''' return (self.get_right() is not None) def is_left(self): '''(BTNode) -&gt; bool returns true if this node is a left child of its parent''' # you need to take care of exception here, if the given node has not parent return (self.get_parent().get_left() is self) def is_right(self): '''(BTNode) -&gt; bool returns true if the given node is a right ch…
upvote count: 1
tagged with: python

http://stackoverflow.com/comment/89447954
type: Comment
type: QuestionComment
score: 0
has text: @ForceBru Thanks. I'm not able to use Python 3 unfortunately.
comment on: http://stackoverflow.com/q/51234380

http://stackoverflow.com/q/51269043
has comment: http://stackoverflow.com/comment/89517620
answer count: 1
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89517469
score: 2
has answer: http://stackoverflow.com/a/51327179
has body: I'm trying to do my first database migration with this tutorial. The difference is that the writer start from scratch whereas I already have a MySQL database. Yet, as the writer did in his tutorial, I wrote the new database models inapp/models.py: from app import db class User(db.Model): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(64), index=True, unique=True) email = db.Column(db.String(120), index=True, unique=True) password_hash = db.Column(db.String(128)) def __repr__(self): return '&lt;User {}&gt;'.format(self.username) It will include the users table that maps to the User database model of a Flask application. I was worried that the database migration script was empty and that the flask db migrate commands didn't seemed to create a database. I therfore tried to play with it using the interpreter : &gt;&gt;&gt; from app import db &gt;&gt;&gt; from app.models import User, Post &gt;&gt;&gt; u = User(username='john', email='john@example.com') &gt;&gt;&gt; db.session.add(u) &gt;&gt;&gt; db.session.commit() Traceback (most recent call last): File "/home/mike/.local/lib/python3.6/site-packages/sqlalchemy/engine/base.py", line 1193, in _execute_context context) File "/home/mike/.local/lib/python3.6/site-packages/sqlalchemy/engine/default.py", line 509, in do_execute cursor.execute(statement, parameters) sqlite3.OperationalError: no such table: user The above exception was the direct cause of the following exception: Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/home/mike/.local/lib/python3.6/site-packages/sqlalchemy/orm/scoping.py", line 153, in do return getattr(self.registry(), name)(*args, **kwargs) File "/home/mike/.local/lib/python3.6/site-packages/sqlalchemy/orm/session.py", line 943, in commit self.transaction.commit() ... ... File "/home/mike/.local/lib/python3.6/site-packages/sqlalchemy/engine/default.py", line 509, in do_execute cursor.execute(statement, parameters) sqlalchemy.exc.Op…
upvote count: 2
has title: Unable to create table from model with sqlalchemy and sqlite
tagged with: sqlalchemy
type: Question
has comment: http://stackoverflow.com/comment/89557437
has comment: http://stackoverflow.com/comment/89520451

http://stackoverflow.com/q/51280988
type: Question
has body: I Have infinite loop that read bytes from serial port, I want to save the read data to firebase database every X seconds. I used this code snippet but it's not helping: import threading def printit(): threading.Timer(5.0, printit).start() print "Hello, World!" printit() This is my code import serial ser = serial.Serial() ser.baudrate = 115200 ser.port = "/dev/ttyUSB0" ser.timeout = 30 try: try: while 1: line = ser.readline().rstrip().decode('utf-8') # print("save data here every X seconds) except KeyboardInterrupt: ser.close() # Close port pass except serial.serialutil.SerialException as e: print(str(e)) I can't use sleep because it blocking the main thread,So how to let the code read continuously and print "data saved" every X seconds (I'll save to database in my case)
linked to: http://stackoverflow.com/q/92928
linked to: http://stackoverflow.com/q/17553543
has title: run code every X seconds
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/51310092
tagged with: python-3.x
tagged with: python-multithreading
tagged with: python
possible better answer: http://stackoverflow.com/a/51282532
has answer: http://stackoverflow.com/a/51282532
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89539294
accepted answer: http://stackoverflow.com/a/51310092
has comment: http://stackoverflow.com/comment/89540937

http://stackoverflow.com/comment/89372744
type: QuestionComment
has text: Fixed by setting pip.conf correctly. Has to be in ~/Library/Application Support/pip I had it in /Library [global] trusted-host = pypi.python.org pypi.org files.pythonhosted.org
score: 1
comment on: http://stackoverflow.com/q/51193759
type: Comment

http://stackoverflow.com/a/51310735
has comment: http://stackoverflow.com/comment/89601895
downvote count: 0
has comment: http://stackoverflow.com/comment/89599909
has comment: http://stackoverflow.com/comment/89602524
has comment: http://stackoverflow.com/comment/89600292
has comment: http://stackoverflow.com/comment/89600352
type: Answer
has body: Modifying your function a little: def seq_duration(row): Duration = None if row.ClipFirstFrameNumber is not None and row.ClipLastFrameNumber is not None: fn = row.ClipLastFrameNumber -row.ClipFirstFrameNumber fps = 0 if row.FrameRate =='23.98' and row.DropFrame == 'False' : fps = 24 / 1.001 elif row.FrameRate == '24' and row.DropFrame == 'False': fps = 24 elif row.FrameRate == '25'and row.DropFrame == 'False': fps = 25 elif row.FrameRate == '29.97': fps = 30 / 1.001 elif row.FrameRate == '30' and row.DropFrame == 'False': fps = 30 elif row.FrameRate == '59.94': fps = 60 / 1.001 if fps&gt;0: Duration = fn/fps elif row.srcDuration is not None: Duration = row.srcDuration return Duration Then you want: df['seg_duration']=df.apply(seq_duration,axis = 1)
accepted answer of: http://stackoverflow.com/q/51310636
has comment: http://stackoverflow.com/comment/89600128
has comment: http://stackoverflow.com/comment/89598753
has comment: http://stackoverflow.com/comment/89602511
answers question: http://stackoverflow.com/q/51310636
upvote count: 1
has comment: http://stackoverflow.com/comment/89601573
has comment: http://stackoverflow.com/comment/89602079
score: 1
has comment: http://stackoverflow.com/comment/89598787
has comment: http://stackoverflow.com/comment/89600183
type: AcceptedAnswer

pid
tags question: http://stackoverflow.com/q/51217300
tag name: pid
type: Tag

http://stackoverflow.com/q/51255592
answer count: 2
has answer: http://stackoverflow.com/a/51255648
has comment: http://stackoverflow.com/comment/89490252
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51255610
tagged with: python
has comment: http://stackoverflow.com/comment/89490343
tagged with: timeit
has title: Timeit showing that regular python is faster than numpy?
tagged with: performance
has comment: http://stackoverflow.com/comment/89499558
has comment: http://stackoverflow.com/comment/89490342
has comment: http://stackoverflow.com/comment/89490375
type: Question
tagged with: numpy
linked to: http://stackoverflow.com/q/15026519
has body: I'm working on a piece of code for a game that calculates the distances between all the objects on the screen using their in-game coordinate positions. Originally I was going to use basic Python and lists to do this, but since the number of distances that will need calculated will increase exponentially with the number of objects, I thought it might be faster to do it with numpy. I'm not very familiar with numpy, and I've been experimenting on basic bits of code with it. I wrote a little bit of code to time how long it takes for the same function to complete a calculation in numpy and in regular Python, and numpy seems to consistently take a good bit more time than the regular python. The function is very simple. It starts with 1.1 and then increments 200,000 times, adding 0.1 to the last value and then finding the square root of the new value. It's not what I'll actually be doing in the game code, which will involve finding total distance vectors from position coordinates; it's just a quick test I threw together. I already read here that the initialization of arrays takes more time in NumPy, so I moved the initializations of both the numpy and python arrays outside their functions, but Python is still faster than numpy. Here is the bit of code: #!/usr/bin/python3 import numpy from timeit import timeit #from time import process_time as timer import math thing = numpy.array([1.1,0.0], dtype='float') thing2 = [1.1,0.0] def NPFunc(): for x in range(1,200000): thing[0] += 0.1 thing[1] = numpy.sqrt(thing[0]) print(thing) return None def PyFunc(): for x in range(1,200000): thing2[0] += 0.1 thing2[1] = math.sqrt(thing2[0]) print(thing2) return None print(timeit(NPFunc, number=1)) print(timeit(PyFunc, number=1)) It gives this result, which indicates normal Python is 3x faster: [ 20000.99999999 141.42489173] 0.2917748889885843 [20000.99999998944, 141.42489172698504] 0.10341173503547907 Am I doing something wrong, is is this calculation just so simple that it isn't a good tes…
score: 0

pip
tags question: http://stackoverflow.com/q/51228228
tags question: http://stackoverflow.com/q/51272437
tags question: http://stackoverflow.com/q/51226976
tags question: http://stackoverflow.com/q/51287636
tags question: http://stackoverflow.com/q/51180548
tags question: http://stackoverflow.com/q/51267610
tags question: http://stackoverflow.com/q/51245648
tags question: http://stackoverflow.com/q/51283708
tags question: http://stackoverflow.com/q/51319189
tags question: http://stackoverflow.com/q/51252030
tags question: http://stackoverflow.com/q/51174655
tags question: http://stackoverflow.com/q/51228764
tags question: http://stackoverflow.com/q/51223407
tags question: http://stackoverflow.com/q/51269053
tags question: http://stackoverflow.com/q/51274999
tags question: http://stackoverflow.com/q/51242622
tags question: http://stackoverflow.com/q/51247419
tags question: http://stackoverflow.com/q/51269959
tags question: http://stackoverflow.com/q/51201459
tags question: http://stackoverflow.com/q/51201515
tags question: http://stackoverflow.com/q/51239146
tags question: http://stackoverflow.com/q/51296770
tags question: http://stackoverflow.com/q/51264172
tags question: http://stackoverflow.com/q/51294268
tag name: pip
tags question: http://stackoverflow.com/q/51304892
tags question: http://stackoverflow.com/q/51277895
tags question: http://stackoverflow.com/q/51193759
tags question: http://stackoverflow.com/q/51187719
tags question: http://stackoverflow.com/q/51245252
tags question: http://stackoverflow.com/q/51264020
tags question: http://stackoverflow.com/q/51192688
tags question: http://stackoverflow.com/q/51172789
tags question: http://stackoverflow.com/q/51236061
tags question: http://stackoverflow.com/q/51222237
tags question: http://stackoverflow.com/q/51275354
tags question: http://stackoverflow.com/q/51254627
tags question: http://stackoverflow.com/q/51231688
tags question: http://stackoverflow.com/q/51221840
tags question: http://stackoverflow.com/q/51196467
tags question: http://stackoverflow.com/q/51319551
tags question: http://stackoverflow.com/q/51270197
tags question: http://stackoverflow.com/q/51273748
tags question: http://stackoverflow.com/q/51272998
tags question: http://stackoverflow.com/q/51221836
tags question: http://stackoverflow.com/q/51210505
tags question: http://stackoverflow.com/q/51322205
tags question: http://stackoverflow.com/q/51189784
tags question: http://stackoverflow.com/q/51225153
type: Tag
tags question: http://stackoverflow.com/q/51273969
tags question: http://stackoverflow.com/q/51197475
tags question: http://stackoverflow.com/q/51306780
tags question: http://stackoverflow.com/q/51282215
tags question: http://stackoverflow.com/q/51249846
tags question: http://stackoverflow.com/q/51292729
tags question: http://stackoverflow.com/q/51256737
tags question: http://stackoverflow.com/q/51296179
tags question: http://stackoverflow.com/q/51234485
tags question: http://stackoverflow.com/q/51221846
tags question: http://stackoverflow.com/q/51219293
tags question: http://stackoverflow.com/q/51276985
tags question: http://stackoverflow.com/q/51182382
tags question: http://stackoverflow.com/q/51205924
tags question: http://stackoverflow.com/q/51207770
tags question: http://stackoverflow.com/q/51222918
tags question: http://stackoverflow.com/q/51282539

http://stackoverflow.com/comment/89340688
type: QuestionComment
comment on: http://stackoverflow.com/q/51178853
score: 0
has text: pylab is not recommended to be used anymore, I edited your question accordingly.
type: Comment

http://stackoverflow.com/comment/111059249
comment on: http://stackoverflow.com/q/51210305
type: Comment
type: QuestionComment
has text: @DaveTheAl did you ever resolve the issue with the hang? I believe I've run into the same issue.
score: 1

http://stackoverflow.com/a/51320636
score: 14
has comment: http://stackoverflow.com/comment/89621992
upvote count: 14
accepted answer of: http://stackoverflow.com/q/51320590
answers question: http://stackoverflow.com/q/51320590
type: AcceptedAnswer
has body: You can do this with for example an {% if ... %} tag: {% for player in players %} &lt;tr&gt; &lt;td&gt; &lt;input type="checkbox" name="player_check"{% if player.player_check %} checked{% endif %}&gt; &lt;/td&gt; &lt;/tr&gt; {% endfor %} But I think you better use Django forms, which will handle this in a more elegant way for you: you specify the form field, and Django will handle the rest.
type: Answer
has comment: http://stackoverflow.com/comment/89617366
downvote count: 0

http://stackoverflow.com/q/51216219
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/89416076
linked to: http://stackoverflow.com/q/17245415
type: Question
linked to: http://stackoverflow.com/q/18219398
has answer: http://stackoverflow.com/a/51261058
accepted answer: http://stackoverflow.com/a/51261058
linked to: http://stackoverflow.com/q/28223242
favorite count: 0
has comment: http://stackoverflow.com/comment/89414393
has comment: http://stackoverflow.com/comment/89449639
has answer: http://stackoverflow.com/a/51242196
has title: Valid JSON Load in Python file
tagged with: python-2.7
score: 0
has comment: http://stackoverflow.com/comment/89637761
possible better answer: http://stackoverflow.com/a/51292836
has comment: http://stackoverflow.com/comment/89414280
has comment: http://stackoverflow.com/comment/89416381
has comment: http://stackoverflow.com/comment/89415438
has answer: http://stackoverflow.com/a/51292836
has comment: http://stackoverflow.com/comment/89415864
tagged with: python
upvote count: 4
has comment: http://stackoverflow.com/comment/89415308
has comment: http://stackoverflow.com/comment/89415584
has comment: http://stackoverflow.com/comment/89416285
answer count: 4
downvote count: 4
has comment: http://stackoverflow.com/comment/89414326
has comment: http://stackoverflow.com/comment/89413728
has body: Running into a problem with my JSON: First issue was that SyntaxError: Non-ASCII character '\xe2' in file so I added # -*- coding: utf-8 -*- at the top of my file. Then the problem became a problem where I load my JSON x = json.loads(x): ValueError: Expecting , delimiter: line 3 column 52 (char 57). I referenced this stackoverflow solution and so added an r in front of my JSON: x = r"""[ { my validated json... } ]""" But then I get an error TypeError: sequence item 3: expected string or Unicode, NoneType found - I think it that the r is throwing it off somehow? JSON Resembles the following: [ { "brief": "Brief 1", "description": "Description 1", "photos": [ "https://cdn.shopify.com/s/files/1/01/01/01/files/imgs-example.jpg?0101010101010", "https://cdn.shopify.com/s/files/1/01/01/01/files/imgs-example2.jpg?0101010101010", "https://cdn.shopify.com/s/files/1/01/01/01/files/imgs-example3.jpg?0101010101010" ], "price": "145", "tags": [ "tag1", "tag2", "tag3" ], "title": "Title 1" }, { "brief": "Brief 2", "description": "Description 2", "photos": [ "https://cdn.shopify.com/s/files/1/01/01/01/files/imgs-example4.jpg?0101010101010", "https://cdn.shopify.com/s/files/1/01/01/01/files/imgs-example5.jpg?0101010101010" ], "price": "150", "tags": [ "tag4", "tag5", "tag6", "tag7", "tag8" ], "title": "Title 2" },{ "brief": "blah blah 5'0\" to 5'4\"", "buyerPickup": true, "condition": "Good", "coverShipping": false, "description": "blah blah 5'0\" to 5'4\". blah blah.Size L/20”\n 5’8-5’11\n29lbs\n3x7 speed\n\n \r\n\r\n", "photos": [ "https://cdn.shopify.com/s/files/1/01/01/01/files/imgs-010101.jpeg?11111", "https://cdn.shopify.com/s/files/1/01/01/01/files/imgs-020202?111111" ], "price": "240", "tags": [ "tag2", "5'0\"-5'4\"" ], "title": "blah blah 17\" Frame", "front": "https://firebasestorage.googleapis.com/v0/b/example.appspot.com/o/Images%2F0007891113.jpg?alt=media&amp;token=111-11-11-11-111" } ] CURRENT CODE # -*- coding: utf-8 -*- import csv import json x = """[ { "brief": "Bri…
has comment: http://stackoverflow.com/comment/89415283
has comment: http://stackoverflow.com/comment/89415713
has answer: http://stackoverflow.com/a/51350621
has comment: http://stackoverflow.com/comment/89413648
has comment: http://stackoverflow.com/comment/89415786
has comment: http://stackoverflow.com/comment/89416456
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89414350

http://stackoverflow.com/a/51307789
accepted answer of: http://stackoverflow.com/q/51307482
has body: You are missing a return on this line in the floor function: self.floor(root.leftnode, key)
type: Answer
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/51307482
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/51948979
accepted answer of: http://stackoverflow.com/q/51301354
has comment: http://stackoverflow.com/comment/90907834
type: Answer
answers question: http://stackoverflow.com/q/51301354
has comment: http://stackoverflow.com/comment/90920986
score: 0
has comment: http://stackoverflow.com/comment/90885029
has body: Okay, you can use cumcount and unstack: df_out = df.set_index(['CardCode',df.groupby('CardCode').cumcount() + 1])\ .unstack()\ .sort_index(level=1, axis=1) df_out.columns = [f'{i}_{j}' for i,j in df_out.columns] df_out = df_out.reset_index() df_out Output: CardCode Coupon_1 ShopName_1 TranDate_1 Coupon_2 ShopName_2 TranDate_2 Coupon_3 ShopName_3 TranDate_3 0 1028670151 S ShopA 2018-05-24 21:02:19.000 S ShopB 2018-05-23 13:14:44.000 G ShopC 2018-05-24 12:31:24.000 1 1029282454 S ShopA 2018-05-19 19:52:40.000 G ShopB 2018-05-19 14:08:02.000 NaN NaN NaN 2 1029646050 S ShopD 2018-06-17 14:10:42.000 NaN NaN NaN NaN NaN NaN 3 1029684151 S ShopE 2018-05-05 12:33:21.000 G ShopB 2018-05-05 15:13:08.000 S ShopC 2018-05-06 14:21:02.000 4 1029754252 G ShopA 2018-05-05 10:40:30.000 NaN NaN NaN NaN NaN NaN
has comment: http://stackoverflow.com/comment/90881124
type: AcceptedAnswer

http://stackoverflow.com/q/51249479
answer count: 3
possible better answer: http://stackoverflow.com/a/51249645
accepted answer: http://stackoverflow.com/a/51249652
favorite count: 0
has comment: http://stackoverflow.com/comment/89477883
has comment: http://stackoverflow.com/comment/89477990
has body: I have a text file with an unknown amount of numbers included. My program reads in the values and calculates the minimum value, the maximum value, the range and the median. The last thing that I have to do is find the mode of the set. I have a sorted list that I am iterating through with a loop in order to place all of the numbers in a dictionary where the key is the number and the value for each number is how many times the number occurs. I understand how to do all of that, but now I need to output the mode of the set. num_count = {} for num in num_list: if num in num_count: num_count[num] += 1 if num not in num_count: num_count[num] = 1 The above code is what places all of the numbers in the dictionary from the list and gives them the corresponding value with how many times that number occurs in the file, so now I just need to output the mode in a fashion such as [mode_1, mode_2, mode_3, etc..], but I can only get one number to appear. I have a text file where the mode should output as: Mode: [660, 476] However, the code I have outputs as: Mode: 660 Mode: 476 This is what I have so far: maximum = 0 for num in num_count: count = num_count[num] if count &gt; maximum: maximum = count if count == maximum: print('Mode: ', num) Using a dictionary seems like the easiest way to go about this. Any help would be greatly appreciated. Basic python loop would be best, without imported things like counter and such.
has comment: http://stackoverflow.com/comment/89478244
tagged with: python
has answer: http://stackoverflow.com/a/51249652
tagged with: dictionary
has comment: http://stackoverflow.com/comment/89477863
type: AnsweredQuestion
tagged with: list
downvote count: 0
has title: Python: Use a dictionary to output the mode of a text file
has answer: http://stackoverflow.com/a/51249645
has comment: http://stackoverflow.com/comment/89477949
type: Question
score: 3
has answer: http://stackoverflow.com/a/74415858
upvote count: 3

http://stackoverflow.com/a/51232248
has comment: http://stackoverflow.com/comment/89443981
has body: I shortened your arrays: a = np.random.exponential(1, [10, 100]) # of shape (10, 100) b = np.random.exponential(1, [10, 100]) ind=np.argmax(a,axis=0) Use that ind to select one row per column in a and b: a_ = a[ind,np.arange(a.shape[1])] b_ = b[ind,np.arange(a.shape[1])] And then calculate c: c=np.minimum(a_, b_)
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89444194
has comment: http://stackoverflow.com/comment/89444063
type: Answer
accepted answer of: http://stackoverflow.com/q/51232019
has comment: http://stackoverflow.com/comment/89444337
answers question: http://stackoverflow.com/q/51232019
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/89444094

http://stackoverflow.com/comment/89506924
has text: @ted my labels and logits looks like same as i describe above , there logits shape is [5,3] and labels shape is also [5,3 ] (one hot )
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51264291
score: 0

http://stackoverflow.com/q/51201640
score: 2
tagged with: python-3.x
answer count: 0
downvote count: 0
has comment: http://stackoverflow.com/comment/89384637
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89384846
type: Question
has title: How to Make Reusable Functions in Python
upvote count: 2
has body: I am new to programming, and to Python. I have written a simple random quote generator which loads various categories of quotes as lists into a dictionary. It then randomly chooses a list and then a specific quote from the list and outputs it to the screen. It is mostly complete but I am looking for ways to clean up the code to make it more efficient. Right now I have a set of 14 different categories that the user can select from to populate the dictionary. Each one of those category selections calls a function to update the dictionary and the config.ini file to save the user preferences. That results in hundreds of lines of near-identical code, where the only differences are the specific category and files in use. I am looking for a way to rewrite it so that the same function can be reused each time and simply pass in the correct information to make it work. I have posted snippets of the relevant code below. I am using Python 3.6 and TKinter. Thank you for any help you can provide. Adversity check button to call update_adversity function and add/remove adversity category quotes to/from the dictionary self.adversity = BooleanVar() self.adv = Checkbutton(self, text = 'Adversity/Hardship', variable = self.adversity, command = self.update_adversity) self.adv.grid(row = 1, column = 0, sticky = 'W', padx = 0, pady = 0) if 'adversity' in quotes: self.adversity.set(1) elif 'adversity' not in quotes: self.adversity.set(0) add/remove adversity list in dictionary based on checkbutton value def update_adversity(self): if self.adversity.get() == True: config.set('categories', 'adversity', 'True') # updates config file with open('adversity.py', 'r', encoding = 'UTF8') as f: new_quotes_added = f.readlines() quotes['adversity'] = new_quotes_added try: del quotes['default'] config.set('categories', 'default', 'False') # updates config file return quotes except: return quotes elif self.adversity.get() == False: config.set('categories', 'adversity', 'False') # updates config file try…
favorite count: 0
tagged with: python

http://stackoverflow.com/comment/89361825
comment on: http://stackoverflow.com/a/51190122
type: Comment
score: 0
type: AnswerComment
has text: you can try this code and you will get o/p as you wanted

http://stackoverflow.com/q/51224997
has title: Type annotation for function returning a lambda
tagged with: python
has answer: http://stackoverflow.com/a/51225097
tagged with: python-typing
type: AnsweredQuestion
upvote count: 14
has body: I’m very fond of the idea of using type annotations in Python. I know how to do such like in this simple example: def foo(bar : int, lol : int) -&gt; int: return bar*lol But I have no clue of how to do so when my function is going to return a lambda: def line(slope : float, b : float) -&gt; lambda: return lambda x: slope*x + b This example generates an error, and I wonder what’s the keyword I’m supposed to use for this return type. Perhaps this doesn’t seem so useful but I want to keep my code consistently annotated and being unable to do so with these type of functions is really bothering me. Thanks in advance.
type: Question
score: 14
accepted answer: http://stackoverflow.com/a/51225097
has comment: http://stackoverflow.com/comment/89430460
linked to: http://stackoverflow.com/q/37835179
downvote count: 0
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/138899412

http://stackoverflow.com/q/51170799
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89324706
tagged with: http://stackoverflow.com/tag/json
type: Question
has comment: http://stackoverflow.com/comment/89324467
has comment: http://stackoverflow.com/comment/89324531
tagged with: gitlab-ci
score: 0
has comment: http://stackoverflow.com/comment/89324655
has body: Hey guys the task I have at hand is to write a python program that checks a Gitlab CI pipeline's status and the runner it's using and to print them out. It is pretty much my first attempt at python so my mistake might be extremely trivial but those are also often that most difficult issues to troubleshoot so I'd be glad if someone can point out what I've done incorrectly. import requests import subprocess import json res = requests.get('https://git.censored.com/censored/Test33004__half/pipelines') json_data = json.loads(res.text) if element['status'] == "active" print element['status'] print element['runner'] else print element['status']
tagged with: python
answer count: 0
has title: Display gitlab-ci pipeline status and runner not really displaying anything

http://stackoverflow.com/q/51261968
has title: Combining several columns with pandas
tagged with: pandas
tagged with: python
has answer: http://stackoverflow.com/a/51262609
accepted answer: http://stackoverflow.com/a/51262609
tagged with: python-3.x
downvote count: 0
has answer: http://stackoverflow.com/a/51262165
score: 2
type: AnsweredQuestion
type: Question
upvote count: 2
answer count: 2
has body: I have a pandas dataframe: Name A1 A2 A3 Andy 1 NaN NaN Brian Nan NaN NaN Carlos NaN 2 NaN David NaN Nan 3 Frank 2 Nan Nan For each row, in 3 columns A1, A2 and A3 there is at most one non-NaN cell. So I want to merge them into one column and remove the rows that are all NaN. So the above dataframe will become: Name A A-ID Andy 1 1 Carlos 2 2 David 3 3 Frank 2 1 A-ID will store the original column (A1, A2 or A3). The row with Brian is removed because all 3 columns are NaN. Naively I can write a for loop to do the task, but is there a more pythonic and faster way?
possible better answer: http://stackoverflow.com/a/51262165
favorite count: 0

http://stackoverflow.com/q/51223647
tagged with: pyqt
answer count: 1
tagged with: python
has title: How can I elegantly prevent QThread from being destroyed or garbage collected?
accepted answer: http://stackoverflow.com/a/51223908
type: AnsweredQuestion
tagged with: pyqt5
has answer: http://stackoverflow.com/a/51223908
type: Question
has body: class CustomThread(QThread): def __init__(self, target, args=()): super().__init__() self.__target = target self.__args = args def run(self): self.__target(*self.__args) class MyClass: def target(self): print("Hello world") # Do something def func(self): thread = CustomThread(self.target) thread.start() In this case, the program crashes if I call func() of MyClass, stating that qthread has been destroyed while running. (Because thread is a local variable) So, I change thread into self.thread, making it be a member variable of MyClass so that it would not be destroyed. class CustomThread(QThread): def __init__(self, target, args=()): super().__init__() self.__target = target self.__args = args def run(self): self.__target(*self.__args) class MyClass: def target(self): print("Hello world") # Do something def func(self): self.thread = CustomThread(self.target) self.thread.start() However, running thread can be potentially garbage collected if I call func() twice or more and program will crash. So, I tried to solve this by adding a list and append every thread. class CustomThread(QThread): def __init__(self, target, args=()): super().__init__() self.__target = target self.__args = args def run(self): self.__target(*self.__args) class MyClass: def __init__(self): self.threads = [] def target(self): print("Hello world") # Do something def func(self): self.thread = CustomThread(self.target) self.threads.append(self.thread) self.thread.start() This solves the problem, but it looks so inefficient and immature. Also I have to pop every thread which finishes its job. (Maybe I have to implement it with signal and slot, and of course it looks redundant) How can I solve this problem more elegantly?
score: 0

http://stackoverflow.com/comment/89365023
comment on: http://stackoverflow.com/q/51191589
score: 0
has text: Or why not just use `df1.TEL.str[:-2]`?
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51246705
answers question: http://stackoverflow.com/q/51246224
score: 3
accepted answer of: http://stackoverflow.com/q/51246224
type: AcceptedAnswer
downvote count: 0
has body: I think need: cc = list(combinations(df.columns,3)) df = pd.concat([df[c[1]].mul(2).sub(df[c[2]]).sub(df[c[0]]) for c in cc], axis=1, keys=cc) df.columns = df.columns.map(''.join) print (df) ABC ABD ACD BCD Dt 11-apr 0 0 0 0 10-apr 3 2 -2 -3
type: Answer
upvote count: 3

http://stackoverflow.com/q/51215402
has comment: http://stackoverflow.com/comment/89416162
has comment: http://stackoverflow.com/comment/89414889
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89411948
upvote count: 1
tagged with: python
has body: I have a binary file, and want to read and decode the file. The file uses one byte for each character. I had an error when decoding the part with a greek letter. Since I cannot share the file, you can use the sample code below for your own testing. The issue is the UnicodeDecodeError. data = b'a5' data.decode("utf-8") 'a5' data = b'a5\xb5' data.decode("utf-8") UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb5 Solution: data = b'a5\xb5' data.decode("windows-1252") 'a5µ'
has title: Python3 decode greek letter from binary file
downvote count: 1
has comment: http://stackoverflow.com/comment/89415291
type: Question
has answer: http://stackoverflow.com/a/51219227
tagged with: decode
answer count: 2
score: 0
tagged with: binaryfiles
has answer: http://stackoverflow.com/a/51215528
favorite count: 0
has comment: http://stackoverflow.com/comment/89411992
tagged with: python-3.x

http://stackoverflow.com/comment/89403016
type: Comment
type: AnswerComment
has text: I hope my new edit will solve your problem. I tried and it works for me
score: 0
comment on: http://stackoverflow.com/a/51210531

http://stackoverflow.com/q/51217584
linked to: http://stackoverflow.com/q/10636024
tagged with: pandas
possible better answer: http://stackoverflow.com/a/65283412
upvote count: 1
tagged with: user-interface
favorite count: 0
has body: There are a number of excellent answers to this question GUIs for displaying dataframes, but what I'm looking to do is a bit more advanced. I'd like to display a dataframe, but have a couple of the columns be interactive where the user can manually overwrite values (and the rest be static). It would be useful to have "total" rows that change with the overwritten values and eventually have some interactive buttons around the dataframe for loading and clearing data. QTPandas looks promising, but appears to be dead as it is build off of a really old version of Pandas (0.17.1). Can this be done in QT? Is something else better?
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/65283412
score: 1
has title: Semi-Interactive Pandas Dataframe in a GUI
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/51935405
accepted answer: http://stackoverflow.com/a/51935405
tagged with: pyqt
downvote count: 0
tagged with: interactive

http://stackoverflow.com/comment/89420770
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51219920
has text: Try just using the .csv file. If it works at least you know the cause. If it doesn't I will try to think of something else

http://stackoverflow.com/comment/89463931
type: AnswerComment
comment on: http://stackoverflow.com/a/51175665
has text: If you need a `While True:` loop, you can put it on a thread, but not as a request answer. Try just deleting that `while True` and the `for` should work
score: 0
type: Comment

http://stackoverflow.com/q/51218869
tagged with: image-processing
has comment: http://stackoverflow.com/comment/89418874
downvote count: 1
tagged with: tensorflow
type: Question
has title: regarding transforming PNG into JPG
has body: I have a set of PNG files which are of shape (64,64,4), and want to feed it to a tensorflow model which was designed for JPG files, which has shape (64,64,3). I plan to transform PNG into JPG, is this a good approach, what's the best way to do it?
score: -1
has answer: http://stackoverflow.com/a/51219305
accepted answer: http://stackoverflow.com/a/51219305
has comment: http://stackoverflow.com/comment/89420307
answer count: 1
favorite count: 0
tagged with: python
tagged with: computer-vision
tagged with: http://stackoverflow.com/tag/png
has comment: http://stackoverflow.com/comment/89419344
type: AnsweredQuestion
upvote count: 0

http://stackoverflow.com/a/51297848
score: 2
has body: If list schema is maintained as (str, int) Using python's zip you can easily unpack list of tuples, without any particular regard to types: my_list = [("Adam",1985),("Karen",1990),("anna",1986)] names, years = zip(*my_list) The unpacked lists are: ('Adam', 'Karen', 'anna'), (1985, 1990, 1986) Notes on the * operator The * operator is called Unpacking Argument Lists, it passes the single elements of the list as argument. Suppose you have a list with 3 elements my_list = [1, 2, 3] ad a function with 3 parameters def func(a, b, c): you can use func(*my_list) to call func(my_list[0], my_list[1], ..., my_list[n]). If list schema is shuffled Solution using sorting, tuple by tuple Using functools.cmp_to_key we can first sort the tuples and then execute the zip: import functools key=functools.cmp_to_key(lambda x1, x2: 1 if isinstance(x2, str) else -1) names, years = zip(*[sorted(t, key=key) for t in l]) This way the list is first sorted as: [['Adam', 1985], ['Karen', 1990], ['anna', 1986]] And afterwards running the zip we obtain the same result: ('Adam', 'Karen', 'anna'), (1985, 1990, 1986) Solution using groupby from itertools import chain, groupby names, years = [ list(v) for _, v in groupby( sorted(chain.from_iterable(my_list), key=lambda x: str(x)), lambda x: isinstance(x, str)) ] Solutions speed comparison on example list Running timeit on the example list we get: Tuple sorting: %timeit zip(*[sorted(t, key=key) for t in my_list]) &gt;&gt;&gt; 5.2 µs ± 157 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each) Groupby %timeit [list(v) for _, v in groupby(sorted(chain.from_iterable(my_list), key=lambda x: str(x)), lambda x: isinstance(x, str))] &gt;&gt;&gt; 6.83 µs ± 358 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each) Solutions speed comparison on large list Running timeit on the a large list such as: import random n = 100000 my_list = [] for i in range(n): if random.choice([True, False]): my_list.append((i, "Karen")) else: my_list.append(("Karen", i)) …
has comment: http://stackoverflow.com/comment/89575174
upvote count: 2
has comment: http://stackoverflow.com/comment/89572866
accepted answer of: http://stackoverflow.com/q/51297742
has comment: http://stackoverflow.com/comment/89574489
answers question: http://stackoverflow.com/q/51297742
has comment: http://stackoverflow.com/comment/89572809
has comment: http://stackoverflow.com/comment/89573358
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/89572827
type: Answer
has comment: http://stackoverflow.com/comment/89572803

http://stackoverflow.com/q/51194214
favorite count: 0
type: UnansweredQuestion
tagged with: pickle
tagged with: python
has title: Django and multiprocessing AttributeError: Can't pickle local object
has comment: http://stackoverflow.com/comment/89371682
answer count: 0
score: 1
tagged with: multithreading
tagged with: django
upvote count: 1
tagged with: multiprocessing
type: Question
linked to: http://stackoverflow.com/q/8242837
has comment: http://stackoverflow.com/comment/89391922
has body: We are trying to proceed multiprocessing in Django, but it never works. To have a simple example, we started an empty Django-project and created the app mp. Then, we added the following code: views.py: from django.http import HttpResponse from .mp import MultiProcess def DoubleIt(number): print("haha") a = number * 2 return a def mp_view(request): mylist = [111,222,333] with MultiProcess() as mp: mp.map(DoubleIt, mylist) results = mp.results() return HttpResponse("Test") urls.py from django.conf.urls import url from django.contrib import admin from mp.views import * urlpatterns = [ url(r'^mp/', mp_view, name="mp_view"), ] mp.py from https://engineering.talentpair.com/django-multiprocessing-153dbcf51dab: from __future__ import print_function, absolute_import, unicode_literals import time try: from Queue import Empty except ImportError: from queue import Empty from multiprocessing import Process, cpu_count, Manager import logging import traceback from django import db from django.conf import settings from django.core.cache import caches from elasticsearch_dsl import connections loggly = logging.getLogger('loggly') class Timer(object): """ Simple class for timing code blocks """ def __init__(self): self.start_time = time.time() def done(self): end_time = time.time() return int(end_time - self.start_time) def close_service_connections(): """ Close all connections before we spawn our processes This function should only be used when writing multithreaded scripts where connections need to manually opened and closed so that threads don't reuse the same connection https://stackoverflow.com/questions/8242837/django-multiprocessing-and-database-connections """ # close db connections, they will be recreated automatically db.connections.close_all() # close ES connection, needs to be manually recreated # connections.connections.remove_connection("default") # close redis connections, will be recreated automatcially for k in settings.CACHES.keys(): caches[k].close() def recreate_se…
downvote count: 0

http://stackoverflow.com/comment/89582133
has text: @AntonvBR yeah if that will help
score: 0
comment on: http://stackoverflow.com/q/51302633
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51245252
type: Question
has body: While trying to install Python (version 2.7.14) on my laptop (Windows 10) today I ran into some issues. See below an image of the command prompt: https://i.gyazo.com/83c487ac3cf569006e4121d95fc1dd1f.png After having tried to fix this myself for a while now I found out that the pip is indeed present, namely in a subfile of python27 (/Tools/Scripts), but is not recognized by cmd. How do I make sure pip is recognized? For some additional info: -the command prompt is ran as an admin -this is not the default location for python to install (which is C: I think), instead I installed it in the program files, as was advised by my University. -I feel like I might know the step of the installation which I did incorrectly, as the Scripts folder is mentioned specifically here. I simply did what the image below suggested. https://i.gyazo.com/a58d4f209b9d56f458d366355f2344ff.png Any help would be greatly appreciated, have a good day!
tagged with: python-2.7
answer count: 1
downvote count: 0
favorite count: 0
has title: Problems with installing Python 2.7.14: Path to pip not recognized
linked to: http://stackoverflow.com/q/23708898
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51246351
tagged with: pip
upvote count: 1
tagged with: python
tagged with: installation
score: 1
has comment: http://stackoverflow.com/comment/109420891

http://stackoverflow.com/q/51246434
duplicate of: http://stackoverflow.com/q/34622715
answer count: 0
score: 1
has comment: http://stackoverflow.com/comment/89471527
upvote count: 1
has title: Pandas DataFrame count number of not None elements in two columns
type: Question
tagged with: dataframe
has comment: http://stackoverflow.com/comment/89471689
tagged with: pandas
downvote count: 0
has body: I have a pandas dataframe and want to count those rows which are not None in two (or more) different columns simultaneously. Of course I can do it like that: count = 0 for index, row in df.iterrows(): if df['Col1'][index] is not None and PurpsAndBanks['Col2'][index] is not None: count+=1 But is there a more elegant/effiecient approach?
favorite count: 0
has comment: http://stackoverflow.com/comment/89471655
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/34622715
tagged with: python
has comment: http://stackoverflow.com/comment/89471538

http://stackoverflow.com/comment/89514187
comment on: http://stackoverflow.com/q/51260177
has text: Yes! that worked! Wow, the issue really seems silly now.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89574262
comment on: http://stackoverflow.com/q/51298426
type: QuestionComment
type: Comment
score: 0
has text: I have gone through the link. But I could find there `I didn't used the same data set for predicting and training. That was my solution.` I am not using a same dataset for training and predicting. Actually the training never starts

find
tags question: http://stackoverflow.com/q/51179236
type: Tag
tags question: http://stackoverflow.com/q/51182776
tags question: http://stackoverflow.com/q/51230252
tags question: http://stackoverflow.com/q/51229817
tag name: find
tags question: http://stackoverflow.com/q/51240862

http://stackoverflow.com/comment/89397702
type: QuestionComment
has text: If the scaling is not identical to begin with, how should zooming be synchronized? I.e. if you have an axes with range [0,1] and another with range [10,100], and you zoom the first to the range [0,.5], what is the expected outcome for the second axis?
comment on: http://stackoverflow.com/q/51201767
score: 0
type: Comment

http://stackoverflow.com/comment/89333790
type: QuestionComment
comment on: http://stackoverflow.com/q/51175450
type: Comment
score: 0
has text: `df.groupby('Country')['Favorite_color'].value_counts().unstack()`

http://stackoverflow.com/comment/92130540
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51280316
has text: I tried this but it also failed when running `make install`. I read the docs and it said that if the system already had Python preinstalled (which mine does as Python 3.6.6) you should run `make altinstall` instead. But I got the exact same error

http://stackoverflow.com/a/51234434
answers question: http://stackoverflow.com/q/51234354
has body: My take on the problem: from itertools import chain names = ['78', '1', '3'] prices = ['15', '20', '10'] names2 = ['82', '11', '33'] prices2 = ['1', '2', '100'] all_subpages = [] subpage = zip(names, prices) all_subpages.append(subpage) subpage2 = zip(names2, prices2) all_subpages.append(subpage2) print('Home number\tprice') for (name, price) in sorted(chain.from_iterable(all_subpages), key=lambda v: int(v[1])): print(f'{name}\t\t{price} GBP') Output: Home number price 82 1 GBP 11 2 GBP 3 10 GBP 78 15 GBP 1 20 GBP 33 100 GBP
accepted answer of: http://stackoverflow.com/q/51234354
upvote count: 1
score: 1
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/q/51256737
has answer: http://stackoverflow.com/a/51273560
has answer: http://stackoverflow.com/a/51257027
type: Question
tagged with: pyside
possible better answer: http://stackoverflow.com/a/51257027
score: 0
accepted answer: http://stackoverflow.com/a/51273560
answer count: 3
tagged with: python
has body: I'm trying to pip install pyside to my Raspberry Pi and receive the following error: pi@raspberrypi:/ $ sudo pip install pyside Collecting pyside Using cached https://files.pythonhosted.org/packages/36/ac/ca31db6f2225844d37a41b10615c3d371587677efd074db29855e7035de6/PySide-1.2.4.tar.gz Building wheels for collected packages: pyside Running setup.py bdist_wheel for pyside ... error Complete output from command /usr/bin/python -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-TXwQwt/pyside/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" bdist_wheel -d /tmp/tmps80BMupip-wheel- --python-tag cp27: Removing /tmp/pip-build-TXwQwt/pyside/pyside_package running bdist_wheel running build Python architecture is 32bit error: Failed to find cmake. Please specify the path to cmake with --cmake parameter. ---------------------------------------- Failed building wheel for pyside Running setup.py clean for pyside Failed to build pyside Installing collected packages: pyside Running setup.py install for pyside ... error Complete output from command /usr/bin/python -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-TXwQwt/pyside/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-5BdNE7-record/install-record.txt --single-version-externally-managed --compile: Removing /tmp/pip-build-TXwQwt/pyside/pyside_package running install running build Python architecture is 32bit error: Failed to find cmake. Please specify the path to cmake with --cmake parameter. ---------------------------------------- Command "/usr/bin/python -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-TXwQwt/pyside/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-5BdNE7-record/in…
has comment: http://stackoverflow.com/comment/89498103
has title: Pip install error (Pyside to Raspberry Pi)
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51257138
tagged with: pip

pyqt5
tags question: http://stackoverflow.com/q/51170224
tags question: http://stackoverflow.com/q/51223647
tags question: http://stackoverflow.com/q/51306172
type: Tag
tags question: http://stackoverflow.com/q/51230544
tags question: http://stackoverflow.com/q/51179279
tags question: http://stackoverflow.com/q/51264267
tags question: http://stackoverflow.com/q/51266185
tags question: http://stackoverflow.com/q/51284338
tags question: http://stackoverflow.com/q/51252887
tags question: http://stackoverflow.com/q/51240875
tags question: http://stackoverflow.com/q/51267623
tags question: http://stackoverflow.com/q/51273301
tags question: http://stackoverflow.com/q/51234288
tags question: http://stackoverflow.com/q/51209797
tags question: http://stackoverflow.com/q/51219981
tags question: http://stackoverflow.com/q/51235632
tags question: http://stackoverflow.com/q/51277302
tags question: http://stackoverflow.com/q/51309888
tags question: http://stackoverflow.com/q/51237546
tags question: http://stackoverflow.com/q/51286721
tags question: http://stackoverflow.com/q/51314138
tags question: http://stackoverflow.com/q/51250663
tags question: http://stackoverflow.com/q/51284268
tags question: http://stackoverflow.com/q/51220934
tags question: http://stackoverflow.com/q/51205071
tags question: http://stackoverflow.com/q/51286339
tags question: http://stackoverflow.com/q/51199137
tags question: http://stackoverflow.com/q/51320402
tags question: http://stackoverflow.com/q/51306683
tags question: http://stackoverflow.com/q/51208669
tags question: http://stackoverflow.com/q/51322698
tags question: http://stackoverflow.com/q/51233683
tags question: http://stackoverflow.com/q/51222085
tags question: http://stackoverflow.com/q/51221094
tag name: pyqt5
tags question: http://stackoverflow.com/q/51320536
tags question: http://stackoverflow.com/q/51251185
tags question: http://stackoverflow.com/q/51308772
tags question: http://stackoverflow.com/q/51265910
tags question: http://stackoverflow.com/q/51246564
tags question: http://stackoverflow.com/q/51220553
tags question: http://stackoverflow.com/q/51257557
tags question: http://stackoverflow.com/q/51173284
tags question: http://stackoverflow.com/q/51169641

http://stackoverflow.com/comment/89429830
type: QuestionComment
comment on: http://stackoverflow.com/q/51222009
has text: You need to pass the device address `response=client.read_holding_registers(0,1, unit=<your slave address here>)`
score: 0
type: Comment

http://stackoverflow.com/q/51241447
score: -1
answer count: 2
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/89461732
type: UnansweredQuestion
tagged with: django
tagged with: python
has body: I want the value to be the category which I pressed. &lt;div class = 'category_Choose'&gt; &lt;input type='text' name = 'category_id' value="???"&gt; &lt;/div&gt; Example: if I choose category Anime I want this field value to be Anime. class Category(models.Model): title = models.CharField(max_length=150) category_post = models.ForeignKey('Post', on_delete=models.CASCADE) body = models.TextField() photo = models.ImageField(upload_to='static/images/', default = 'static/images/single_image.png') url = models.CharField(max_length=150) def __str__(self): return self.title How can I do this?
has answer: http://stackoverflow.com/a/51241685
upvote count: 0
has title: django Category -id value
has comment: http://stackoverflow.com/comment/89462051
type: Question
has answer: http://stackoverflow.com/a/51241805
has comment: http://stackoverflow.com/comment/89461883
has comment: http://stackoverflow.com/comment/89461812

http://stackoverflow.com/comment/89592227
type: QuestionComment
comment on: http://stackoverflow.com/q/51307435
score: 0
has text: Fixed, thank you for your help.
type: Comment

http://stackoverflow.com/q/51243181
score: 1
type: Question
answer count: 2
downvote count: 0
possible better answer: http://stackoverflow.com/a/70909325
has body: I have a data frame in pandas including several columns, I need to get access to the one cell which contains a list of items, how would it be possible? (e.g. how to get access to Match elements in the following example) ID Match 1 (word1,,,) 2 (word2,,,),(word1) 3 (word2,,,),(word1),(word3,,,)
tagged with: pandas
upvote count: 1
favorite count: 0
has title: how to get access to a list of items in a cell in pandas
tagged with: python
has answer: http://stackoverflow.com/a/51243346
accepted answer: http://stackoverflow.com/a/51243346
has answer: http://stackoverflow.com/a/70909325
type: AnsweredQuestion

http://stackoverflow.com/comment/89400455
has text: Edited. I apologize. I thought that was clear enough "how can I make my line's color shade darken with increasing index".
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51204559
score: 0

http://stackoverflow.com/a/51285186
answers question: http://stackoverflow.com/q/51284583
downvote count: 0
has body: Use decorators, with @login_required you can tell this views will be only accesseed when user os logged in, you can pass parameters to it too or create one your own to validate if the logged user on the request can see or no your view With Login Required from django.contrib.auth.decorators import login_required @login_required(login_url='/accounts/login/') class AdminView(generic.ListView): ... @login_required(login_url='/accounts/login/') class AdminUpdateView(UpdateView): ... https://docs.djangoproject.com/en/2.0/topics/auth/default/#the-login-required-decorator With Permission from django.contrib.auth.decorators import permission_required @permission_required('user.is_staff') def my_view(request): ... https://docs.djangoproject.com/en/2.0/topics/auth/default/#the-permission-required-decorator
type: Answer
upvote count: 2
score: 2

http://stackoverflow.com/comment/89517508
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51267467
has text: You're using the `-n` flag. In the first snippet you're matching against feature files with "Login"; in the second snippet you're matching against feature files with "Neat". Try having a simple feature file and test step to test this with

http://stackoverflow.com/comment/89466506
has text: Give your `Game` a `self.world_shift = 0` attribute in the `__init__` method.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51231774

http://stackoverflow.com/q/51254686
has comment: http://stackoverflow.com/comment/89488992
favorite count: 0
upvote count: 1
tagged with: python
has body: Graph randomly generated with networkx. I want to retrieve from this graph the strongly connected components. Why do I get only one large scc using the built-in networkx function? n = random.randint(10, 500) p = random.randint(1, 9) / 10 graph = nx.gnp_random_graph(n, p, seed=None, directed=True) print("Nodes {} Edge density {}".format(n, p)) comp = nx.strongly_connected_components(graph) sccs = list(nx.strongly_connected_components(graph)) sccs.reverse() print(sccs) Nodes 127 Edge density 0.9 [{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126}] Even if a force density of edge to 0.1, I get the same SCC. graph = nx.gnp_random_graph(n, 0.1, seed=None, directed=True) print("Nodes {} Edge density {}".format(n, p)) comp = nx.strongly_connected_components(graph) sccs = list(nx.strongly_connected_components(graph)) sccs.reverse() print(sccs) Nodes 484 Edge density 0.1 <generator object strongly_connected_component_subgraphs at 0x000001B8019A9468> [{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135…
tagged with: networkx
has title: Strongly connected components in graph - networkx library
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51254924
score: 1
tagged with: strongly-connected-graph
has comment: http://stackoverflow.com/comment/89488296
type: Question
tagged with: graph
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/89489010
accepted answer: http://stackoverflow.com/a/51254924
has comment: http://stackoverflow.com/comment/89488316
tagged with: graph-algorithm

http://stackoverflow.com/q/51230690
type: Question
upvote count: 1
has title: How to extract patches of same size from images of different size and batch them together with tensorflow dataset api?
answer count: 1
has answer: http://stackoverflow.com/a/51365947
accepted answer: http://stackoverflow.com/a/51365947
favorite count: 0
tagged with: deep-learning
tagged with: python
downvote count: 0
tagged with: machine-learning
tagged with: computer-vision
tagged with: tensorflow
type: AnsweredQuestion
has body: I am trying to make a tensorflow dataset api(tf version 1.8) for a set of images which are of different sizes. To do this, I am extracting patches of same size from the images and feeding it to my neural net. The problem is in tf.extract_patches_from_images, the patches get stored in the channel dimension. As each image is of different size, number of patches are different for each image. Hence the shape of each resulting image is different. Hence I can't batch them together using tf dataset api. Can someone suggest changes in my following modify_image function to tackle the issue? I guess separating the patches into different images and then batching them together would work. But I can't understand how to do that. I want to scan the whole image, hence randomly selecting equal number of patches won't work for me. def modify_image(image): '''add preprocessing functions here''' image = tf.expand_dims(image,0) image = tf.extract_image_patches( image, ksizes=[1,patch_size,patch_size,1], strides=[1,patch_size,patch_size,1], rates=[1,1,1,1], padding='SAME', name=None ) image = tf.reshape(image,shape=[-1,patch_size,patch_size,1]) return image; def parse_function(image,labels): image= tf.read_file(image) image = tf.image.decode_image(image) labels = tf.read_file(labels) labels = tf.image.decode_image(labels) image = modify_image(image) labels = modify_image(labels) return image,labels def list_files(directory): files = glob.glob(directory) return files def load_dataset(img_dir,labels_dir): images = list_files(img_dir) images = tf.constant(images) labels = list_files(labels_dir) labels = tf.constant(labels) dataset = tf.data.Dataset.from_tensor_slices((images,labels)) dataset = dataset.map(parse_function) return dataset def make_batches(home_dir,img_dir,labels_dir,batch_size): img_dir = home_dir + img_dir labels_dir = home_dir +labels_dir dataset = load_dataset(img_dir,labels_dir) batched_dataset = dataset.batch(batch_size) return batched_dataset
score: 1

http://stackoverflow.com/comment/89431111
has text: Note that I am trying to create a zip file before everything. `xzip = zipfile.ZipFile(os.path.join(directory,"%s.zip" % filename), "w")` the OP shows it. Are you talking about this? .... because the `return HttpResponseRedirect` will just generate the file
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51224525

http://stackoverflow.com/comment/89489047
comment on: http://stackoverflow.com/q/51254627
type: Comment
score: 0
type: QuestionComment
has text: I have, but not immediately. And using your tip (sorry for not seeing it), I found the exact installation path. So, should I just remove it from there?

http://stackoverflow.com/q/51289421
upvote count: 0
tagged with: flask
has comment: http://stackoverflow.com/comment/89556782
answer count: 1
score: -2
favorite count: 0
has answer: http://stackoverflow.com/a/51289514
downvote count: 2
has body: The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again from flask import Flask app = Flask(__name__) @app.route('/user/&lt;username&gt;') def show_user_profile(username): return 'User %s' % username @app.route('/post/&lt;int:post_id&gt;') def show_post(post_id): return 'Post %d' % post_id @app.route('/path/&lt;path:subpath&gt;') def show_subpath(subpath): return 'Subpath %s' % subpath
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89557036
has title: i did all the instruction on the documentation but i still get this error
type: Question
accepted answer: http://stackoverflow.com/a/51289514

http://stackoverflow.com/comment/89385775
type: Comment
type: QuestionComment
has text: Welcome to [so].Please check [ask] and make your question a [mcve] .
score: 0
comment on: http://stackoverflow.com/q/51202159

http://stackoverflow.com/a/51309886
type: AcceptedAnswer
has body: You can use simple recursion: demo_dict = {1:{2:{3:{4:5}}}} path = [1,2,3,4] def get_val(d, _path): return d[_path[0]] if not _path[1:] else get_val(d[_path[0]], _path[1:]) print(get_val(demo_dict, path)) Output: 5
accepted answer of: http://stackoverflow.com/q/51300877
type: Answer
downvote count: 0
score: 3
upvote count: 3
answers question: http://stackoverflow.com/q/51300877

http://stackoverflow.com/q/51300431
possible better answer: http://stackoverflow.com/a/51300490
has answer: http://stackoverflow.com/a/51300522
type: Question
has answer: http://stackoverflow.com/a/51301202
has answer: http://stackoverflow.com/a/51300516
has answer: http://stackoverflow.com/a/51300585
has comment: http://stackoverflow.com/comment/89578413
has answer: http://stackoverflow.com/a/51300714
tagged with: list-comprehension
score: 0
has comment: http://stackoverflow.com/comment/89577765
has answer: http://stackoverflow.com/a/51300552
has comment: http://stackoverflow.com/comment/89577734
has body: I have a list with floats, for example numbers = [1000.45,1002.98,1005.099,1007.987] I want to create a new list containing the deltas of the value in numbers - i.e. I want the difference between numbers[0],[numbers[1] to be the first value in a new list. So the first number in my new list should be 2.53, the second should be 2.119, and so forth. I tried list comprehension newnumbers= [i[-1] - i[-2] for i in numbers] but it gives a TypeError TypeError: 'float' object is not subscriptable I tried converting the list to integers, but then it gives the same type of error. How can I create my desired list?
answer count: 7
accepted answer: http://stackoverflow.com/a/51300516
has title: Create a new list with changes of value of a previous list
tagged with: python
has answer: http://stackoverflow.com/a/51300490
type: AnsweredQuestion

http://stackoverflow.com/q/51320119
answer count: 1
tagged with: wxpython
has body: I am new for python and try to create a app to process the data from different CSV file. My app always to process the first open CSV file data and I have no idea for where is wrong in my code? below is my sample: Sample1.csv : ABC,DEF,GHI 1,3,7 2,5,8 3,6,9 Sample2.csv : JKL,MNO,PQR,STU 1,3,7,10 2,5,8,11 3,6,9,12 My app will open the CSV file and put the header of CSV file which like ABC,DEF,GHI into the wx.Listbox selection and process something if you click on the selection. It looks OK to open sample1.csv first but when I open the sample2.csv and click the JKL,MNO,PRQ and STU then the panel will go back sample1.csv data! I don't know why? is need to clear the old panel then create a new? if yes How to do? Or I need to create a new frame to process the csv data? Thanks for your help ! import csv import wx class Mywin(wx.Frame): def __init__(self, parent, title): super(Mywin, self).__init__(parent, title = title,size = (550,500)) toolbar = self.CreateToolBar() OpenCsvBtn = wx.Button(toolbar, -1," Open CSV") self.Bind(wx.EVT_BUTTON, self.OnClick, OpenCsvBtn) self.Centre() self.Show(True) def onListBox(self, event): self.text.AppendText( "Current selection:"+event.GetEventObject().GetStringSelection()+"\n") def OnClick(self, event): panel = wx.Panel(self) print("open the csv file and get the path") frame = wx.Frame(None, -1, 'win.py') openFileDialog = wx.FileDialog(frame, "Open CSV file", "", "", "CSV files (*.csv)|*.csv", wx.FD_OPEN | wx.FD_FILE_MUST_EXIST) openFileDialog.ShowModal() csvPath=openFileDialog.GetPath() print(csvPath) with open(csvPath) as csvFile: csvReader = csv.reader(csvFile) i=csvReader.next() rest = [row for row in csvReader] print (i) box = wx.BoxSizer(wx.HORIZONTAL) self.text = wx.TextCtrl(panel,size =(200,400), style = wx.TE_MULTILINE) languages = i #[title[0]] lst = wx.ListBox(panel, size = (200,400), choices = languages, style = wx.LB_SINGLE) box.Add(lst,0,wx.EXPAND) box.Add(self.text, 1, wx.EXPAND) panel.SetSizer(box) panel.Fit() self.Bind(wx…
score: 0
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has answer: http://stackoverflow.com/a/51329153
type: UnansweredQuestion
type: Question
has title: How to use new wx.panel or wx.ListBox when press button event

http://stackoverflow.com/comment/90210382
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51227190
has text: The `argparse.py` file from a 3.7 repository can be used with earlier Py3 distributions. Just copy it to your own directory, possibly renaming, and import.
score: 0

http://stackoverflow.com/a/51202770
type: Answer
answers question: http://stackoverflow.com/q/51202430
score: 0
has body: In the image that you shared, it shows a directory listing as you have no index file set for the root of your virtual server. You probably don't want your data files exposed to the world. To display your Django project when requesting the mysite.com root, consider setting up WSCGI using the WSGIDaemonProcess directive. You'll probably want to set up some additional directories for static resources, too. Some simple directory permissions in your VirtualHost configuration and access permissions for your project data files should help get things running safely and reliably. Check out this HOWTO for setting up Apache to serve up Django written by someone awesome at DigitalOcean (skip down to the Configuring Apache section). Though the documentation I provided is not geared specifically to amazon-ec2, the Apache section should be enough to get you running. Please let me know how it works out.

http://stackoverflow.com/q/51287084
tagged with: javascript
has body: I'm building a Django Weather App, where there is a search input field and and by writing city name in input we can get weather details in console for now. But when typing any city name in input form, its showing "Uncaught SyntaxError: Unexpected identifier" error in console. I am unable to debug this error. models.py class City(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name forms.py class CityForm(forms.ModelForm): class Meta: model = City fields = ('__all__') urls.py urlpatterns = [ path('ajax5',views.ajax5view) ] views.py def ajax5view(request): return render (request,'ajax5.html') ajax5.html {% load staticfiles %} Title javascript (ajax5.js) $(document).ready(function(){ $('.btn').click(function(){ var city = $('#city').val(); $.ajax({ url: 'https://api.openweathermap.org/data/2.5/forecast?q='+ city +'&appid=026b9c980571390d69406536cdaaccea', method : 'GET', dataType: 'json' success: function(data){ console.log(data); } }) }); });
tagged with: python
has comment: http://stackoverflow.com/comment/89552937
has comment: http://stackoverflow.com/comment/89553335
has comment: http://stackoverflow.com/comment/89553192
has comment: http://stackoverflow.com/comment/89553722
has comment: http://stackoverflow.com/comment/89552903
has comment: http://stackoverflow.com/comment/89552205
type: UnansweredQuestion
tagged with: django
has comment: http://stackoverflow.com/comment/89551792
has title: "Uncaught SyntaxError: Unexpected identifier" in Javascript in Django Template
has comment: http://stackoverflow.com/comment/89552194
has answer: http://stackoverflow.com/a/51288185
has comment: http://stackoverflow.com/comment/89551695
has comment: http://stackoverflow.com/comment/89552765
has comment: http://stackoverflow.com/comment/89552365
has comment: http://stackoverflow.com/comment/89552116
has comment: http://stackoverflow.com/comment/89551823
has comment: http://stackoverflow.com/comment/89553223
type: Question
score: 0
has comment: http://stackoverflow.com/comment/89551797
answer count: 1

http://stackoverflow.com/q/51190198
tagged with: pandas
answer count: 1
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/51190241
accepted answer: http://stackoverflow.com/a/51190241
tagged with: python
type: AnsweredQuestion
score: 1
upvote count: 1
type: Question
has body: Evening Chaps, quick one, what's the best method to concatenate strings in a dataframe? I have a CSV which is output of a form. True to if/else form fashion the outputs for any child questions has been output in new columns. As the majority of the form are child questions I want to write a small script to do the following. 1, Drop Irrelevant Columns 2. Concatenate remaining columns by delimiter. (',') 3. Create new DF by adding in the merged columns and the irrelevant columns from step 1. my attempt: import pandas as pd import os enter code here df = pd.read_csv('survey.csv') df Qual, Qual2, Qual3, Qual4, Qual5, Qual6 0 IT Digital NaN NaN NaN NaN 1 NaN NaN Maths NaN NaN NaN df['Combined_Data'] = df.fillna('').astype(str).sum(axis=1) df: Qual, Qual2, Qual3, Qual4, Qual5, Qual6 Combined Data 0 IT Digital NaN NaN NaN NaN ITDigital 1 NaN NaN Maths NaN Algebra NaN MathsAlgebra I'm unsure how to add a , in between each sum or if in fact sum is the correct way to do this..? probably not. but this is what I found after several google searches. any help would be most appreciated.
has title: Concatenate string data in Pandas Python
has comment: http://stackoverflow.com/comment/89361953

http://stackoverflow.com/comment/89438889
has text: @zilong - its called a list comprehension. you have to read it kind of backwards. `data` is a list. `for year in data` means that `year` will take every value of data after the other. `[x.strip() for x in year.split("\t") if x.strip()]` means - split `year` at '|' (gives another list in return) and `for x in yearl.split('|')` means x will in turn take the value of every split part. 'x.strip()' removes the whitespaces and `if x.strip()` only matches for x that are not empty after stripping them (removes the `'\t \t'` whitespace from the result).
comment on: http://stackoverflow.com/a/51221425
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/89417500
has text: If you use the `tr` command I gave you to look at the environment variables that PyCharm itself has set, what does its PATH look like?
type: Comment
score: 0
comment on: http://stackoverflow.com/q/51218108
type: QuestionComment

http://stackoverflow.com/comment/89581698
score: 0
type: Comment
type: QuestionComment
has text: @AndrejKesely go click 'example-tree'. do you see the image?
comment on: http://stackoverflow.com/q/51302378

http://stackoverflow.com/a/51221976
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/51221908
score: 2
upvote count: 2
has body: if you want to keep processing other files in case of an exception you should change the try/except, by using with the file gets closed automatically: def read_file(): for filename in input_files: try: with open(filename, encoding="utf-8") as f: for line_num, line in enumerate(f, 1): line = line.rstrip() if line: # do something with line and line_num except FileNotFoundError as err: print("File not found", filename)

http://stackoverflow.com/comment/89564926
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51273292
score: 0
has text: what would I put for port and is it possible not to have a password? When I login to the SQL database, there is no password

http://stackoverflow.com/comment/89563769
score: 0
type: Comment
type: QuestionComment
has text: Please fix the formatting of your code.
comment on: http://stackoverflow.com/q/51292672

http://stackoverflow.com/a/51284669
has body: As mentioned - StopIteration gets raised when attempting to consume an element from an exhausted iterable. it = iter([1, 2]) next(it) # 1 next(it) # 2 next(it) # raises StopIteration as nothing to return # however you can use the default argument to return a default value when exhausted # next(it, 'cabbage!') # cabbage! However, since you only want to be taking a random line from a file, instead of counting the lines and picking a line number, then scanning the file and extracting that line, you can use a min with a random key and do it in one pass, eg: import heapq, random with open('your_file') as fin: random_line = min(fin, key=lambda L: random.random()) If you want to take more than 1, then you can use heapq as such: with open('your_file') as fin: random_50 = heapq.nlargest(50, fin, key=lambda L: random.random()) If the files aren't going to blow up system memory and you're going to be wanting to take a random line a lot, then you can load them into a list and then use random.choice, eg: with open('your_file') as fin: data = list(fin) r1 = random.choice(data) r2 = random.choice(data) # ...
upvote count: 3
has comment: http://stackoverflow.com/comment/89547346
type: Answer
downvote count: 1
has comment: http://stackoverflow.com/comment/89547488
accepted answer of: http://stackoverflow.com/q/51284354
answers question: http://stackoverflow.com/q/51284354
has comment: http://stackoverflow.com/comment/89549674
score: 2
has comment: http://stackoverflow.com/comment/89549665
has comment: http://stackoverflow.com/comment/89549874
type: AcceptedAnswer

http://stackoverflow.com/comment/89506774
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51264130
has text: {u'ActiveChats': [{u'Id': u'abRMVBl30bTO7huMKvdgiUEjC8m2', u'Name': u'Sushma Benakatti'}, {u'Name': u'Sushma B', u'Id': u'pFrCGMI1VRZVCDCvPa837YjRin62'}]} I want this data to be available on the excel sheet. @Willem

http://stackoverflow.com/a/51169095
type: Answer
score: 1
has body: Looking at your question, I believe one way of working around this is to have several of your function parameters set to default sentinel values (usually None; use whichever default value makes sense in your scenario) so that you do not have to pass the values on function call; and if you do pass them, they get processed just like normal parameters. Your function definition would look like this: def search(url, query, authHeader, resultLimit=None, resultInfoSize=None): Additionally, you may have to change your searchRequest definition in the function in the event that resultLimit or resultInfoSize is None.
upvote count: 1
accepted answer of: http://stackoverflow.com/q/51168499
has comment: http://stackoverflow.com/comment/89324252
has comment: http://stackoverflow.com/comment/89322470
answers question: http://stackoverflow.com/q/51168499
has comment: http://stackoverflow.com/comment/89324862
has comment: http://stackoverflow.com/comment/89323258
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/89347327
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51181348
has text: Maybe using [Threads](https://docs.python.org/2/library/threading.html) .

http://stackoverflow.com/comment/89584792
type: AnswerComment
has text: with your alternative, you still have to read the entire file into the `lines` list, right? so what is the difference?
comment on: http://stackoverflow.com/a/51302332
score: 0
type: Comment

http://stackoverflow.com/q/51175192
has comment: http://stackoverflow.com/comment/89432462
score: 6
linked to: http://stackoverflow.com/q/26187759
has body: I am processing a dataframe with a click-stream and I'm extracting features for each user in the click-stream to be used in a Machine Learning project. The dataframe is something like this: data = pd.DataFrame({'id':['A01','B01','A01','C01','A01','B01','A01'], 'event':['search','search','buy','home','cancel','home','search'], 'date':['2018-01-01','2018-01-01','2018-01-02','2018-01-03','2018-01-04','2018-01-04','2018-01-06'], 'product':['tablet','dvd','tablet','tablet','tablet','book','book'], 'price': [103,2,203,103,203,21,21]}) data['date'] = pd.to_datetime(data['date']) Since I have to create features for each user I'm using a groupby/apply with a custom function like: featurized = data.groupby('id').apply(featurize) Create user features will take a chunk of the dataframe and create many (hundreds) of features. The whole process is just too slow so I'm looking for a recommendation to do this more effciently. An example of the function used to create features: def featurize(group): features = dict() # Userid features['id'] = group['id'].max() # Feature 1: Number of search events features['number_of_search_events'] = (group['event']=='search').sum() # Feature 2: Number of tablets features['number_of_tablets'] = (group['product']=='tablet').sum() # Feature 3: Total time features['total_time'] = (group['date'].max() - group['date'].min()) / np.timedelta64(1,'D') # Feature 4: Total number of events features['events'] = len(group) # Histogram of products examined product_counts = group['product'].value_counts() # Feature 5 max events for a product features['max_product_events'] = product_counts.max() # Feature 6 min events for a product features['min_product_events'] = product_counts.min() # Feature 7 avg events for a product features['mean_product_events'] = product_counts.mean() # Feature 8 std events for a product features['std_product_events'] = product_counts.std() # Feature 9 total price for tablet products features['tablet_price_sum'] = group.loc[group['product']…
answer count: 2
tagged with: pandas
downvote count: 0
has title: Best way to process a click stream to create features in Pandas
linked to: http://stackoverflow.com/q/14262433
has comment: http://stackoverflow.com/comment/89451435
favorite count: 0
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/51247197
upvote count: 6
has answer: http://stackoverflow.com/a/51316571
has comment: http://stackoverflow.com/comment/89432306
type: Question

http://stackoverflow.com/a/58431589
type: Answer
answers question: http://stackoverflow.com/q/51308225
score: 0
has body: Certainly not because the dropout layer doesn't really affect the network architecture.

http://stackoverflow.com/a/51314275
type: AcceptedAnswer
type: Answer
upvote count: 4
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51314045
has body: Bokeh does not "use" a Python version. Bokeh is installed in to a Python environment, and when you run bokeh serve the Python version from the corresponding environment is used. That is how Python works in general, there is no way for Bokeh to behave differently. The most likely explanation is that you have multiple Python environments, and the Python 2.7 environment is first on your system PATH. Make sure Bokeh is installed into the Python 3 environment (i.e. into its site-packages) and make sure that the bin directory for the Python 3 environment is first on your path (or run the Bokeh server by providing a full absolute path to the correct one). Alternatively, you can run the Bokeh server with -m: python -m bokeh serve app.py In which case you can control exactly which Python executable is used, directly.
has comment: http://stackoverflow.com/comment/89676089
answers question: http://stackoverflow.com/q/51314045
score: 4

http://stackoverflow.com/comment/89428257
type: AnswerComment
has text: Could you explain, please, what is that number 3 from here: grouper(3, splitted) ? Thank you very much in advance !
type: Comment
comment on: http://stackoverflow.com/a/51223939
score: 0

http://stackoverflow.com/comment/89546809
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/51284652
has text: Hard to tell, what you wanna do. What does help() do? Why you need to call it from the main process? Does help() depend ons some variables available only in the main process? Normally you can share variables between threads, just remember to make them thread-safe (locking)
type: Comment

http://stackoverflow.com/a/78840304
has body: The solution is to set the following env variables MYSQLCLIENT_CFLAGS and MYSQLCLIENT_LDFLAGS CFLAGS should be &quot;-I&lt;path to mysql/include folder&gt; For example in linux export MYSQLCLIENT_CFLAGS=-I/usr/test/mysql8.0.36/include And MYSQLCLIENT_LDFLAGS=-L/usr/test/mysql8.0.36/lib
score: 0
answers question: http://stackoverflow.com/q/51294268
type: Answer

http://stackoverflow.com/q/51209836
has answer: http://stackoverflow.com/a/51210254
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/4706499
tagged with: multiple-columns
type: Question
tagged with: http://stackoverflow.com/tag/csv
tagged with: addition
tagged with: python
has title: add extracted data as a new column in the existing csv-python
score: 0
has body: Anyone please helps. Please point out where i am wrong when the extracted reviews are written into 3 separate columns in hotelreview.csv, how can i fix this in order to write them into 1 column? and how to add the heading name "review" for it based on the codes below. And I also want to add the new extracted data ("review" column) into the existing csv 'hotel_FortWorth.csv'. I just added the extracted information into a new csv, i don't know how to combine 2 files together or any other ways? the url can be repeated to match the reviews. Please! Thank you! File 'hotel_FortWorth.csv' has 3 columns, for example: Name link 1 Omni Fort Worth Hotel https://www.tripadvisor.com.au/Hotel_Review-g55857-d777199-Reviews-Omni_Fort_Worth_Hotel-Fort_Worth_Texas.html 2 Hilton Garden Hotel https://www.tripadvisor.com.au/Hotel_Review-g55857-d2533205-Reviews-Hilton_Garden_Inn_Fort_Worth_Medical_Center-Fort_Worth_Texas.html 3...... ... I used the urls from existing csv to extract the reviews, the codes as shown: import requests from unidecode import unidecode from bs4 import BeautifulSoup import pandas as pd file = [] data = pd.read_csv('hotel_FortWorth.csv', header = None) df = data[2] for url in df[1:]: print(url) thepage = requests.get(url).text soup = BeautifulSoup(thepage, "html.parser") resultsoup = soup.find_all("p", {"class": "partial_entry"}) file.extend(resultsoup) with open('hotelreview.csv', 'w', newline='') as fid: for review in file: review_list = review.get_text() fid.write(unidecode(review_list+'\n')) Expected result: name link review 1 ... ... ... 2 ....
answer count: 1

http://stackoverflow.com/comment/89564321
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/51293346
has text: Your code doesn't check that the file exists, it iterates through the directory (to the variable `file`) but you are passing in `filename` when you try and read the csv, when there is no guarantee that `filename` exists.
type: Comment

http://stackoverflow.com/comment/89377582
type: Comment
has text: @blhsing Once you add something to the default value, though, it *stays* there; you don't get a fresh empty list on every call that doesn't take an explicit argument.
comment on: http://stackoverflow.com/a/51197809
score: 0
type: AnswerComment

http://stackoverflow.com/comment/89602552
type: Comment
comment on: http://stackoverflow.com/q/51306655
score: 0
type: QuestionComment
has text: To anyone reading this, let me note that I ended up using ProcExp to find out all of the locations that the regular python was touching and therefore I needed to add the following three locations to `PythonEngine.PythonPath: c:\conda_env\lib c:\conda_env\lib\site-packages and c:\conda_env\dlls

http://stackoverflow.com/comment/89386029
comment on: http://stackoverflow.com/a/51202037
has text: No, see https://stackoverflow.com/questions/4395230/building-a-list-in-django-templates for building a list within your template. Also fix your input tag so that `name` uses the loop variable, i.e. `<input name="{{ name }}" ...` and get rid of the commas inside the `input` tag
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/89558315
score: 0
type: Comment
has text: i added the home route to my code, but i get only the world 'welcome'
type: AnswerComment
comment on: http://stackoverflow.com/a/51289514

http://stackoverflow.com/q/51265145
possible better answer: http://stackoverflow.com/a/51266742
favorite count: 0
has title: Generalizing custom sorting function to multiple columns (ascending/descending order)
has body: This question is based on previous Stackoverflow answer. The problem seems too big for me. I now have sorting function sort_multi(lst, index_normal, index_reversed) which takes input list, and two parameters which indicates which column is sorted in normal order and which in reverse: from pprint import pprint from itertools import groupby, chain l = ((1, 'b'), (1, 'd'), (2, 'a'), (1, 'a')) def sort_multi(lst, index_normal, index_reversed): return list(chain.from_iterable([sorted(list(j), key=lambda v:v[index_reversed], reverse=True) for i, j in groupby(sorted(lst), key=lambda v:v[index_normal])])) pprint(sort_multi(l, 0, 1), width=10) # index 0 is sorted normally, 1 in reversed order. Output: [(1, 'd'), (1, 'b'), (1, 'a'), (2, 'a')] What I want is extend the function to work for any number of indices. Eg. For example input of 3 columns: l = ((1, 'c', 'aa'), (2, 'b', 'bb'), (1, 'c', 'cc'), (1, 'd', 'dd')) sort_multi(l, reversed=(False, True, True)) Gives output: [(1, 'd', 'dd'), (1, 'c', 'cc'), (1, 'c', 'aa'), (2, 'b', 'bb')] The tuples can contains strings, integers, ...
tagged with: python
type: AnsweredQuestion
upvote count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/51266742
type: Question
linked to: http://stackoverflow.com/q/51252687
tagged with: python-itertools
has comment: http://stackoverflow.com/comment/89508992
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/51265784
accepted answer: http://stackoverflow.com/a/51265784
has comment: http://stackoverflow.com/comment/89508753
tagged with: sorting

http://stackoverflow.com/a/51184279
answers question: http://stackoverflow.com/q/51184089
has body: As far as I understand your data, the following regex should work: pattern = "Iteration\s+(\d+)|detection_eval\s+=\s+(.+$)" for it,de in re.findall(pattern, log, flags=re.M): if it: print('Iteration', int(it)) if de: print('detection_eval', float(de)) #Iteration 200 #detection_eval 0.00273318 However, reading the whole log file at once is usually a bad idea. Consider reading one line at a time: with open(log_file, 'r') as log_file2: for line in log_file2: for it,de in re.findall(pattern, log): if it: print('Iteration', int(it)) if de: print('detection_eval', float(de))
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 2
accepted answer of: http://stackoverflow.com/q/51184089
score: 2

http://stackoverflow.com/comment/90652085
comment on: http://stackoverflow.com/a/51838489
score: 0
type: AnswerComment
type: Comment
has text: are you saying that im talking about the wrong version of python? I have 2.7, 3.4 (the problem version) and now this release candidate

http://stackoverflow.com/a/51198155
has comment: http://stackoverflow.com/comment/89378310
has body: N = 4 # number of objects (e.g. slots) possible_values = ['A','B'] result = itertools.product(possible_values, repeat=N) print(list(result))
has comment: http://stackoverflow.com/comment/89378503
has comment: http://stackoverflow.com/comment/89378355
has comment: http://stackoverflow.com/comment/89378264
answers question: http://stackoverflow.com/q/51198109
has comment: http://stackoverflow.com/comment/89378408
has comment: http://stackoverflow.com/comment/89378365
score: 1
upvote count: 5
has comment: http://stackoverflow.com/comment/89378392
has comment: http://stackoverflow.com/comment/89378394
has comment: http://stackoverflow.com/comment/89378251
downvote count: 4
has comment: http://stackoverflow.com/comment/89378473
has comment: http://stackoverflow.com/comment/89378197
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89378334
has comment: http://stackoverflow.com/comment/89378422
accepted answer of: http://stackoverflow.com/q/51198109
has comment: http://stackoverflow.com/comment/89378447
has comment: http://stackoverflow.com/comment/89378291
type: Answer
has comment: http://stackoverflow.com/comment/89378562
has comment: http://stackoverflow.com/comment/89378364
has comment: http://stackoverflow.com/comment/89378370

http://stackoverflow.com/comment/89550960
has text: It will work with MSSQL, but you'll need the SQLAlchemy package to create your MSSQL engine. There's some info in their [docs](http://docs.sqlalchemy.org/en/latest/dialects/mssql.html#module-sqlalchemy.dialects.mssql.pyodbc) for creating one.
type: Comment
score: 1
comment on: http://stackoverflow.com/a/51273292
type: AnswerComment

http://stackoverflow.com/q/51182025
has answer: http://stackoverflow.com/a/51182474
type: Question
upvote count: 2
answer count: 2
has body: I've written the following code that displays a correlation matrix/heatmap for Pandas DataFrames. It works well for DataFrames with 20 or fewer variables. However, I am looking for a smart way/function that easily handles many variables, like by producing multiple heatmaps, such that all variables are compared against each other. For example, a data frame with 100 variables wouldn't be coherently displayed in a single correlation heatmap. import seaborn as sns fig, ax = plt.subplots(figsize=(15, 15)) # Sample figsize in inches cmap = sns.diverging_palette( 220 , 10 , as_cmap = True ) # color map sns.heatmap(data = df.corr(), cmap = cmap, square = True, cbar_kws = {'shrink': .3}, annot = True, annot_kws = {'fontsize': 12}, ax = ax ) A way to visualize this problem is below. Let's let at a toy example. Suppose we have a dataframe with 6 variables: [a, b, c, d, e, f] and not all 6 variables can fit on 1 heatmap. I'm guessing the solution will have to partition the columns into partitions, like [a, b], [c, d] and [e, f].
tagged with: pandas
favorite count: 0
has answer: http://stackoverflow.com/a/76714110
type: UnansweredQuestion
has title: Python: very large correlation heatmap for many variables
tagged with: python
score: 2
downvote count: 0

http://stackoverflow.com/q/51294382
has title: Python Contingency Table
type: Question
tagged with: numpy
answer count: 2
score: 5
has body: I am generating many, many contingency tables as part of a project that I'm writing. The workflow is: Take a large data array with continuous (float) rows and convert those to discrete integer values by binning (so that the resulting row has values 0-9, for example) Slice two rows into vectors X &amp; Y and generate a contingency table from them, so that I have the 2-dimensional frequency distribution For example, I'd have a 10 x 10 array, counting the number of (xi, yi) that occur Use the contingency table to do some information theory math Initially, I wrote this as: def make_table(x, y, num_bins): ctable = np.zeros((num_bins, num_bins), dtype=np.dtype(int)) for xn, yn in zip(x, y): ctable[xn, yn] += 1 return ctable This works fine, but is so slow that it's eating up like 90% of the runtime of the entire project. The fastest python-only optimization I've been able to come up with is this: def make_table(x, y, num_bins): ctable = np.zeros(num_bins ** 2, dtype=np.dtype(int)) reindex = np.dot(np.stack((x, y)).transpose(), np.array([num_bins, 1])) idx, count = np.unique(reindex, return_counts=True) for i, c in zip(idx, count): ctable[i] = c return ctable.reshape((num_bins, num_bins)) That's (somehow) a lot faster, but it's still pretty expensive for something that doesn't seem like it should be a bottleneck. Are there any efficient ways to do this that I'm just not seeing, or should I just give up and do this in cython? Also, here's a benchmarking function. def timetable(func): size = 5000 bins = 10 repeat = 1000 start = time.time() for i in range(repeat): x = np.random.randint(0, bins, size=size) y = np.random.randint(0, bins, size=size) func(x, y, bins) end = time.time() print("Func {na}: {ti} Ms".format(na=func.__name__, ti=(end - start)))
downvote count: 0
has answer: http://stackoverflow.com/a/51294568
tagged with: python
possible better answer: http://stackoverflow.com/a/76948232
favorite count: 0
accepted answer: http://stackoverflow.com/a/51294568
has answer: http://stackoverflow.com/a/76948232
tagged with: information-theory
has comment: http://stackoverflow.com/comment/89566933
type: AnsweredQuestion
upvote count: 5

http://stackoverflow.com/comment/99255010
type: Comment
has text: The [docs](https://sentinelsat.readthedocs.io/en/stable/api.html?highlight=products_df_sorted) point to using `api.download_all(df.index)` and have been for some time. Where did you find the example using `df['id']` @dave?
type: AnswerComment
comment on: http://stackoverflow.com/a/51280857
score: 0

http://stackoverflow.com/comment/89981529
has text: If you don't have to stick with the arrow key but would accept ENTER or RETURN, too, the easiest way to go would be to simply add "input('press ENTER to continue... ')" at the beginning of the loop
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51396064
type: AnswerComment

http://stackoverflow.com/q/51307550
favorite count: 0
has comment: http://stackoverflow.com/comment/89592324
upvote count: 2
type: UnansweredQuestion
tagged with: python
has title: Issues with counters in while loop Python
score: 0
downvote count: 2
type: Question
has answer: http://stackoverflow.com/a/51307611
tagged with: counter
answer count: 2
tagged with: while-loop
has body: I'm currently having an issue in my code, in which I am attempting to create a rock paper scissors game. My counting method does not seem to work (when the program looped the win loss counters are both on 0), so I was hoping I could get some help. I am fairly new to Python and stack overflow, so bear that in mind. Sorry for the long wall of code: import random import time win=0 loss=0 def compare(): if choice == "rock" and opp == "paper": print("You lose!") loss+1 elif choice == "paper" and opp == "scissors": print("You lose!") loss+1 elif choice== "scissors" and opp == "rock": print("you lose") loss+1 elif choice == "scissors" and opp == "paper": print("you win") win+1 elif choice == "rock" and opp =="scissors": print("you win") win+1 elif choice == "paper" and opp == "rock": print("you win!") win+1 else: print("...") op=["rock","paper","scissors"] phrase=["Rock paper scissors shoot!","janken bo!", "pierre-feuille-ciseaux!","papier, kamień, nożyczki!"] while True: print ("You have",win,"wins and",loss,"losses") choice=input(random.choice(phrase)).lower() if choice not in op: print("Rock paper or scissors") continue else: print() opp=random.choice(op) print (opp) compare() while opp==choice: choice=input(random.choice(phrase)).lower() time.sleep(1) opp=random.choice(op) print (opp) compare() I appreciate any help. Thanks
has answer: http://stackoverflow.com/a/51307597
has comment: http://stackoverflow.com/comment/89591836

http://stackoverflow.com/q/51304809
has answer: http://stackoverflow.com/a/51307695
has body: I want to ‘grow’ a matrix using a set of rules. Example of rules: 0-&gt;[[1,1,1],[0,0,0],[2,2,2]], 1-&gt;[[2,2,2],[2,2,2],[2,2,2]], 2-&gt;[[0,0,0],[0,0,0],[0,0,0]] Example of growing a matrix: [[0]]-&gt;[[1,1,1],[0,0,0],[2,2,2]]-&gt; [[2,2,2,2,2,2,2,2,2],[2,2,2,2,2,2,2,2,2],[2,2,2,2,2,2,2,2,2], [1,1,1,1,1,1,1,1,1],[0,0,0,0,0,0,0,0,0],[2,2,2,2,2,2,2,2,2], [0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0]] This is the code I’ve been trying to get to work in Pytorch rules = np.random.randint(256,size=(10,256,3,3,3)) rules_tensor = torch.randint(256,size=(10, 256, 3, 3, 3), dtype=torch.uint8, device = torch.device('cuda')) rules = rules[0] rules_tensor = rules_tensor[0] seed = np.array(128) seed_tensor = seed_tensor = torch.cuda.ByteTensor(128) decode = np.empty((3**3, 3**3, 3)) decode_tensor = torch.empty((3**3, 3**3, 3), dtype=torch.uint8, device = torch.device('cuda')) for i in range(3): grow = seed grow_tensor = seed_tensor for j in range(1,4): grow = rules[grow,:,:,i].reshape(3**j,-1) grow_tensor = rules_tensor[grow_tensor,:,:,i].reshape(3**j,-1) decode[..., i] = grow decode_tensor[..., i] = grow_tensor I can’t seem to select indices the same way as in Numpy in this line: grow = rules[grow,:,:,i].reshape(3**j,-1) Is there a way to do the following in Pytorch?
tagged with: numpy
tagged with: matrix
answer count: 1
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: python
has title: 2d array as index in Pytorch
tagged with: pytorch
score: 1
upvote count: 1
type: Question
tagged with: indexing

http://stackoverflow.com/comment/89606456
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51314891
type: Comment
has text: this first is working thank you bro

http://stackoverflow.com/q/51198988
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51199407
has comment: http://stackoverflow.com/comment/89383798
downvote count: 1
type: Question
has title: remove , from string via def - tokenized
answer count: 1
has body: Trying to tokenize and strip comma off value current output with def clean(string): result = "" for i,char in enumerate(line): if char == " ": if string[i+1].isdigit() or string[i+1] == " ": continue result += char return result latitude +41.136778, -95.948622 65.000000 red latitude +41.136778, -95.948622 65.000000 red latitude +41.136778, -95.948622 65.000000 blue latitude +41.136778, -95.948622 65.000000 red If I try to add a comma to the string as such: def clean(string): result = "" for i,char in enumerate(line): if char == " ": if string[i+1].isdigit() or or string[i+1] + "," string[i+1] == " ": continue result += char return result I get the following: latitude +41.137342,longitude=-95.947951bar=65.000000foo=23.849165secscolor=red latitude +41.137338,longitude=-95.947936bar=65.000000foo=0.036936secscolor=blue latitude +41.137338,longitude=-95.947936bar=65.000000foo=58.715930secscolor=blue Desired output: latitude +41.136778 longitude bar -95.948622 foo 65.000000 color blue latitude +41.136778 longitude bar -95.948622 foo 65.000000 color red Thanks
score: 0
has answer: http://stackoverflow.com/a/51199407
tagged with: parsing
favorite count: 0
upvote count: 1
tagged with: python

http://stackoverflow.com/q/51254308
type: Question
tagged with: matplotlib
has answer: http://stackoverflow.com/a/51291581
has title: Format matplotlib figure ticks
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python-3.x
has body: I am using matplotlib together with tkinter to display graphs. I am trying to change the format of my y-axis ticks to fit the need of the graph. Here is what I have tried. a.set_title('Ending AUM') a.set_xlabel('Dates') a.set_ylabel('Ending AUM ($)') a.grid(True) a.get_yaxis().set_major_formatter(matplotlib.ticker.FuncFormatter(lambda x, p: format(int(x), ','))) However this formats the ticks to an integer with commas in the thousands marks. Shown here. How would I format this so the y-axis ticks began with a $ and ended with a decimal. Thank you.
accepted answer: http://stackoverflow.com/a/51291581
tagged with: python
score: 2
type: AnsweredQuestion
upvote count: 2

http://stackoverflow.com/comment/89486383
comment on: http://stackoverflow.com/q/51253641
type: Comment
type: QuestionComment
has text: This question calls for a major research effort and is not a good match for SO.
score: 1

http://stackoverflow.com/a/51242567
upvote count: 1
has body: It's straightforward to parse with regexps, using the re module. import re from collections import defaultdict from pprint import pprint data = """ parameters.styleList.0.fill=rgb (255, 0, 0) parameters.styleList.0.key=-2.74, -2.391666666666667 parameters.styleList.0.markerSize=10,10 parameters.styleList.0.stroke=rgb (255, 0, 0) parameters.styleList.0.strokeCapType= parameters.styleList.0.strokeDashArray= parameters.styleList.0.strokeJoinType= parameters.styleList.0.strokeWidth=0.5px parameters.styleList.0.symbol= parameters.styleList.0.title=-2.740 - -2.392 parameters.styleList.1.fill=rgb (255, 85, 0) parameters.styleList.1.key=-2.391666666666667, -2.0433333333333334 parameters.styleList.1.markerSize=10,10 parameters.styleList.1.stroke=rgb (255, 85, 0) parameters.styleList.1.strokeCapType= parameters.styleList.1.strokeDashArray= parameters.styleList.1.strokeJoinType= parameters.styleList.1.strokeWidth=0.5px parameters.styleList.1.symbol= parameters.styleList.1.title=-2.392 - -2.043 """ style_re = re.compile('^parameters\.styleList\.(?P&lt;id&gt;.+?)\.(?P&lt;property&gt;.+?)=(?P&lt;value&gt;.*)$', re.MULTILINE) styles = defaultdict(dict) for match in style_re.finditer(data): id, property, value = match.groups() styles[id][property] = value pprint(dict(styles)) outputs {'0': {'fill': 'rgb (255, 0, 0)', 'key': '-2.74, -2.391666666666667', 'markerSize': '10,10', 'stroke': 'rgb (255, 0, 0)', 'strokeCapType': '', 'strokeDashArray': '', 'strokeJoinType': '', 'strokeWidth': '0.5px', 'symbol': '', 'title': '-2.740 - -2.392'}, '1': {'fill': 'rgb (255, 85, 0)', 'key': '-2.391666666666667, -2.0433333333333334', 'markerSize': '10,10', 'stroke': 'rgb (255, 85, 0)', 'strokeCapType': '', 'strokeDashArray': '', 'strokeJoinType': '', 'strokeWidth': '0.5px', 'symbol': '', 'title': '-2.392 - -2.043'}}
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51242437
score: 1
accepted answer of: http://stackoverflow.com/q/51242437
type: Answer

http://stackoverflow.com/comment/89506650
comment on: http://stackoverflow.com/a/51264130
type: AnswerComment
score: 0
type: Comment
has text: @DineshJosephite: can you post the content of your `pro` variable (together but how you want to render it).

http://stackoverflow.com/comment/89602970
type: Comment
has text: Absolutely fantastic, thanks a lot for your help! Much appreciated! :)
comment on: http://stackoverflow.com/a/51298160
type: AnswerComment
score: 0

http://stackoverflow.com/q/51276877
tagged with: python
accepted answer: http://stackoverflow.com/a/51287192
score: 2
has body: Looking at both function signatures, with arguments tf.train.shuffle_batch_join( tensors_list, batch_size, capacity, min_after_dequeue, seed=None, enqueue_many=False, shapes=None, allow_smaller_final_batch=False, shared_name=None, name=None ) and tf.train.shuffle_batch( tensors, batch_size, capacity, min_after_dequeue, num_threads=1, seed=None, enqueue_many=False, shapes=None, allow_smaller_final_batch=False, shared_name=None, name=None ) the only difference is among the atguments is num_threads that denotes intuitively that tf.train.shuffle_batch could be processed with multiple threads or processes, Except that, they seem to do pretty much the same work. I was wondering if there is a fundamental difference on which someone might choose one over the other except multiprocessing of batches.
type: AnsweredQuestion
upvote count: 2
tagged with: machine-learning
tagged with: tensorflow
type: Question
has title: Difference between tf.train.shuffle_batch_join and tf.train.shuffle_batch
tagged with: pipeline
has answer: http://stackoverflow.com/a/51287192
downvote count: 0
answer count: 1
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/comment/89971884
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51307573
has text: May you run this command *gcloud compute snapshots list --log-http* in your console and confirm the snapshot storageBytes are 0B?? And, **if so**, could you add a piece of your script in order to try to reproduce your issue and answer you properly?
score: 0

http://stackoverflow.com/q/51209000
score: 0
answer count: 1
has body: I have the following function for reading images from the SO: from keras.preprocessing import image as kimage from keras.applications.vgg16 import preprocess_input def read_image(path): img = kimage.load_img(path, target_size=(224, 224)) tmp = kimage.img_to_array(img) tmp = np.expand_dims(tmp, axis=0) tmp = preprocess_input(tmp) return tmp And I create the following data generator that basically iterates my path strings and call the previous function. I want to call read image function and stack its output into a numpy array that I can input to keras fit function. I am using this code: batch_holder = np.zeros((batch_size, 224, 244, 3)) for j, row in batch.iterrows(): batch_holder[j, :] = read_image(row['path'])[0] But this does not work and I am receiving the following error which I consider as impossible to interpret: File "train.py", line 71, in data_generator batch_holder[j, :] = read_image(row['path'])[0] ValueError: could not broadcast input array from shape (224,224,3) into shape (224,244,3) What I am doing wrong?
has answer: http://stackoverflow.com/a/51209263
tagged with: numpy
has title: Keras open images and create a batch with them
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89398968
has comment: http://stackoverflow.com/comment/89399149
tagged with: keras
has comment: http://stackoverflow.com/comment/89399017
type: Question
accepted answer: http://stackoverflow.com/a/51209263
tagged with: python

http://stackoverflow.com/q/51210132
has body: I have used multiprocessing module and created a process, in which I want to access a file and need to write some logs in it. I have specific dependency,that's why i have declared file outside worker function, and from worked function i am able to print and access the file object but was not able to write anything to it. could you please suggest how can i write to that file. import multiprocessing import time file1 = open("files.txt",'w+') def worker(): print "iam called" print file1 file1.write("hello 123") jobs = [] p = multiprocessing.Process(target=worker) jobs.append(p) p.start() time.sleep(10) p.terminate() output: iam called &lt;open file 'files.txt', mode 'w+' at 0x7f5ee8bd7f60&gt;
has answer: http://stackoverflow.com/a/51210638
possible better answer: http://stackoverflow.com/a/51210247
upvote count: 0
has answer: http://stackoverflow.com/a/51210247
answer count: 3
has answer: http://stackoverflow.com/a/51210212
tagged with: python
favorite count: 0
downvote count: 1
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51210212
has title: Not able to write into the file from a process but was able to access the file object using Multiprocessing module
score: -1
tagged with: python-multiprocessing
type: Question

http://stackoverflow.com/comment/89525090
has text: This is also OS-dependent as I imagine you would have to dig into some lower-level soundcard stuff
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51273367

http://stackoverflow.com/comment/89438693
type: QuestionComment
has text: I'm not sure to understand, i should replace my input by a unique one to assign for each embedding ?
score: 0
type: Comment
comment on: http://stackoverflow.com/q/51229446

http://stackoverflow.com/a/51199384
accepted answer of: http://stackoverflow.com/q/51198555
type: AcceptedAnswer
has body: I still do not fully grasp the algorithm, but some mistakes you had: The powers of u start at n and end at 0. For your convolution to work you need to reverse it as you are expecting the coefficients to be in order in the convolution function. Coefficients in the v polynomial only depend on j, not n-j (you use i) Only the first n+1 elements of the convolution are needed (you do not need the powers of n+1...2n. The resulting convolution (it's not really a convolution is it?) is "backwards", as in you final result will start the calculation at i=0, so the power of x**(n-i=n). Putting all of these together: from math import factorial def convolve(f, h): g = [0] * (len(f) + len(h) - 1) for hindex, hval in enumerate(h): for findex, fval in enumerate(f): g[hindex + findex] += fval * hval return g def shift(f, a): n = len(f) - 1 u = [factorial(i)*c for i, c in enumerate(f)][::-1] v = [factorial(n)*a**i//factorial(i) for i in range(n + 1)] g = convolve(u, v) g = [g[n-i]//(factorial(n)*factorial(i)) for i in range(n+1)][::-1] return g f = [1, 2, 3, -4, 5, 6, -7, 8, 9] print(shift(f, 1)) I get [9, 80, 301, 636, 840, 720, 396, 132, 23] I do not know why this is different than your expectation, but I hope this gets you on track.
type: Answer
score: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/89389407
has comment: http://stackoverflow.com/comment/89389350
has comment: http://stackoverflow.com/comment/89388988
answers question: http://stackoverflow.com/q/51198555
upvote count: 3

http://stackoverflow.com/a/51473092
has body: This is possible a common issue when uses VPS. People like me may often forget to setup firewall(s) if the codes are correct. You mentioned that it works locally but not externally. I guess it should be. Digital Ocean level: Add inbound TCP port 5555 in droplet firewall setting System level iptables: e.g. iptables -A INPUT -p tcp -dport 5555 -j ACCEPT firewalld: e.g. firewall-cmd --permanent --zone=public --add-port=5555/tcp Or you may disable OS firewalls by systemctl stop [service-name] or service [service-name] stop. You may google the commands.
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/51199475
has comment: http://stackoverflow.com/comment/90030258
has comment: http://stackoverflow.com/comment/90030192
has comment: http://stackoverflow.com/comment/90030340
has comment: http://stackoverflow.com/comment/90030132
score: 5
upvote count: 5
has comment: http://stackoverflow.com/comment/89997134

aggregation-framework
tags question: http://stackoverflow.com/q/51246163
type: Tag
tag name: aggregation-framework

http://stackoverflow.com/q/51211916
linked to: http://stackoverflow.com/q/30288797
favorite count: 0
tagged with: http://stackoverflow.com/tag/pdf
tagged with: python
answer count: 0
has body: I am new in python and need your help. I am writing a GUI in Python from which I would like to refer to specific pages in a PDF. I can open a PDF on page x following this: Python Open PDF to Bookmark/Named Destination However, I need to give the path to the Acrobat.exe which I image could be problematic when sending my GUI to someone else. Is there a way to open a PDF on page x without setting the file path for Acrobat.exe?
type: UnansweredQuestion
has title: Open PDF on specific page without setting acrobat file path
has comment: http://stackoverflow.com/comment/89409422
has comment: http://stackoverflow.com/comment/89406297
score: 1
type: Question
upvote count: 1
has comment: http://stackoverflow.com/comment/89416492
downvote count: 0

http://stackoverflow.com/q/51260268
has answer: http://stackoverflow.com/a/51260400
answer count: 4
type: Question
has answer: http://stackoverflow.com/a/51260364
tagged with: dataframe
score: 4
has answer: http://stackoverflow.com/a/51260725
tagged with: pandas
downvote count: 1
favorite count: 0
has body: I have the following dataframe import pandas as pd import numpy as np df = pd.DataFrame(data=[['yes',8],['yes',7],['no',np.nan],['yes',7],['no',np.nan]],columns=['passed','score']) Out[8]: passed score 0 yes 8.0 1 yes 7.0 2 no NaN 3 yes 7.0 4 no NaN and I would like to merge the columns passed and score into only 1 column as follow Out[10]: passed 0 yes_8 1 yes_7 2 no 3 yes_7 4 no my attempt is df["passed"].map(str) + '_' + df["score"].map(str) but it is not as clean as I would want could you help me?
upvote count: 5
type: UnansweredQuestion
has title: merge two columns pandas dataframe into one string
tagged with: python
has answer: http://stackoverflow.com/a/51260429

http://stackoverflow.com/q/51282670
has body: i need a help! I have some logs from which is needed to parse/extract some informations. These logs are for different cases and saved in different folders. I made some python script that extract the info's i need but what i want is to be able to give the location of folder/files as argument in script so that i don't need to copy and execute the .py script every time to another folder. The part of code looks like this, ignore all these initialized var's: def peip(*args): split_data = '' split_data1 = '' split_data2 = '' split_data3 = '' split_data4 = '' split_data5 = '' split_data6 = '' split_data7 = '' split_data8 = '' split_data9 = '' split_data10 = '' split_data11 = '' SPU = '' Burst = '' CountRTT_avrg = 0 output = [] Mbps = [] Total_Packets1 = [] output.append('Peip1 Pack., Peip2 Pack., Peip3 Pack., Peip4 Pack., Total Packets, Mbps, SPU Load(%), Average RTT(ms), Burst\n') for arg in args: print "another arg:", arg if arg == 'putty_1_1.log': with open ('putty_1_1' + '.log', mode='r') as a: lines = a.readlines() #lines is list for i, line in enumerate(lines): if line.startswith('^C--'): data = lines[i - 1].strip() split_data = data.split()[4] split_data1 = data.split()[6] print 'PeipX Mbps:', split_data print 'PeipX packets:', split_data1 elif arg == 'putty_1_2_rtt.log': with open ('putty_1_2_rtt' + '.log', mode='r') as b: lines1 = b.readlines() #lines is list for i, line in enumerate(lines1): if line.startswith('rtt'): data = lines1[i].strip() split_data2 = data.split('/')[4] print 'avg rtt/peipX:', split_data2 # ... # ... # ... # and at the end i have calling the function... names = [] Num_of_input_logs = raw_input('Enter the number of input logs: ') #print Num_of_input_logs for z in range(0, int(Num_of_input_logs)): Input_logs = raw_input('Enter the input logs one by one: ') names.append(Input_logs) print names print z peip(*names)
type: UnansweredQuestion
tagged with: python
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/51282785
tagged with: python-2.7
score: 0
answer count: 1
has title: Enter path (as argument) to files that are processed by python script

http://stackoverflow.com/comment/89529839
has text: This solution works, thank you CZoellner. Sorry for can't upvote, not enough reputation.
comment on: http://stackoverflow.com/a/51264958
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/89506208
type: Comment
has text: Welcome, glad to have helped :)
comment on: http://stackoverflow.com/a/51212550
type: AnswerComment
score: 0

http://stackoverflow.com/a/64060484
has body: Here is a Python 3 version of the answer by @eyllanesc using the newer http.server and the threading module import sys import time import threading import webbrowser from http.server import HTTPServer, SimpleHTTPRequestHandler ip = "127.0.0.1" port = 3600 url = f"http://{ip}:{port}" def start_server(): server_address = (ip, port) httpd = HTTPServer(server_address, SimpleHTTPRequestHandler) httpd.serve_forever() threading.Thread(target=start_server).start() webbrowser.open_new(url) while True: try: time.sleep(1) except KeyboardInterrupt: sys.exit(0)
type: Answer
upvote count: 7
score: 7
answers question: http://stackoverflow.com/q/51295378
downvote count: 0

http://stackoverflow.com/q/51245689
score: 8
upvote count: 9
has title: What does epochs mean in Doc2Vec and train when I have to manually run the iteration?
downvote count: 1
type: AnsweredQuestion
type: Question
has body: I am trying to understand the epochs parameter in the Doc2Vec function and epochs parameter in the train function. In the following code snippet, I manually set up a loop of 4000 iterations. Is it required or passing 4000 as epochs parameter in the Doc2Vec enough? Also how epochs in Doc2Vec is different from epochs in train? documents = Documents(train_set) model = Doc2Vec(vector_size=100, dbow_words=1, dm=0, epochs=4000, window=5, seed=1337, min_count=5, workers=4, alpha=0.001, min_alpha=0.025) model.build_vocab(documents) for epoch in range(model.epochs): print("epoch "+str(epoch)) model.train(documents, total_examples=total_length, epochs=1) ckpnt = model_name+"_epoch_"+str(epoch) model.save(ckpnt) print("Saving {}".format(ckpnt)) Also, how and when are the weights updated?
accepted answer: http://stackoverflow.com/a/51256902
answer count: 1
tagged with: doc2vec
favorite count: 0
has answer: http://stackoverflow.com/a/51256902
has comment: http://stackoverflow.com/comment/89478402
tagged with: python
tagged with: gensim

http://stackoverflow.com/comment/89606598
has text: Instead of reassigning to `Df`, you need to concat or join, or assign them explicitly to new columns
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51314984

http://stackoverflow.com/comment/89419459
score: 0
type: AnswerComment
has text: this happens because the django template backend escape all characters in not safe strings. so when you tray to print the var {{ x }} when x is a code expression ( like your code ) you obtain an escape version of the text (**"image.jpg"**). see the **autoescape** configuration in the default template backend https://docs.djangoproject.com/en/2.1/topics/templates/#module-django.template.backends.django
type: Comment
comment on: http://stackoverflow.com/a/51219124

http://stackoverflow.com/comment/89360818
score: 0
type: Comment
has text: This is faster as the code is split but I think this will take a while regardless because of the amount of data. Thank you very much! @Mohammed Kashif
type: AnswerComment
comment on: http://stackoverflow.com/a/51181088

http://stackoverflow.com/a/51207918
type: Answer
answers question: http://stackoverflow.com/q/51207828
score: 0
has body: Just count the laps and compare the current lap with the desired lap. For the xth repetition: counter = 0 while True: if counter == xth: print("This is the xth lap") print('this is one lap') counter += 1

http://stackoverflow.com/comment/93411791
type: QuestionComment
has text: yes I sure did. thanks
comment on: http://stackoverflow.com/q/51197176
score: 0
type: Comment

http://stackoverflow.com/comment/89453015
type: Comment
score: 0
comment on: http://stackoverflow.com/a/51236823
type: AnswerComment
has text: Thanks fort all the information! Regarding the invalidity of an Iterator not returning `self` in `__iter__()`, I actually was following something I found in google's core API: https://github.com/GoogleCloudPlatform/google-cloud-python/blob/master/api_core/google/api_core/page_iterator.py#L216 . Is the invalidity due to the fact that I didn't check if has started? Or is what google has done here considered poor practice?

http://stackoverflow.com/comment/89612108
has text: It would be better to not hard-code the 2. Try to handle `data_1` and `data_2` of any lengths.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51318113

http://stackoverflow.com/comment/89553424
type: AnswerComment
has text: I deleted the answer since I believed the others to better fit what OP required. Didn't your answer work?
type: Comment
comment on: http://stackoverflow.com/a/51272988
score: 0

http://stackoverflow.com/comment/89550473
type: AnswerComment
type: Comment
has text: if i run the above code with only one addition index=False in the first instant i am not getting the output for some of the supplier. the code i am using currently is as for key2 in df['Seller Name'].unique(): dw1 = df[df['Seller Name']==key2] GROUP_LENGTH=1000000 writer=pd.ExcelWriter(key2+'.xlsx') for i in range (0, len(dw1), GROUP_LENGTH): print (i) dw1.iloc[i:i+GROUP_LENGTH,].to_excel(writer, sheet_name=key2+' Row{}'.format(i),index=False)
comment on: http://stackoverflow.com/a/51243367
score: 0

http://stackoverflow.com/q/51275839
upvote count: 1
has comment: http://stackoverflow.com/comment/89529709
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89529737
downvote count: 0
has comment: http://stackoverflow.com/comment/89529623
score: 1
has title: reading arrow keys without Curses module
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89530383
type: Question
tagged with: arrow-keys
has answer: http://stackoverflow.com/a/51276045
tagged with: python
tagged with: module
has comment: http://stackoverflow.com/comment/89529690
has comment: http://stackoverflow.com/comment/89529637
has body: So I am making a program that requires arrow keys but cannot use curses or chr funtion. Is there any simple and easy way to do this? BTW I have already tried inp.key_UP but this does not seem to work. Also I am on mac so gtsrc wont work.
answer count: 2
has answer: http://stackoverflow.com/a/51275979

http://stackoverflow.com/a/51197213
type: Answer
has comment: http://stackoverflow.com/comment/89376435
has comment: http://stackoverflow.com/comment/89376419
score: 1
has body: try this : from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.action_chains import ActionChains browser = webdriver.Chrome(executable_path = r'C:/chromedriver_win32/chromedriver.exe') browser.get("http://mail.google.com") wait = WebDriverWait(browser, 10) user_name = wait.until(EC.element_to_be_clickable((By.ID, 'identifierId'))) user_name.click() user_name.send_keys("samplekeys")
upvote count: 1
has comment: http://stackoverflow.com/comment/89376463
accepted answer of: http://stackoverflow.com/q/51196799
answers question: http://stackoverflow.com/q/51196799
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/51169471
answer count: 1
has comment: http://stackoverflow.com/comment/89321704
favorite count: 0
has answer: http://stackoverflow.com/a/51169995
type: UnansweredQuestion
tagged with: python
has body: I am in need of help with an assignment I have been given. I have been asked to modify the section below from a blackjack game so that a dealer deals a card to each player and the highest card wins unless there is a draw. I am unable to get the code right for this. This is what i have in place: for player in self.still_playing: if player.total > self.players.total: player.win() elif player.total < self.players.total: player.lose() else: player.push() here is the rest of the code: import Cards, Games class BJ_Card(Cards.Card): # Defines a Blackjack card ACE_VALUE = 1 @property def value(self): if self.is_face_up: val = BJ_Card.CARDS.index(self.card) + 1 if val > 10: val = 10 else: val = None return val # This object returns a number between 1 and 10, # representing the value of a Blackjack card class BJ_Deck(Cards.Deck): # Defines a Blackjack deck def populate(self): for suit in BJ_Card.SUITS: for card in BJ_Card.CARDS: self.cards.append(BJ_Card(card, suit)) class BJ_Hand(Cards.Hand): # Defines a Blackjack hand def __init__(self, name): super(BJ_Hand, self).__init__() self.name = name def __str__(self): rep = self.name + ":\t" + super(BJ_Hand, self).__str__() if self.total: rep += "(" + str(self.total) + ")" return rep @property def total(self): # If a card has the value None, then total is None for card in self.cards: if not card.value: return None # Add card values t = 0 for card in self.cards: t += card.value # Check if hand contains an Ace contains_ace = False for card in self.cards: if card.value == BJ_Card.ACE_VALUE: contains_ace = True # treat Ace as 1 contains_ace = 1 return t def is_busted(self): return self.total > 21 class BJ_Player(BJ_Hand): # Defines a Blackjack player def is_hitting(self): response = Games.askYesNo("\n" + self.name + ", do you want another card? (Y/N): ") return response == "y" def bust(self): print(self.name, "busts.") self.lose() def lose(self): print(self.name, "loses.") def win(self): print(self.name, "wins.") def push(self): print(…
downvote count: 1
has comment: http://stackoverflow.com/comment/89322025
type: Question
has comment: http://stackoverflow.com/comment/89322670
has title: Python, modifying a blackjack game
score: -1
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/89322161
upvote count: 0

http://stackoverflow.com/a/51283845
upvote count: 2
type: AcceptedAnswer
downvote count: 0
has body: Found the solution finally. I knew it in is because of the Root/Path. It has nothing to do with admin/sudo stuff. It can be done as follows. for r,d,files in os.walk(my_path): for f in files: print(r) shutil.copy(r + "/" + f, dest_path)
type: Answer
accepted answer of: http://stackoverflow.com/q/51280487
score: 2
answers question: http://stackoverflow.com/q/51280487

http://stackoverflow.com/comment/89434315
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51227065
has text: Thanks Tomas !! The solution given by you produces the expected result.

http://stackoverflow.com/q/51256300
has answer: http://stackoverflow.com/a/51256415
tagged with: python-2.7
answer count: 2
possible better answer: http://stackoverflow.com/a/51256415
has answer: http://stackoverflow.com/a/51256627
score: 0
has body: hey stackoverflow I am needing assistance with this problem. I want to be able to read a text file that is formatted like this: test: value1 test2: value2 test3(sometimes included): value3 test: value1 test2: value2 test: value1 test2: value2 test3(sometimes included): value3 you see test3 is sometimes included in the file and I want to be able to read it but not get it mangled up with the other values in the file. just to make it fully clear I want to be able to read the file in python and put the values of the variables into a string in python. here is what I have so far (this is not what I want because it gets mangled up with other values if the line doesn't have test3) file = open("output.txt").readlines() with line in file: if "test3" in line: test = find_between(...) test2 = find_between(...) test3 = find_between(...) ...
accepted answer: http://stackoverflow.com/a/51256627
tagged with: python
tagged with: text
tagged with: file
type: Question
has title: python read data from file and put values into variables
type: AnsweredQuestion

http://stackoverflow.com/comment/89321569
has text: haggi krey, you're awesome, just drop the "bend2.", with just 'curvature' as attribute name. and the object name is 'bend2'. I tried, and it finally works!
type: Comment
comment on: http://stackoverflow.com/a/51169213
type: AnswerComment
score: 0

http://stackoverflow.com/q/51313214
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/51313294
has answer: http://stackoverflow.com/a/51313294
type: Question
tagged with: for-loop
tagged with: nested-loops
has answer: http://stackoverflow.com/a/51313524
score: 0
answer count: 2
has title: When using a for loop range with an increment of three, why does the first number 'group' to itself?
has body: We are using the following book in a class I am TA-ing for: craftbuzzcoder. In Part 3 (Loop), section Wall &amp; cube, they have a challenge of creating an inverted pyramid. The following is the book solution: for j in range(0,10,3): for i in range (-j, j+1, 3): for k in range(-j, j+1, 3): game.set_block(Position(i, j+1, k), 45) From what I can tell, it seems to be that the first number in the sequence of the respective range (for example, the y-axis/j variable) is counted/grouped by itself rather than by the increment of 3. Why is this? tl;dr I would expect it to increment like this: Instead it seems to be increment like this: Why?
accepted answer: http://stackoverflow.com/a/51313524
tagged with: python

http://stackoverflow.com/comment/89624432
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51305509
type: Comment
has text: What is the type of `constchararrayiwant` ?

http://stackoverflow.com/comment/89558056
type: QuestionComment
score: 0
has text: @jpp sorry for the confusion...see the edits
comment on: http://stackoverflow.com/q/51289898
type: Comment

http://stackoverflow.com/comment/120750043
comment on: http://stackoverflow.com/a/55481248
type: AnswerComment
score: 0
type: Comment
has text: @sam You can just use csaps function or CubicSmoothingSpline class for multivariate case. See the section: https://csaps.readthedocs.io/en/latest/tutorial.html#multivariate-smoothing

http://stackoverflow.com/comment/132628886
score: 0
type: Comment
type: QuestionComment
has text: This **isn't actually a question about Python**; it's a question about the shell. Deciding which words go into which command-line arguments is done by the terminal, **before the program starts**.
comment on: http://stackoverflow.com/q/51255058

http://stackoverflow.com/a/52712543
answers question: http://stackoverflow.com/q/51231852
upvote count: 1
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/51231852
downvote count: 0
score: 1
has body: I am not sure about the specific error you are getting but, in this case, you can iterate over a batch by using the following code: for i in train_iter: print i.Tweet print i.Anger print i.Fear print i.Joy print i.Sadness i.Tweet (also others) is a tensor of shape (input_data_length, batch_size). So, to view a single batch data (lets say batch 0), you can do print i.Tweet[:,0]. Same goes for val_iter (and test_iter, if needed).

experimental-design
type: Tag
tag name: experimental-design
tags question: http://stackoverflow.com/q/51321595
tags question: http://stackoverflow.com/q/51191964

http://stackoverflow.com/q/51243498
has title: Get individual listbox item properties in tkinter using itemcget?
tagged with: python
type: AnsweredQuestion
score: 1
type: Question
tagged with: listbox
accepted answer: http://stackoverflow.com/a/51244076
tagged with: colors
upvote count: 1
has body: I wrote the below code to bind event and do operations on individual listbox items. import tkinter as tk root = tk.Tk() custom_list = tk.Listbox(root) custom_list.grid(row=0, column=0, sticky="news") def onselect_listitem(event): w = event.widget index = int(w.curselection()[0]) value = w.get(index) print(index, value, " color : ",custom_list.itemcget(index,'background')) custom_list.itemconfig(index, fg='gray', selectforeground="gray") custom_list.bind('&lt;Double-Button-1&gt;', onselect_listitem) for k in range(20): custom_list.insert(k, " --------- " + str(k)) root.mainloop() I am having trouble using itemcget to get the background properties while itemconfig works properly. Everything else is working. Can someone tell me if there is something wrong? I am trying to obtain the current item background color via index of the item in the listbox. The part with custom_list.itemcget doesn't print anything. Thanks
answer count: 1
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/51244076
tagged with: tkinter

http://stackoverflow.com/comment/89344796
comment on: http://stackoverflow.com/q/51180949
score: 0
has text: Fixed the styling errors. I still have no idea how to start this second smallest function.I can only have one input which is the list if that matters.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51237910
type: UnansweredQuestion
score: -3
tagged with: python
linked to: http://stackoverflow.com/q/5755023
has body: class Local(object): __slots__ = ('__storage__', '__ident_func__') def __init__(self): object.__setattr__(self, '__storage__', {}) object.__setattr__(self, '__ident_func__', get_ident) def __call__(self, proxy): """Create a proxy for a name.""" return LocalProxy(self, proxy) def __getattr__(self, name): try: return self.__storage__[self.__ident_func__()][name] except KeyError: raise AttributeError(name) def __setattr__(self, name, value): ident = self.__ident_func__() storage = self.__storage__ try: storage[ident][name] = value except KeyError: storage[ident] = {name: value} def __delattr__(self, name): try: del self.__storage__[self.__ident_func__()][name] except KeyError: raise AttributeError(name) I want to know the difference between __setattr__ magic function and self.__xxx__ = {}. Now I put more code here.In the constructor,it's object.setattr.So does the overwritten have some influence to it ?
downvote count: 3
type: Question
has comment: http://stackoverflow.com/comment/89454787
has answer: http://stackoverflow.com/a/51237960
has comment: http://stackoverflow.com/comment/89454735
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/89454818
favorite count: 0
has comment: http://stackoverflow.com/comment/89454758
has comment: http://stackoverflow.com/comment/89456442
has title: What's the meaning of the __setattr__ in this Python code?

http://stackoverflow.com/q/51313649
answer count: 1
favorite count: 0
tagged with: python-3.x
has body: Hello I would like to ask if is possible to update my app with a socket server like in other apps when there is an update so its downloading and updating the code without downloading the app again
tagged with: python
has answer: http://stackoverflow.com/a/51313884
type: AnsweredQuestion
upvote count: 1
tagged with: updates
downvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/51313884
has title: UPDATE my script in python with python socket
score: 0

http://stackoverflow.com/q/51304684
has comment: http://stackoverflow.com/comment/89586701
type: AnsweredQuestion
has body: I need to digitize some values such that the index returned is the "floor" or "ceiling" bin. E.g., for bins = numpy.array([0.0, 0.5, 1.0, 1.5, 2.0]) and a value 0.2 I expect the index to be 0, for a value 0.26 the index returned should be 1, and so on. I have the following ugly looking function to do what I want: import numpy def get_bin_index(value, bins): bin_diff = bins[1]-bins[0] index = numpy.digitize(value, bins) if bins[index] - value &gt; bin_diff/2.0: index -= 1 return index Is there any neat (read better/efficient) way to do this? Edit: Including timing values (just satisfying my curiosity!) In [1]: def get_bin_index(value, bins): ...: bin_diff = bins[1]-bins[0] ...: index = numpy.digitize(value, bins) ...: if bins[index] - value &gt; bin_diff/2.0: ...: index -= 1 ...: return index ...: In [2]: def get_bin_index_c(value, bins): ...: return numpy.rint((value-bins[0])/(bins[1]-bins[0])) ...: In [3]: def get_bin_index_mid_digitized(value, bins): ...: return numpy.digitize(0.6, (bins[1:] + bins[:-1])/2.0) ...: In [4]: bin_halfs = numpy.array([0.0, 0.5, 1.0, 1.5, 2.0]) In [5]: %timeit get_bin_index(0.9, bin_halfs) The slowest run took 5.71 times longer than the fastest. This could mean that an intermediate result is being cached. 1000000 loops, best of 3: 4.93 µs per loop In [6]: %timeit get_bin_index_c(0.9, bin_halfs) The slowest run took 14.60 times longer than the fastest. This could mean that an intermediate result is being cached. 100000 loops, best of 3: 2.34 µs per loop In [7]: %timeit get_bin_index_mid_digitized(0.9, bin_halfs) The slowest run took 4.09 times longer than the fastest. This could mean that an intermediate result is being cached. 100000 loops, best of 3: 8.37 µs per loop
has comment: http://stackoverflow.com/comment/89586737
tagged with: numpy
answer count: 2
possible better answer: http://stackoverflow.com/a/51305444
score: 0
tagged with: python
has title: Digitizing value to "floor" bin python
has comment: http://stackoverflow.com/comment/89586831
tagged with: digitization
accepted answer: http://stackoverflow.com/a/51308143
has answer: http://stackoverflow.com/a/51305444
has comment: http://stackoverflow.com/comment/89586916
type: Question
has answer: http://stackoverflow.com/a/51308143

http://stackoverflow.com/q/51196438
has answer: http://stackoverflow.com/a/56590572
has comment: http://stackoverflow.com/comment/91105312
type: Question
tagged with: numpy
upvote count: 13
has answer: http://stackoverflow.com/a/51206339
favorite count: 0
tagged with: python-xarray
answer count: 3
has answer: http://stackoverflow.com/a/73966302
tagged with: python
has body: This seems like a very basic operation, but I can't figure out how to do it using the xarray documentation. I have an xarray DataSet: dss &lt;xarray.DataArray (y: 1000, x: 1334)&gt; dask.array&lt;shape=(1000, 1334), dtype=uint8, chunksize=(222, 58)&gt; Coordinates: band int32 1 * y (y) float64 2.218e+06 2.218e+06 2.218e+06 2.218e+06 2.218e+06 ... * x (x) float64 1.891e+06 1.891e+06 1.891e+06 1.891e+06 1.891e+06 ... Attributes: transform: (30.0, 0.0, -2493045.0, 0.0, -30.0, 3310005.0, 0.0, 0.0, 1.0) crs: +ellps=GRS80 +lat_0=23 +lat_1=29.5 +lat_2=45.5 +lon_0=-96 +n... res: (30.0, 30.0) is_tiled: 1 nodatavals: (nan,) and a numpy array with the correct dimensions: print(np.shape(nmap)) (1000, 1334) nmap array([[ 0.15, 0.1 , 0.15, ..., 0.05, 0.05, 0.02], [ 0.15, 0.1 , 0.05, ..., 0.05, 0.05, 0.05], [ 0.1 , 0.15, 0.15, ..., 0.05, 0.05, 0.02], ..., [ 0.02, 0.02, 0.02, ..., 0.02, 0.02, 0.02], [ 0.02, 0.09, 0.09, ..., 0.02, 0.02, 0.02], [ 0.02, 0.09, 0.09, ..., 0.02, 0.02, 0.02]]) I would like to add the array to the DataSet. My ultimate goal is to do spatial interpolation using x and y to extract interpolated values of nmap on a new grid.
downvote count: 0
type: UnansweredQuestion
has title: Add numpy array as variable to Xarray Dataset
score: 13

http://stackoverflow.com/comment/89381123
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/51199492
type: Comment
has text: I didn't see your code, and darn, I use it and it works, I'm going to check the differences to learn. Thank you!

http://stackoverflow.com/comment/96562331
score: 1
has text: No solution for hosted UI.
type: Comment
comment on: http://stackoverflow.com/q/51256302
type: QuestionComment

http://stackoverflow.com/a/64895190
score: 0
answers question: http://stackoverflow.com/q/51190561
has body: I assume you only need the inner spots inside a leaf. Segment using the otsu algorithm apply the flood-fill operation to ensure you capture all leaf pixels Extract only the inner contour All can simply be done using opencv below are the codes: import cv2 import numpy as np def flood_fill_binary(binary): hh = binary.shape[0] ww = binary.shape[1] xx = 10 yy = 10 black = [0,0,0] binary = cv2.copyMakeBorder(binary,10,10,10,10,cv2.BORDER_CONSTANT,value=black) im_floodfill = binary.copy() h, w = binary.shape[:2] mask = np.zeros((h+2, w+2), np.uint8) cv2.floodFill(im_floodfill, mask, (0,0), 255) im_floodfill_inv = cv2.bitwise_not(im_floodfill) im_out = binary | im_floodfill_inv crop_og = im_out[yy:yy+hh,xx:xx+ww] return crop_og def leaf_spots_detector(image): image = image.astype('uint8') hh = image.shape[0] ww = image.shape[1] xx = 10 yy = 10 #kernel = np.ones((3,3),np.uint8) grayed_image = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY) _, segmented = cv2.threshold(grayed_image,0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU) segmented = flood_fill_binary(segmented) segmented = cv2.copyMakeBorder(segmented,xx,xx,yy,yy,cv2.BORDER_CONSTANT,value= [0,0,0]) major = cv2.__version__.split('.')[0] if major == '3': ret, contours, hierarchy = cv2.findContours(segmented, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) else: contours, hierarchy = cv2.findContours(segmented, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) print(hierarchy.shape) image_external = np.zeros(segmented.shape, segmented.dtype) for i in range(1,len(contours)): #if hierarchy[0][i][3] == -1: cv2.drawContours(image_external, contours, i,(225,255,255), -1) image_external = image_external[yy:yy+hh,xx:xx+ww] #image_external = cv2.dilate(image_external,kernel,iterations = 1) return image_external image = cv2.imread('image/path.png') leaf_spots = leaf_spots_detector(image) cv2.imshow("detected spots", leaf_spots) cv2.waitKey(0) cv2.destroyAllWindow()
type: Answer

http://stackoverflow.com/comment/89404333
type: Comment
comment on: http://stackoverflow.com/a/51211536
has text: You want output be hello, megan(seperated by comma)?
type: AnswerComment
score: 0

http://stackoverflow.com/comment/89479345
has text: @chepner: There’s no reuse here, though.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/51250214
score: 0

http://stackoverflow.com/a/51289000
upvote count: 3
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51288942
answers question: http://stackoverflow.com/q/51288942
type: AcceptedAnswer
has body: You can just use str.split(' ', expand=True) to split on the space, and then join with the Image Column: new_df = df'Image'.join(df['Bounding Boxes'].str.split(' ', expand=True)) &gt;&gt;&gt; new_df Image 0 1 2 3 4 5 6 7 8 9 0 a.jpg xyz 0.1 0.2 0.3 0.4 None None None None None 1 b.jpg xyz 0.1 0.2 0.3 0.4 ijk 0.4 0.3 0.2 0.1 You can rename your columns as you see fit after that, using either new_df.columns = ['my', 'list', 'of', 'column', 'names'] or new_df.rename(columns={'old column name':'desired column name'})
type: Answer
score: 3

http://stackoverflow.com/q/51280742
has body: My code looks like this: import requests #grabs HTML from remote file from bs4 import BeautifulSoup #core scraping module import csv #prints results to a file import time #adds delay and avoid overloading host server from urllib.request import urlopen # create file to hold scraped data. artist_csv_file = open('artist_data.csv', 'w') csv_writer = csv.writer(artist_csv_file) # nominate header columns for the CSV csv_writer.writerow(['date_text', 'artist', 'track', 'url']) # read in a list of URLs to scrap (testing with 3 of 500+ pages) contents = [] with open('Rage-links.csv','r') as csvf: # Open file in read mode urls = csv.reader(csvf) for url in urls: page = urlopen(url[0]).read() rage = BeautifulSoup(page, 'html.parser') # identify page section with artist and track names playlist = rage.find('div', class_='comp-rich-text article-text clearfix') # open a CSV file to collect results. And set file's column headers artist_csv_file = open('artist_data.csv', 'w') csv_writer = csv.writer(artist_csv_file) csv_writer.writerow(['date_text', 'artist', 'track', 'url']) # capture date from the page rage_date = rage.find('div', class_='view-comp-publish-date') date_text = rage_date.time.text # define the artist and define song title as its sibling artist = playlist.find('strong') # track = playlist.strong.next_sibling # loop through the HTML, write date, artist and track data. for artist in playlist.find_all('strong'): print(date_text) print(artist) print(artist.next_sibling) print(url) time.sleep(.1) # delay scrape for .1 seconds csv_writer.writerow([date_text, artist, artist.next_sibling, url]) # close the CSV file artist_csv_file.close() All of the data prints to screen, but only a portion of it arrives in my CSV file. I'm a novice, so any help appreciated. I wonder if I'm trying to capture too much data at once as in this post (Pandas prints to screen corrently but saves only some data to csv) but the explanation is beyond my skill level.
accepted answer: http://stackoverflow.com/a/51281187
type: Question
has title: BeautifulSoup scraped data prints to screen but won't save
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/51281187
tagged with: beautifulsoup
has comment: http://stackoverflow.com/comment/89539099
linked to: http://stackoverflow.com/q/32531058
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/a/51274758
downvote count: 0
has comment: http://stackoverflow.com/comment/89527784
answers question: http://stackoverflow.com/q/51273582
type: Answer
has body: The evaluate() method evaluates the model on the whole data you pass to it and therefore the given loss value and the metric(s) value(s) are based on the performance of the model on the whole data. Further, there is another method called test_on_batch() which tests the model on a single batch of data and returns the corresponding loss value and metric(s) value(s) of the model on the given data batch. However, I am not sure what you mean by saying "I have a large cross validation data set which kind of requires me to call the evaluate function several times..." (emphasize mine). Do you mean the whole validation data does not fit in memory? If that's the case, and you have stored the validation data in a file on the disk (say a h5py file), then you can define a generator and use evaluate_generator() method to perform evaluation using the generator you have defined.
score: 1
has comment: http://stackoverflow.com/comment/89527747
upvote count: 1
has comment: http://stackoverflow.com/comment/89527984
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51273582

http://stackoverflow.com/comment/89585444
has text: i think the problem is in that you assert in code that you have in dict keys like "start" and "end" but when you don't have them, you have a error... you need check have your dict a key or not. you can do this: if "some_need_key" in name_of_dict
type: Comment
comment on: http://stackoverflow.com/a/51304082
score: 0
type: AnswerComment

http://stackoverflow.com/q/51210342
type: Question
score: 0
answer count: 1
has title: changing index in other datetime format in python
favorite count: 0
tagged with: pandas
has answer: http://stackoverflow.com/a/51210850
tagged with: python
has body: I'm new to Python, I hope my question isn't to silly... I want to join to pandas DataFrame (f1 and f3) and it seems that the indices are different. f1: DatetimeIndex(['2018-01-01', '2018-01-02', '2018-01-03', '2018-01-04', '2018-01-05', '2018-01-06', '2018-01-07', '2018-01-08', '2018-01-09', '2018-01-10', ... '2018-12-22', '2018-12-23', '2018-12-24', '2018-12-25', '2018-12-26', '2018-12-27', '2018-12-28', '2018-12-29', '2018-12-30', '2018-12-31'], dtype='datetime64[ns]', name='date', length=365, freq=None) f3: Index([2018-01-01, 2018-01-02, 2018-01-07, 2018-03-30, 2018-04-01, 2018-04-02, 2018-05-01, 2018-05-10, 2018-05-20, 2018-05-21, 2018-06-04, 2018-08-01, 2018-12-25, 2018-12-26], dtype='object') Now if I join them in order cat = [f1, f3] with cat_total = pd.concat(cat, axis=1, sort=False) it seems to work and the correct result looks like this: print(cat.head()) weekday holidays 2018-01-01 0 Neujahrestag 2018-01-02 1 Berchtoldstag 2018-01-03 2 NaN 2018-01-04 3 NaN 2018-01-05 4 NaN If I change to order of cat like cat = [f3, f1] it doesn't work properly... print(cat) holidays weekday 2018-01-01 Neujahrestag 0 2018-01-02 Berchtoldstag 1 2018-01-07 Test ZH 1 6 2018-03-30 Karfreitag 4 2018-04-01 Ostern 6 2018-04-02 Ostermontag 0 2018-05-01 Tag der Arbeit 1 2018-05-10 Auffahrt 3 2018-05-20 Pfingsten 6 2018-05-21 Pfingstmontag 0 2018-06-04 Test ZH 2 0 2018-08-01 Nationalfeiertag 2 2018-12-25 Weihnachten 1 2018-12-26 Stephanstag 2 2018-01-01 00:00:00 NaN 0 2018-01-02 00:00:00 NaN 1 2018-01-03 00:00:00 NaN 2 2018-01-04 00:00:00 NaN 3 2018-01-05 00:00:00 NaN 4 2018-01-06 00:00:00 NaN 5 2018-01-07 00:00:00 NaN 6 Why is that like this? How can I change one of the indices of the pandas DataFrame that the formats are the same? The f1-index arises from dates = pd.date_range(start = startdate, end = enddate, freq = 'D') and the f3-one is the result of the external package 'holidays' I hope these are all infos needed. Thanks a lot in advance Marco
upvote count: 1
downvote count: 1
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51210850
tagged with: dataframe
tagged with: date

http://stackoverflow.com/q/51212744
answer count: 1
tagged with: numpy
has title: How can I save multiple images with labels in a numpy array?
tagged with: numpy-ndarray
has answer: http://stackoverflow.com/a/51213048
type: AnsweredQuestion
type: Question
tagged with: multidimensional-array
has body: Previously this type of questions was asked. But my one is a little different. For example, I have 20 files ( 20 matrix ) in one folder, each of the matrix is 40*40 in dimension. Also, these 20 files represent 20 different categories. Now I want to create one single Numpy array, where the length will be 20*2. In the first column of each row, I want to store a 40*40 matrix. Thus all the 20 files I want to cover. Then I want to keep the labels as number e.g. 1,2,3 .... 20. later on, when I will call the createdNumpyArray[0,0], it should show the first matrix. How to do this in Python?
tagged with: python
accepted answer: http://stackoverflow.com/a/51213048
score: 0

http://stackoverflow.com/a/51245344
has body: You can use operator.itemgetter for this from operator import itemgetter f = itemgetter(0, 3) f(myList) # ('Sprite', '7up')
answers question: http://stackoverflow.com/q/51245098
type: Answer
score: 0

http://stackoverflow.com/q/51252852
type: Question
tagged with: flask-ask
tagged with: python
has body: I am developing a Web Service using python that would operate as the backend logic for a custom Alexa Skill. I am using the flask, flask-ask(Alexa Skill Kit), and MySQL extensions to develop this Web Service. This Alexa Skill would allow users to reserve parking spots, check if lots are full, and find parking spots. I also have a local database where all parking related information is stored. I'm having an issue where I am only able to return the first result of a query. Here is the code for one of my intents: '''This is a Web Service for the *** Parking skill''' author__ = '*****' import logging from flaskext.mysql import MySQL from flask import Flask, render_template from flask_ask import Ask, statement, question mysql = MySQL() app = Flask(__name__) app.config.from_object(__name__) app.config['MYSQL_DATABASE_USER'] = '*****' app.config['MYSQL_DATABASE_PASSWORD'] = '*****' app.config['MYSQL_DATABASE_DB'] = '*****' app.config['MYSQL_DATABASE_HOST'] = '*****' mysql.init_app(app) ask = Ask(app, "/") logging.getLogger("flask_ask").setLevel(logging.DEBUG) @ask.intent('AvailableParking') def available(occupancy): #converts the inputted occupancy variable into all caps, to match the DB schema occupancy = occupancy.upper() #creates cursor variable that connects to DB cursor = mysql.connect().cursor() #connects to db and executes SQL query that displays all garages where the OCCUPANCY field matches the users slot input (OPEN OR CLOSED) cursor.execute("SELECT GARAGE_NAME FROM GARAGES WHERE OCCUPANCY = %s", (occupancy,)) #returns the first row of the query results data = cursor.fetchone() data = data[0] return statement(data) This works as intended. Alexa says "Lot A" when triggering the intent, even thought there are 3 parking lots in total. I thought to use the MySQL method cursor.fetchall() in place of cursor.fetchone, like so: data = cursor.fetchall() return statement(data) But I receive the error: Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-pa…
has title: Returning All Query Results to Alexa Skill
tagged with: alexa-skills-kit
score: 0
tagged with: mysql
answer count: 1
type: UnansweredQuestion
tagged with: flask
has answer: http://stackoverflow.com/a/51270011

http://stackoverflow.com/comment/89368999
comment on: http://stackoverflow.com/q/51192310
score: 0
type: Comment
type: QuestionComment
has text: Message me. That s some other

http://stackoverflow.com/q/51270345
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/51290091
tagged with: tkinter
type: Question
has body: My GUI program built with tkinter has the following main part. if __name__ == '__main__': root = Tk() my_gui = DataExtractorUI(root) root.mainloop() The DataExtractor calls another function on button click. The said function has multi-processing tasks inside. The GUI was working perfectly when run from command line. When compiling to exe using pyinstaller or cx_Freeze, the program keeps on spawning windows 1+number of processes and doesn't work as expected. Following in my pyinstaller spec file: # -*- mode: python -*- block_cipher = None a = Analysis(['MainGUI.py'], pathex=['.'], binaries=[], datas=[('logo/m3_logo.png', 'logo')], hiddenimports=[], hookspath=[], runtime_hooks=[], excludes=[], win_no_prefer_redirects=False, win_private_assemblies=False, cipher=block_cipher) pyz = PYZ(a.pure, a.zipped_data, cipher=block_cipher) exe = EXE(pyz, a.scripts, exclude_binaries=True, name='MainGUI', debug=False, strip=False, upx=True, console=False ) coll = COLLECT(exe, a.binaries, a.zipfiles, a.datas, strip=False, upx=True, name='MainGUI') I had the same problem with the command line version in the beginning which was solved by adding if __name__ == "__main__" With the exe packing tool, it's not clear to me why it's bypassing the __main__ entry point.
has title: GUI program breaking with pyinstaller & cx_Freeze
tagged with: python-multiprocessing
score: 0
answer count: 1
tagged with: cx-freeze
linked to: http://stackoverflow.com/q/33970690
tagged with: pyinstaller

http://stackoverflow.com/comment/129183174
score: 0
comment on: http://stackoverflow.com/a/51285612
has text: Nope, I was in time crunch so switched to tkinter to make it work.
type: Comment
type: AnswerComment

cython
tags question: http://stackoverflow.com/q/51311521
tags question: http://stackoverflow.com/q/51268841
tags question: http://stackoverflow.com/q/51187592
tags question: http://stackoverflow.com/q/51272170
tags question: http://stackoverflow.com/q/51284315
tags question: http://stackoverflow.com/q/51268202
type: Tag
tags question: http://stackoverflow.com/q/51245056
tag name: cython
tags question: http://stackoverflow.com/q/51205793
tags question: http://stackoverflow.com/q/51177099
tags question: http://stackoverflow.com/q/51311233
tags question: http://stackoverflow.com/q/51263233
tags question: http://stackoverflow.com/q/51284438

http://stackoverflow.com/a/51271268
upvote count: 1
type: Answer
downvote count: 0
has body: Most typically, text is passed to Word2Vec in logical units (like sentences or paragraphs). Also, the published papers and early demo code tended to convert punctuation into tokens, as well. But text without punctuation, and arbitrary breaks between texts, are a reasonable workaround and still give pretty good results. For example, the text8/text9 corpuses often used in demos (including the word2vec intro Jupyter notebook bundled in gensim) are just giant runs-of-words, lacking punctuation and line-breaks. So, the utility LineSentence class used in gensim will break them into individual 10,000-token texts. It's probably better to go larger in your arbitrary breaks (eg 10,000), rather than smaller (eg 10), for a couple reasons: source texts are usually longer than 10 words often the source material that was run-together was still semantically-related across its original boundaries the optimized algorithms work better on larger chunks of data the harm of "false context windows" (created by the concatenation) is probably just noise with no net biasing effect, while more "true windows" (by creating as few false splits as possible) likely retains more of the original corpus' learnable word-to-word relationships signal you can always simulate more-conservative contexts with a smaller window parameter (if the original source really did have tiny sentences that weren't sequentially-related) But, gensim's cython-optimized training path has an implementation limit of 10,000 tokens per text – with any more being silently ignored – so you wouldn't intentionally want to supply longer texts for any reason.
score: 1
answers question: http://stackoverflow.com/q/51269058

http://stackoverflow.com/comment/89390723
type: Comment
comment on: http://stackoverflow.com/q/51204269
type: QuestionComment
score: 0
has text: Probably not the answer you are looking for, but preprocessing your inputs with `val %= 2 * numpy.pi` would probably do the trick.

http://stackoverflow.com/q/51252120
has answer: http://stackoverflow.com/a/51252503
has comment: http://stackoverflow.com/comment/89485190
tagged with: hdf5
has comment: http://stackoverflow.com/comment/89483446
has comment: http://stackoverflow.com/comment/89483827
type: Question
has answer: http://stackoverflow.com/a/51300707
has comment: http://stackoverflow.com/comment/89483740
score: 0
answer count: 2
has title: updating hdf5 data on simple calibration
has comment: http://stackoverflow.com/comment/89495886
tagged with: python-3.x
tagged with: h5py
has body: I am trying to update hdf5 file data which needs calibration. The code which I have added is: with h5py.File(fileName,'r+') as hf: keys=hf.keys() data = hf[key][...] hf[key][...] = data*calibration_factor Just for the simple calibration. However, its resulting to all zero in hf[key][...]. When I am assigning the product on the right side to a variable, I am getting the result properly. The dtype of data is int16. Any possible solution for this? I am struggling a lot on this,thanks for understanding. This question I have posted as an add-on to another question, but as its separate hence created a new question here. Please don't mark it as duplicate.
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89483555

http://stackoverflow.com/a/51255282
upvote count: 3
score: 3
answers question: http://stackoverflow.com/q/51255237
has body: The random integers generated need not be unique. Consequently, the same indices are getting set to 1 multiple times. I am sure you would get different sums everytime you run it. You can use random.sample(range(0,80), 30) to generate 30 unique indices in the range. Doc
downvote count: 0
type: Answer

http://stackoverflow.com/q/51197695
tagged with: python-2.7
has title: Static methods for recursive functions within a class?
accepted answer: http://stackoverflow.com/a/51197911
favorite count: 0
upvote count: 1
tagged with: python
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/51197911
possible better answer: http://stackoverflow.com/a/51197809
type: Question
has answer: http://stackoverflow.com/a/51197809
answer count: 2
downvote count: 0
has body: I'm working with nested dictionaries on Python (2.7) obtained from YAML objects and I have a couple of questions that I've been trying to get an answer to by reading, but have not been successful. I'm somewhat new to Python. One of the simplest functions is one that reads the whole dictionary and outputs a list of all the keys that exist in it. I use an underscore at the beginning since this function is later used by others within a class. class Myclass(object): @staticmethod def _get_key_list(d,keylist): for key,value in d.iteritems(): keylist.append(key) if isinstance(value,dict): Myclass._get_key_list(d.get(key),keylist) return list(set(keylist)) def diff(self,dict2): keylist = [] all_keys1 = self._get_key_list(self.d,keylist) all_keys2 = self._get_key_list(dict2,keylist) ... # More code Question 1: Is this a correct way to do this? I am not sure whether it's good practice to use a static method for this reason. Since self._get_key_list(d,keylist) is recursive, I dont want "self" to be the first argument once the function is recursively called, which is what would happen for a regular instance method. I have a bunch of static methods that I'm using, but I've read in a lot of places thay they could perhaps not be good practice when used a lot. I also thought I could make them module functions, but I wanted them to be tied to the class. Question 2: Instead of passing the argument keylist to self._get_key_list(d,keylist), how can I initialize an empty list inside the recursive function and update it? Initializing it inside would reset it to [] every time.

openblas
tags question: http://stackoverflow.com/q/51256738
tag name: openblas
type: Tag
tags question: http://stackoverflow.com/q/51179118

http://stackoverflow.com/q/51221836
tagged with: pip
tagged with: scrapy
has answer: http://stackoverflow.com/a/53141948
type: Question
answer count: 2
score: 0
tagged with: python
has answer: http://stackoverflow.com/a/51221957
has body: I already have anaconda installed version 4.5.4, i went to the cmd to install scrapy referring to the docs pip install Scrapy and got the following error: error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools": http://landinghub.visualstudio.com/visual-cpp-build-tools I tried going to that link but they just give me error 404 page not found.
has title: Issues installing Scrapy on windows
type: UnansweredQuestion

http://stackoverflow.com/comment/89637797
score: 0
type: Comment
type: AnswerComment
has text: Yeah. I get that <function main.ACCESS.<locals>.ACCESS_LAMBDA()> when I execute "ACCESS(dic,'a','b','c')". When executing "print ABC_ACCESS()", I get File "<ipython-input-53-0685598597d5>", line 19 print ABC_ACCESS() ^ SyntaxError: invalid syntax
comment on: http://stackoverflow.com/a/51314215

http://stackoverflow.com/q/51299411
type: UnansweredQuestion
tagged with: python
upvote count: 2
has answer: http://stackoverflow.com/a/51340187
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/89645607
score: 1
answer count: 1
has title: I want my app.db to be automatically created inside a package folder, every time I command migrate
tagged with: flask
tagged with: flask-sqlalchemy
has comment: http://stackoverflow.com/comment/89610643
favorite count: 0
tagged with: python-3.x
has body: this is my directory hotel/ ___grandluis/ ______main/ ______static/ ______templates/ ______users/ ______config.py ______models.py ___migrations/ ______versions/ ___run.py ___app.db My problem is I want my app.db to be inside of grandluis folder. because every time I run python run.py db migrate. my app.db gets created outside of grandluis folder and when I add something to my database through my app it creates another app.db inside the grandluis folder. I'ts like my flask app only reads the app.db which is inside the grandluis folder not the one which is outside of grandluis folder. Because It can cause an error. It says that there's no SQLAlchemy.model that has been created. Because my app only read the app.db which is inside of grandluis. So I want that every time I command migrate, I want that it will create/affect the app.db which is inside my grandluis folder. I really want some Answers guys Thank you so much for having time to read this ridiculous question of mine. --models.py-- from datetime import datetime from itsdangerous import TimedJSONWebSignatureSerializer as Serializer from flask import current_app from grandluis import db, loginManager from flask_login import UserMixin @loginManager.user_loader def load_user(user_id): return User.query.get(int(user_id)) class User(db.Model, UserMixin): UserId = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(300), nullable=False) address = db.Column(db.String(100), nullable=False) contact = db.Column(db.String(100), nullable=False) email = db.Column(db.String(120), unique=True, nullable=False) username = db.Column(db.String(20), unique=True, nullable=False) password = db.Column(db.String(60), nullable=False) class Room(db.Model): roomId = db.Column(db.Integer, primary_key=True) roomNum = db.Column(db.String(100), nullable=False) roomType = db.Column(db.String(100), nullable=False) roomPrice = db.Column(db.Integer, nullable=False) roomStatus = db.Column(db.String(100), nullable=False) class Meals(db…

http://stackoverflow.com/comment/89554777
score: 1
has text: I THINK that `global xxx` is just a redundant statement but since its a valid python code the python interpreter merely ignores it like a mother ignores your childish mistakes. I could be wrong though.
comment on: http://stackoverflow.com/q/51288447
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89381804
type: QuestionComment
score: 0
has text: Your question would be better if you removed about 90% of the code. Do you really need to call `findARestaurant` nine times in order to duplicate this error?
type: Comment
comment on: http://stackoverflow.com/q/51198673

http://stackoverflow.com/comment/89577796
type: Comment
has text: The external code is inspecting the function signature and changes its behaviour accordingly?
comment on: http://stackoverflow.com/q/51299787
score: 0
type: QuestionComment

http://stackoverflow.com/comment/89413225
has text: You probably don't need `enumerate` here. You want to iterate over `range` objects directly, not enumerated `range` objects.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51216002

http://stackoverflow.com/a/51250339
type: Answer
answers question: http://stackoverflow.com/q/51250210
score: 3
upvote count: 3
has body: When you call df.iloc[0], it is selecting first row and type is Series whereas, in other case df.iloc[0:0] it is slicing rows and is of type dataframe. And Series are according to pandas Series documentation : One-dimensional ndarray with axis labels whereas dataframe are Two-dimensional (pandas Dataframe documentation). Try running following lines to see the difference: print(type(df.iloc[0])) # &lt;class 'pandas.core.series.Series'&gt; print(type(df.iloc[0:0])) # &lt;class 'pandas.core.frame.DataFrame'&gt;
downvote count: 0

http://stackoverflow.com/q/51250706
has title: Combining semaphore and time limiting in python-trio with asks http request
has answer: http://stackoverflow.com/a/52635077
accepted answer: http://stackoverflow.com/a/52635077
tagged with: python-trio
possible better answer: http://stackoverflow.com/a/51253257
score: 0
has answer: http://stackoverflow.com/a/51253257
tagged with: asynchronous
has answer: http://stackoverflow.com/a/51252103
tagged with: python-3.x
tagged with: python
answer count: 4
type: AnsweredQuestion
has body: I'm trying to use Python in an async manner in order to speed up my requests to a server. The server has a slow response time (often several seconds, but also sometimes faster than a second), but works well in parallel. I have no access to this server and can't change anything about it. So, I have a big list of URLs (in the code below, pages) which I know beforehand, and want to speed up their loading by making NO_TASKS=5 requests at a time. On the other hand, I don't want to overload the server, so I want a minimum pause between every request of 1 second (i. e. a limit of 1 request per second). So far I have successfully implemented the semaphore part (five requests at a time) using a Trio queue. import asks import time import trio NO_TASKS = 5 asks.init('trio') asks_session = asks.Session() queue = trio.Queue(NO_TASKS) next_request_at = 0 results = [] pages = [ 'https://www.yahoo.com/', 'http://www.cnn.com', 'http://www.python.org', 'http://www.jython.org', 'http://www.pypy.org', 'http://www.perl.org', 'http://www.cisco.com', 'http://www.facebook.com', 'http://www.twitter.com', 'http://www.macrumors.com/', 'http://arstechnica.com/', 'http://www.reuters.com/', 'http://abcnews.go.com/', 'http://www.cnbc.com/', ] async def async_load_page(url): global next_request_at sleep = next_request_at next_request_at = max(trio.current_time() + 1, next_request_at) await trio.sleep_until(sleep) next_request_at = max(trio.current_time() + 1, next_request_at) print('start loading page {} at {} seconds'.format(url, trio.current_time())) req = await asks_session.get(url) results.append(req.text) async def producer(url): await queue.put(url) async def consumer(): while True: if queue.empty(): print('queue empty') return url = await queue.get() await async_load_page(url) async def main(): async with trio.open_nursery() as nursery: for page in pages: nursery.start_soon(producer, page) await trio.sleep(0.2) for _ in range(NO_TASKS): nursery.start_soon(consumer) start = time.time() trio.…
type: Question
has answer: http://stackoverflow.com/a/54486595

http://stackoverflow.com/q/51257143
has title: Relate two models by geometry intersection in Geodjango
has answer: http://stackoverflow.com/a/51291276
tagged with: postgis
type: AnsweredQuestion
favorite count: 0
type: Question
has body: In GeoDjango with two have two models which contain geometry fields: from django.contrib.gis.db import models class Country(models.Model): territory = models.MultiPolygonField() language = models.CharField(max_length=2) class House(models.Model): location = models.PointField() I want to make a query that returns all houses located in countries that speak English. The relation between Country and House should be done by intersecting House.location with Country.territory. How can I achieve this using GeoDjango's ORM?
tagged with: django
tagged with: python
accepted answer: http://stackoverflow.com/a/51291276
answer count: 1
score: 4
tagged with: geodjango
upvote count: 4
downvote count: 0
linked to: http://stackoverflow.com/q/37166891

http://stackoverflow.com/comment/89623676
score: 0
type: AnswerComment
has text: Editing that, so that OP can understand what went wrong.
type: Comment
comment on: http://stackoverflow.com/a/51323693

http://stackoverflow.com/a/51183547
has body: This might not be the best solution, but you can remove the 'help' command, and re-add the 'help' command within your cog, since discord.py does not allow you to change a command's cog_name. The default help command is stored commands.bot._default_help_command. from discord.ext import commands bot = commands.Bot('.') bot.remove_command('help') class ACog: @commands.command(pass_context=True) async def help(self, ctx, *args: str): """Shows this message.""" return await commands.bot._default_help_command(ctx, *args) bot.add_cog(ACog()) bot.run('TKOEN')
upvote count: 1
has comment: http://stackoverflow.com/comment/89368285
has comment: http://stackoverflow.com/comment/89357533
has comment: http://stackoverflow.com/comment/112715763
answers question: http://stackoverflow.com/q/51170844
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51170844
type: Answer
score: 1

http://stackoverflow.com/comment/89336285
type: Comment
comment on: http://stackoverflow.com/q/51176688
has text: ok, I think the problem lies here `output_df.at[j, 'parent'] = key` instead of incrementing index, I am overwriting it with`j` variable, I might need to maintain a separate counter
score: 0
type: QuestionComment

http://stackoverflow.com/comment/89410567
has text: How do I do a regex on a bytes string though? The `info.stdout.read()` does not work.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51214741

http://stackoverflow.com/comment/89608536
type: QuestionComment
score: 0
has text: Or, more seriously, what about `str.find` or `str.index`?
comment on: http://stackoverflow.com/q/51315922
type: Comment

http://stackoverflow.com/comment/89506663
type: Comment
has text: Please, add an example, how are you running your tests. Try `pytest -s -v test_login.py`
comment on: http://stackoverflow.com/q/51253980
score: 0
type: QuestionComment

http://stackoverflow.com/comment/89565395
has text: I still got Download text instead of the link address. I tried something like this (pd.read_html('http://sisweb.tesouro.gov.br/apex/f?p=2501:2::::2::', attrs={'id': '82502690936618670'})[0]) --- and this (pd.read_html('http://sisweb.tesouro.gov.br/apex/f?p=2501:2::::2::', attrs={'id': '82502690936618670'})[0][3])
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51293574

http://stackoverflow.com/comment/89481625
type: AnswerComment
has text: I did but still I'm not able to replicate your result. would you double check?
comment on: http://stackoverflow.com/a/51250511
type: Comment
score: 0

http://stackoverflow.com/comment/89528145
has text: @AntoineBarthelet multiprocessing is a way to get around the GIL - pandas, or mostly numpy, can do that naturally. It sounds like you have a good pandas question. I reiterate that I think the multiprocessing approach should be dropped and you should let people scrutinise the code you're trying to speed up (in an [MCVE](https://stackoverflow.com/help/mcve))
type: Comment
score: 0
comment on: http://stackoverflow.com/q/51274847
type: QuestionComment

http://stackoverflow.com/comment/89324623
score: 1
comment on: http://stackoverflow.com/q/51170939
has text: Can you add data asample?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89528798
type: AnswerComment
has text: Or you may be rate limited
type: Comment
comment on: http://stackoverflow.com/a/51275167
score: 0

http://stackoverflow.com/q/51296268
tagged with: package
tagged with: windows
tagged with: python
has comment: http://stackoverflow.com/comment/129045779
linked to: http://stackoverflow.com/q/50283077
has comment: http://stackoverflow.com/comment/129133218
upvote count: 1
has comment: http://stackoverflow.com/comment/129199207
has answer: http://stackoverflow.com/a/51367720
type: AnsweredQuestion
score: 1
tagged with: executable
accepted answer: http://stackoverflow.com/a/51367720
has title: How to make python package refer to packaged, non-python executable (.exe); Windows
type: Question
linked to: http://stackoverflow.com/q/30218802
has body: I am putting together a Python package that uses a Cygwin executable without having Cygwin installed. This means that I have an executable (.exe) file and a library (.dll) file inside my package. I am doing this so that the tool can be used on Windows by people who only use Windows and Python. I am new to Python packages, so I appreciate any help. The Main Question How do I make my package point to the executable file inside my package? This would be used, for example, instead of the executable referenced by PATH. The answer might be out there, but all I've found in my search is a bunch of info on how to create an executable from a Python script, which is NOT what I want. Details/My Attempts The tool is sclite, a tool to score speech recognition output. For information about how I get the tool available on Windows, have a look at the How to Install SCLITE (for reproduce-ability) section, below. Here's a small, "toy" example of how I have my package set up. $ tree package_holder_dir/ package_holder_dir/ ├── bbd_package │ ├── __init__.py │ ├── non_py_exe_dll │ │ ├── cygwin1.dll │ │ └── sclite.exe │ ├── score │ │ ├── __init__.py │ │ └── run_sclite.py │ └── score_transcript.py ├── MANIFEST.in ├── README.txt └── setup.py 3 directories, 9 files My first guess was that the sclite.exe should go in the MANIFEST.in file. # @file MANIFEST.in include ./README.txt include ./bbd_package/non_py_exe_dll/sclite.exe include ./bbd_package/non_py_exe_dll/cygwin1.dll I also tried putting them in setup.py My setup.py is as follows #!/usr/bin/env/python3 # -*- coding: utf-8 -*- # @file setup.py import setuptools from distutils.core import setup with open ("README.txt", "r") as fh: long_description = fh.read() setup( name='bbd_package', url='user@host.com', author='bballdave025', author_email='not.likely@idontwantspam.com', packages=setuptools.find_packages(), #data_files=[('lib', ['./non_py_exe_dll/cygwin1.dll']), # './non_py_exe_dll/sclite.exe'], version='0.0.1', description="Example for…
answer count: 1
downvote count: 0
tagged with: cygwin
favorite count: 0
linked to: http://stackoverflow.com/q/33216691

http://stackoverflow.com/a/70610799
type: Answer
has body: Try raising a ValueError: raise ValueError("My custom message") For me, this changed the wording of the exception returned to the boto client from An error occurred (UserNotFoundException) when calling the AdminInitiateAuth operation: Exception migrating user in app client aeiouffhfha to the somewhat more useful An error occurred (UserNotFoundException) when calling the AdminInitiateAuth operation: UserMigration failed with error My custom message.
answers question: http://stackoverflow.com/q/51256302
upvote count: 1
downvote count: 0
score: 1

http://stackoverflow.com/comment/89499813
type: Comment
type: QuestionComment
score: 2
has text: Is your code not idented, or is it just while copying it on SO that it got un-indented ?
comment on: http://stackoverflow.com/q/51260858

http://stackoverflow.com/q/51225370
tagged with: io
has comment: http://stackoverflow.com/comment/89435512
tagged with: python
tagged with: utf-8
has comment: http://stackoverflow.com/comment/89431498
has comment: http://stackoverflow.com/comment/89434975
has comment: http://stackoverflow.com/comment/89431701
has comment: http://stackoverflow.com/comment/89433305
has body: I have a variable such as title: title = "révolution_essentielle" I could encode and decode it like this for other purposes: title1 = unicode(title, encoding = "utf-8") But how do I preserve the Non-English and use it as part of a url string to access the url? For instance, I ideally want https://mainurl.com/révolution_essentielle.html by concatenating several strings including title like this: url = main_url + "/" + title + ".html" Could anyone kindly show me how to do that? Thanks a bunch!
linked to: http://stackoverflow.com/q/1916684
upvote count: 1
downvote count: 1
type: AnsweredQuestion
has title: python decoding Non-English to use as url?
has comment: http://stackoverflow.com/comment/89435014
type: Question
tagged with: decode
has comment: http://stackoverflow.com/comment/89434836
score: 0
has answer: http://stackoverflow.com/a/51234005
answer count: 1
tagged with: unicode
favorite count: 0
has comment: http://stackoverflow.com/comment/89435534
has comment: http://stackoverflow.com/comment/89433157
accepted answer: http://stackoverflow.com/a/51234005
has comment: http://stackoverflow.com/comment/89520417
has comment: http://stackoverflow.com/comment/89440041
has comment: http://stackoverflow.com/comment/89434928

http://stackoverflow.com/comment/89439412
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51228118
has text: psycopg2.copy_to
score: 0

http://stackoverflow.com/q/51245011
answer count: 1
favorite count: 0
has body: the __aenter__ and __aexit__ methods are meant to ensure cleanup, But after a keyboard intterrupt is thrown, the __aexit__ method is not called anymore. I can imagine this being due to the fact that "with" statement is not part of the stacktrace of the current execution point(wild guess). How to deal effectively with this problem in asyncio? EDIT: I created some sample code: import asyncio class manager: async def __aenter__(self): print("enter") async def __aexit__(self, exc_type, exc_val, exc_tb): print("exit") async def func1(): print("func1") async with manager(): await asyncio.sleep(1000) async def func2(): print("func2") await asyncio.sleep(2) raise KeyboardInterrupt loop = asyncio.get_event_loop() loop.create_task(func1()) loop.create_task(func2()) loop.run_forever()
tagged with: python-asyncio
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89476258
tagged with: python
has comment: http://stackoverflow.com/comment/89470241
score: 2
downvote count: 0
has title: Keyboard Intterupt with __aexit__
has comment: http://stackoverflow.com/comment/89471603
has answer: http://stackoverflow.com/a/51248946
type: Question
tagged with: async-await
upvote count: 2
has comment: http://stackoverflow.com/comment/89474177

http://stackoverflow.com/q/51195102
favorite count: 0
has body: I just got the code from https://github.com/heykeetae/Self-Attention-GAN (the file is spectral.py). Partial code is under there. I don't really understand what is the use of the .data, is this a method in some class? if it is, which class does it belong to? import torch from torch.optim.optimizer import Optimizer, required from torch.autograd import Variable import torch.nn.functional as F from torch import nn from torch import Tensor from torch.nn import Parameter def l2normalize(v, eps=1e-12): return v / (v.norm() + eps) class SpectralNorm(nn.Module): def _make_params(self): w = getattr(self.module, self.name) height = w.data.shape[0] width = w.view(height, -1).data.shape[1] u = Parameter(w.data.new(height).normal_(0, 1), requires_grad=False) v = Parameter(w.data.new(width).normal_(0, 1), requires_grad=False) u.data = l2normalize(u.data) v.data = l2normalize(v.data) w_bar = Parameter(w.data)
type: UnansweredQuestion
has title: what is the use of .data in pytorch
tagged with: python
has comment: http://stackoverflow.com/comment/89401737
tagged with: generative-adversarial-network
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/51195908
has comment: http://stackoverflow.com/comment/89399734
type: Question
has comment: http://stackoverflow.com/comment/89372529
downvote count: 0
answer count: 1

http://stackoverflow.com/q/51176364
has comment: http://stackoverflow.com/comment/89338303
score: 0
answer count: 0
type: UnansweredQuestion
has title: Python 3 object creation consumes large amounts of memory
has body: I want to create a list of instances of user-defined classes. These instances contain many matrices which are created inside the constructor of the class. The total size of such an instance, measured with pympler, is 1.2 MB. When creating these objects one after another, something weird happens. When the first object is created, the system-wide memory usage only increases insignificantly, however, when the second object is created, it uses more than 1 GB of system-wide memory. This memory usage is not reflected inside python, i.e. pympler still says that memory usage has increased by 1.2 MB. This goes on for each newly created object, with every second using huge amounts of memory. Is there a way to see what causes this memory usage? For clarity, I have included the respective (pseudo) code below: class ClassA: class SubClass: def __init__(self, ...): self.matrix_a = np.zeros(256) self.matrix_b = np.zeros(256) self.matrix_c = np.zeros(256) def __init__(self, ...): self.subitems = [] for i in range(0, 100000): self.subitems.append(ClassA.SubClass(self, ...)
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89358635
type: Question
tagged with: python

http://stackoverflow.com/a/52504458
score: 3
downvote count: 0
type: AcceptedAnswer
upvote count: 3
type: Answer
accepted answer of: http://stackoverflow.com/q/51183280
answers question: http://stackoverflow.com/q/51183280
has body: Fixed in 4c18633. The problem is that for version x64 for Python 3.7 it is not working due to class config for freezer.py. You need to go cx_Freezer installation folder. If you have a virtual environment, go to your environment folder \lib\site-packages\cx_Freeze, find the freezer.py and add the code found on the commit. You can find the patch at GitHub

http://stackoverflow.com/a/51286793
answers question: http://stackoverflow.com/q/51286525
downvote count: 0
has comment: http://stackoverflow.com/comment/89551191
type: Answer
has body: You can get stock data from prepared datasets or scrape from other websites. Here is where you can find it: https://github.com/eliangcs/pystock-data or https://www.kaggle.com/borismarjanovic/price-volume-data-for-all-us-stocks-etfs https://www.kaggle.com/camnugent/sandp500
upvote count: 1
score: 1

http://stackoverflow.com/a/51290585
upvote count: 3
accepted answer of: http://stackoverflow.com/q/51290514
type: AcceptedAnswer
downvote count: 0
has body: Using str.extract df.assign(MainCountry=df.CountryName.str.extract(r'(.*?)(?:\||$)')) CountryName MainCountry 0 India|Pakistan India 1 Pakistan|Agansitan Pakistan 2 Sweden Sweden 3 Nepal|Bhutan Nepal Or str.partition df.assign(MainCountry=df.CountryName.str.partition('|')[0]) CountryName MainCountry 0 India|Pakistan India 1 Pakistan|Agansitan Pakistan 2 Sweden Sweden 3 Nepal|Bhutan Nepal
type: Answer
answers question: http://stackoverflow.com/q/51290514
score: 3

http://stackoverflow.com/q/51168728
favorite count: 0
linked to: http://stackoverflow.com/q/1689015
tagged with: python
accepted answer: http://stackoverflow.com/a/51168803
type: AnsweredQuestion
has title: Start Python program in the background
possible better answer: http://stackoverflow.com/a/51168781
has answer: http://stackoverflow.com/a/51168803
has answer: http://stackoverflow.com/a/51168927
has body: I have a Python program which I compiled into a .exe file using PyInstaller. When you open the .exe, there should be no console, no command prompt or whatever. It should run the Python program in the background completely silently. Is it possible to put something in the Python script so that it does not open a command prompt and executes silently?
type: Question
score: 0
tagged with: batch-file
answer count: 3
has answer: http://stackoverflow.com/a/51168781
upvote count: 1
tagged with: windows
downvote count: 1

http://stackoverflow.com/q/51233325
type: Question
downvote count: 0
has body: I have written a script in python using selenium to fetch the business summary (which is within p tag) located at the bottom right corner of a webpage under the header Company profile. The webpage is heavily dynamic, so I thought to use a browser simulator. I have created a css selector, which is able to parse the summary if I copy the html elements directly from that webpage and try on it locally. For some reason, when I tried the same selector within my below script, it doesn't do the trick. It throws timeout exception error instead. How can I fetch it? This is my try: from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.common.exceptions import TimeoutException link = "https://in.finance.yahoo.com/quote/AAPL?p=AAPL" def get_information(driver, url): driver.get(url) item = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, "[id$='-QuoteModule'] p[class^='businessSummary']"))) driver.execute_script("arguments[0].scrollIntoView();", item) print(item.text) if __name__ == "__main__": driver = webdriver.Chrome() wait = WebDriverWait(driver, 20) try: get_information(driver,link) finally: driver.quit()
accepted answer: http://stackoverflow.com/a/51233465
favorite count: 0
has title: Unable to get a dynamically generated content from a webpage
has answer: http://stackoverflow.com/a/51233984
answer count: 3
possible better answer: http://stackoverflow.com/a/51233572
tagged with: python
has answer: http://stackoverflow.com/a/51233572
tagged with: selenium-webdriver
score: 2
tagged with: python-3.x
upvote count: 2
tagged with: selenium
tagged with: web-scraping
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51233465

http://stackoverflow.com/q/51264291
tagged with: keras
has comment: http://stackoverflow.com/comment/89506967
has answer: http://stackoverflow.com/a/51265068
has comment: http://stackoverflow.com/comment/89507561
score: 0
has comment: http://stackoverflow.com/comment/89506757
tagged with: python
has comment: http://stackoverflow.com/comment/89506673
has comment: http://stackoverflow.com/comment/89506924
tagged with: machine-learning
has comment: http://stackoverflow.com/comment/89506572
has body: So basically we usually define cross entropy like this: dim = 5 logits = tf.random_normal([5,3],dtype=tf.float32) labels = tf.cast(tf.one_hot(10,5),tf.int32) cost_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits,labels=labels) with tf.Session() as sess: a,b=sess.run([logits,labels]) print(b) print(sess.run(cost_entropy)) print('\n') print(a) output: [0 0 0 0 0] [1.8559302 2.1816468 2.9526126 1.5903687 2.500083 ] [[ 0.1913337 0.32995617 -0.23624638] [ 0.65993434 -0.2852072 -1.1419022 ] [-0.2529132 -0.35611948 0.4710417 ] [-0.61094457 -0.76033163 -0.6311429 ] [-1.5868235 0.81744194 -0.31859735]] Now if my logits are : [[ 0.1913337 0.32995617 -0.23624638] [ 0.65993434 -0.2852072 -1.1419022 ] [-0.2529132 -0.35611948 0.4710417 ] [-0.61094457 -0.76033163 -0.6311429 ] [-1.5868235 0.81744194 -0.31859735]] And my labels are same shape of logits like : [ [ 0 1 0] [ 1 0 1] [1 1 0] [1 1 1] [0 0 0] ] So each value in logits have a 0 or one ( One hot encoding ) , How can i achieve that ? I tried with `tf.nn.sparse_softmax_cross_entropy_with_logits` and `tf.nn.softmax_cross_entropy_with_logits` But it's giving Error . For more explanation : So suppose my input is . [ [12 , 14 , 15 ] . , [23 ,24 , 25 ] ] . now i will get logits for this input like . [ [ 0.11 , -0.1 , 0.2 ] , [0.91 0.2 0.12] ] . now my labels are for this logits . [ [ 0, 0 , 1 ] , [ 1 , 0 ,1 ] ] . it means i want . [0.2] from first and [0.91 , 0.12] from second from this vector [ 0.11 , -0.1 , 0.2 ] . i wan last one so my label are [ 0 , 0 ,1 ] from this vector [0.91 0.2 0.12] . i want first and last so i want [ 1, 0, 1]
accepted answer: http://stackoverflow.com/a/51265068
tagged with: tensorflow
type: Question
type: AnsweredQuestion
has title: How to define cross entropy for equal logits and labels?
has comment: http://stackoverflow.com/comment/89507404
has comment: http://stackoverflow.com/comment/89506618
has comment: http://stackoverflow.com/comment/89506842
tagged with: deep-learning
answer count: 1

http://stackoverflow.com/comment/89525338
has text: Try EXIFTOOL to see what the actual density/resolution is. You may also have to specify a set of units such as pixelsperinch via wand. If not specified, some tools do not know how to interpret the density/resolution. See wand.image.UNIT_TYPES
score: 0
type: Comment
comment on: http://stackoverflow.com/q/51271878
type: QuestionComment

http://stackoverflow.com/q/51212631
has comment: http://stackoverflow.com/comment/89406253
tagged with: python-3.x
type: UnansweredQuestion
has body: characters = ["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", "-", "'", " ", "*"] def enter_first_name(): while True: first_name = input("Enter your first name: ").lower().rstrip().lstrip() for i in first_name: if i in characters: print(i) return first_name else: print("ERROR! Invalid entry.") The print(i) is there to check that it's working properly but all it prints is the first letter from whatever the user inputs as their name. The purpose is so that if someone were for example to accidentally type a number in their name (any symbol not included in the list characters) that it returns "ERROR! Invalid entry." and prompts them to enter their name again. What am I doing wrong and how can I go through each letter from the input to ensure it's a valid entry? Thank you!
tagged with: python
has title: User Input Against a List - Python
has answer: http://stackoverflow.com/a/51212777
has comment: http://stackoverflow.com/comment/89406209
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/51212776
score: 0

http://stackoverflow.com/q/51191138
accepted answer: http://stackoverflow.com/a/51194942
upvote count: 0
tagged with: connected-components
answer count: 1
has comment: http://stackoverflow.com/comment/89364100
has body: My work requires applying Local Binary Operator on Images. For that I have already converted the images in Gray then implemented a Connected Components analysis on the image also. Here is the Code: Adding Libraries import numpy as np import pandas as pd import matplotlib.pyplot as plt from skimage.io import imread, imshow from skimage.color import rgb2gray from skimage.morphology import (erosion, dilation, closing, opening,area_closing, area_opening) from skimage.measure import label, regionprops, regionprops_table Rendering the image plt.figure(figsize=(6,6)) painting = imread("E:/Project/for_annotation/Gupi Gain0032.jpg") plt.imshow(painting); plt.figure(figsize=(6,6)) Binarizing Image gray_painting = rgb2gray(painting) binarized = gray_painting<0.55 plt.imshow(binarized); 4.Declaring Kernel square = np.array([[1,1,1], [1,1,1], [1,1,1]]) Dilation function def multi_dil(im, num, element=square): for i in range(num): im = dilation(im, element) return im Erosion function def multi_ero(im, num, element=square): for i in range(num): im = erosion(im, element) return im Functions Applied plt.figure(figsize=(6,6)) multi_dilated = multi_dil(binarized, 7) area_closed = area_closing(multi_dilated, 50000) multi_eroded = multi_ero(area_closed, 7) opened = opening(multi_eroded) plt.imshow(opened); Label function plt.figure(figsize=(6,6)) label_im = label(opened) regions = regionprops(label_im) plt.imshow(label_im); Extract features properties = ['area','convex_area','bbox_area', 'extent', 'mean_intensity','solidity', 'eccentricity', 'orientation'] pd.DataFrame(regionprops_table(label_im, gray_painting, properties=properties)) Filtering Regions masks = [] bbox = [] list_of_index = [] for num, x in enumerate(regions): area = x.area convex_area = x.convex_area if (num!=0 and (area>100) and (convex_area/area <1.05) and (convex_area/area >0.95)): masks.append(regions[num].convex_image) bbox.append(regions[num].bbox) list_of_index.append(num) count = len(masks) Extracting Images fig,…
favorite count: 0
has comment: http://stackoverflow.com/comment/89363942
score: -4
tagged with: python
type: AnsweredQuestion
tagged with: edit
has comment: http://stackoverflow.com/comment/89364085
has comment: http://stackoverflow.com/comment/89363973
type: Question
has comment: http://stackoverflow.com/comment/89364092
tagged with: algorithm
has title: Connected Component Labeling Algorithm in Python
has answer: http://stackoverflow.com/a/51194942
downvote count: 4

http://stackoverflow.com/comment/89603466
comment on: http://stackoverflow.com/a/51313296
score: 0
type: AnswerComment
has text: @LucasCioffi from the image it seems a floating `div` added by javascript. Try using the inspector from your browser (press F12) to see how the element is added to the page.
type: Comment

http://stackoverflow.com/q/51232401
has comment: http://stackoverflow.com/comment/89479195
has comment: http://stackoverflow.com/comment/89478973
has comment: http://stackoverflow.com/comment/89479675
has answer: http://stackoverflow.com/a/56309775
tagged with: sqlalchemy
has comment: http://stackoverflow.com/comment/122594841
type: Question
tagged with: alembic
has comment: http://stackoverflow.com/comment/89457360
answer count: 1
score: 4
has title: SQLAlchemy / Alembic raw SQL for adding index
tagged with: postgresql
tagged with: python
upvote count: 4
has body: I'd like to use the following raw SQL to create an index in PostgreSQL: CREATE INDEX ix_action_date ON events_map ((action -&gt;&gt; 'action'), date, map_id); I tried to put this line into the model class's __table_args__ part, but I couldn't. Then I simply solved it by using raw SQL in Alembic migration. conn = op.get_bind() conn.execute(text("CREATE INDEX ...")) and just using a dummy index in __table_args__ like: Index('ix_action_date') My only problem is that Alembic doesn't accept the dummy index with the same name, and every time I run a revision --autogenerate, it tells me the following: SAWarning: Skipped unsupported reflection of expression-based index ix_action_date % idx_name) and then it adds the autogenerated index to the migration file: op.create_index('ix_action_date', 'events_map', [], unique=False) My question is: How can I write raw SQL into a __table_args__ Index? How can I really make my dummy index concept work ? I mean an index which is only compared by name?
has comment: http://stackoverflow.com/comment/89478807
favorite count: 0
downvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89479354

http://stackoverflow.com/comment/89323619
type: AnswerComment
comment on: http://stackoverflow.com/a/51170408
score: 0
type: Comment
has text: Thank you! This works for the top two examples nicely! Could this be extended for the connecting words?

http://stackoverflow.com/q/51319061
has answer: http://stackoverflow.com/a/51319135
downvote count: 1
type: Question
upvote count: 0
has body: My code below finds which city the district entered by the user is located in and it's postal code. I have put my data into a dictionary and I want to know how I can modify the code to receive a postal code from the user and output the district and the city it is located in. Code: zipcode = { "Trap City": { "C District": 100, "D District": 103, "E District": 104, "S District": 105 }, "Zap City": { "R District": 200, "D District": 201 }, "Los City": { "X District": 207, "Y District": 208 } } district=input('Enter your district: ') for city in zipcode: if district in zipcode[city]: print(city,zipcode[city][district])
has answer: http://stackoverflow.com/a/51319163
score: -1
linked to: http://stackoverflow.com/q/51301426
has answer: http://stackoverflow.com/a/51320737
has answer: http://stackoverflow.com/a/51319307
favorite count: 0
tagged with: python-3.x
has title: Referencing and Printing Values from Dictionary (Python)
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89615382
tagged with: python
tagged with: dictionary
answer count: 4

http://stackoverflow.com/a/51363237
has comment: http://stackoverflow.com/comment/95264227
has comment: http://stackoverflow.com/comment/95339257
upvote count: 4
has body: When you have more than one data instance that needs processing, you have two options: Send a single request containing all of the instances (a batch). Send a separate request out for each instance individually (usually in parallel). There are pros and cons to both. The first option (send them all in the same request) is the most efficient, i.e., the cost per prediction and the time per prediction is lowest. However, the wall clock time for the predictions will be higher. For example, you may send 50 images and it might take 50 seconds process those. So the time per image is 1 second and the cost is 50 node*seconds. You should especially know that each instance in a request is processed on the same machine -- which is why you are observing no horizontal scaling. On the other hand, if you create a new thread for each image and send one image per request, thus sending out the requests in parallel, you may get all of the responses back within, say, 10 seconds (firing a large number of requests simultaneously can cause new servers to spin up which can add to the processing time). The average time per request might be 2.5 seconds and you might require 25 machines to process it all (costing 25*2.5 = 62.5 node*seconds) So the wall clock time is lower, but the time per prediction and the cost are higher. It's a tradeoff each project will make based on their individual needs. For your use case, it's clear you're expecting horizontal scaling, so I recommend sending fewer images per request, and more requests in parallel, keeping in mind the above tradeoffs. If you fire too many requests off simultaneously, you may cause more machines to spin up to handle the load, which will add to the processing time, so you'll want to balance how many images you put in a request and how many 'min_nodes' you keep up. Finally, you can consider using the batch prediction service which is very efficient at processing (large amounts of) data in parallel. However, that service is intended for a f…
answers question: http://stackoverflow.com/q/51241717
downvote count: 0
score: 4
type: Answer
has comment: http://stackoverflow.com/comment/95339314
has comment: http://stackoverflow.com/comment/95339926
has comment: http://stackoverflow.com/comment/111510670

http://stackoverflow.com/q/51176185
has answer: http://stackoverflow.com/a/51190545
tagged with: python
score: 0
has body: I'm stuck trying to get functions that are existent in scipy (or sympy) for the following task: Suppose we are given the following function: f(A,B,C) = k1-A*sin(B*k2-C) for each of the axis A,B,C of the space we have a specific interval, like [a_lb, a_ub], [b_lb, b_ub], [c_lb, c_ub], [d_lb, d_ub]. Which functions of scipy can be used to compute if the space encompassed by the boundaries is intersected by the given function? I thought of like e.g. computing the Hessian matrix. Thank you for hints Best regards
has title: Computing intersection of a function with a specific interval using scipy
tagged with: scipy
type: Question
tagged with: intersection
answer count: 1
type: UnansweredQuestion

http://stackoverflow.com/a/51191433
has comment: http://stackoverflow.com/comment/89365237
has body: As Sergio mentions, the http request is probably slower than the for loops, but when you have a large amount of iterations, the for loop can slow things down as wel. You could try to build a list of urls using list comprehension and then do the request: for the first line in the inner loop it would be: pokemon_move_url = ['https://pokeapi.co/api/v2/move/'+move['move']['name'] for move in pokemon_parsed['moves'] for method in move['version_group_details'] if method['version_group']['name'] == 'sun-moon' and method['move_learn_method']['name'] == 'level-up'] pokemon_move = [requests.get(url) for url in pokemon_move_url] pokemon_move_text = [move.text for move in pokemon_move] pokemon_parsed_moves = [json.loads(text) for text in pokemon_move_text] This should be significantly faster than using the for loops (depending of course if the for loop or the request is the bottleneck)
answers question: http://stackoverflow.com/q/51190701
has comment: http://stackoverflow.com/comment/89367958
has comment: http://stackoverflow.com/comment/89367444
score: 0
accepted answer of: http://stackoverflow.com/q/51190701
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89369727
type: Answer

http://stackoverflow.com/a/51186294
score: 1
upvote count: 1
type: AcceptedAnswer
has body: Spelling mistake. testPython.py ==> testPyhton.py (in the directory) There are autocomplete tools, ide available to avoid these kind of mistakes
accepted answer of: http://stackoverflow.com/q/51185970
answers question: http://stackoverflow.com/q/51185970
type: Answer
downvote count: 0

http://stackoverflow.com/q/51223407
has answer: http://stackoverflow.com/a/54181690
has comment: http://stackoverflow.com/comment/89427482
has comment: http://stackoverflow.com/comment/89427713
type: Question
has title: python pip install failures
has answer: http://stackoverflow.com/a/52327219
has body: i am trying to install a library pynput using sudo pip install pynput but i am getting this error log. This has been happening with any other python package. everything used to work fine suddenly these errors are appearing i tried to copy error log from ~/.pip/pip.log and this is what i have: Using version 1.4 (newest of versions: 1.4, 1.3.10, 1.3.9, 1.3.8.1, 1.3.7, 1.3.6, 1.3.5, 1.3.4, 1.3.3, 1.3.2, 1.3.1, 1.3, 1.2, 1.1.7, 1.1.6, 1.1.5, 1.1.4, 1.1.3, 1.1.2, 1.1.1, 1.1, 1.0.6, 1.0.5, 1.0.4, 1.0.3, 1.0.2, 1.0.1, 1.0, 0.6, 0.5.1, 0.5, 0.4, 0.3, 0.2) Cleaning up... Removing temporary dir /tmp/pip_build_root... Exception: Traceback (most recent call last): File "/usr/lib/python2.7/dist-packages/pip/basecommand.py", line 122, in main status = self.run(options, args) File "/usr/lib/python2.7/dist-packages/pip/commands/install.py", line 278, in run requirement_set.prepare_files(finder, force_root_egg_info=self.bundle, bundle=self.bundle) File "/usr/lib/python2.7/dist-packages/pip/req.py", line 1198, in prepare_files do_download, File "/usr/lib/python2.7/dist-packages/pip/req.py", line 1376, in unpack_url self.session, File "/usr/lib/python2.7/dist-packages/pip/download.py", line 546, in unpack_http_url resp = session.get(target_url, stream=True) File "/usr/share/python-wheels/requests-2.2.1-py2.py3-none-any.whl/requests/sessions.py", line 467, in get return self.request('GET', url, **kwargs) File "/usr/lib/python2.7/dist-packages/pip/download.py", line 237, in request return super(PipSession, self).request(method, url, *args, **kwargs) File "/usr/share/python-wheels/requests-2.2.1-py2.py3-none-any.whl/requests/sessions.py", line 455, in request resp = self.send(prep, **send_kwargs) File "/usr/share/python-wheels/requests-2.2.1-py2.py3-none-any.whl/requests/sessions.py", line 558, in send r = adapter.send(request, **kwargs) File "/usr/share/python-wheels/requests-2.2.1-py2.py3-none-any.whl/requests/adapters.py", line 330, in send timeout=timeout File "/usr/share/python-whee…
upvote count: 5
has comment: http://stackoverflow.com/comment/89475045
tagged with: ubuntu-14.04
score: 4
has answer: http://stackoverflow.com/a/51223546
favorite count: 0
has answer: http://stackoverflow.com/a/51250507
accepted answer: http://stackoverflow.com/a/51250507
has answer: http://stackoverflow.com/a/51259588
answer count: 5
possible better answer: http://stackoverflow.com/a/54181690
tagged with: pip
tagged with: python
downvote count: 1
has comment: http://stackoverflow.com/comment/89475025
type: AnsweredQuestion

http://stackoverflow.com/comment/89482287
type: QuestionComment
type: Comment
has text: I don't fully understand your code, but any time you have many named arguments where the names incorporate numbers (either as `foo1`, `foo2` or in your case, numbers spelled out), you probably should be using a list instead of separate variables.
comment on: http://stackoverflow.com/q/51250137
score: 0

http://stackoverflow.com/a/51212737
upvote count: 3
score: 0
downvote count: 3
has comment: http://stackoverflow.com/comment/89414923
answers question: http://stackoverflow.com/q/51211176
type: Answer
has comment: http://stackoverflow.com/comment/89500005
has comment: http://stackoverflow.com/comment/89467906
has body: If you really must have an np.ndarray with dtype=object, you can do this: a = np.array([list([1]), list([4, 5])], dtype=object) b = [2, 3, 4] a = np.hstack((a, np.empty(1))) a[-1] = b (Or of course remove np. in your case where you fully imported numpy.) But I recommend not using np.ndarrays of dtype=object. Instead use lists with: a = [[list([1]), list([4, 5])]] b = [2, 3, 4] a.append(b) Now if you really want to have a as an np.ndarray, you can then do the following: a = np.array(a)
has comment: http://stackoverflow.com/comment/89484930
has comment: http://stackoverflow.com/comment/89467909
has comment: http://stackoverflow.com/comment/89499583

http://stackoverflow.com/comment/125286898
comment on: http://stackoverflow.com/a/55136776
has text: This method can easily be adapted to write streaming data.
score: 1
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/89603667
type: Comment
type: QuestionComment
has text: It is running now, and I do see that my memory load has increased. We'll see if it is able to run successfully!
comment on: http://stackoverflow.com/q/51310952
score: 0

http://stackoverflow.com/comment/89340986
type: AnswerComment
type: Comment
has text: @Guydangerous99 everything seems to be correct. The behavior you describe is exactly how the code you wrote should behave, so there isn't anything that is **not working**.
score: 1
comment on: http://stackoverflow.com/a/51179222

http://stackoverflow.com/comment/89452114
type: AnswerComment
comment on: http://stackoverflow.com/a/51236494
has text: @Nexus It's a function that chunks or groups a list's elements, that you chose out of the examples from the linked question. You can use the `chunks` function from the first answer, or the `grouper` recipe from the `itertools` docs, or the different `chunks` function from the third answer, or `array_split` from numpy, etc.
score: 0
type: Comment

http://stackoverflow.com/q/51168569
has answer: http://stackoverflow.com/a/51169656
accepted answer: http://stackoverflow.com/a/51169656
tagged with: bash
answer count: 3
has answer: http://stackoverflow.com/a/51170378
tagged with: http://stackoverflow.com/tag/pdf
downvote count: 1
favorite count: 0
possible better answer: http://stackoverflow.com/a/51170378
tagged with: linux
has body: I have around 500 PDFs in which the last page is not required. Can I write a script using any tool using command line which can loop over all the files, remove the last page and save the new file? I researched on the internet and pdftk was the most viable option, but it no longer works in Ubuntu. Help would be appreciated. Thanks
has comment: http://stackoverflow.com/comment/89320932
tagged with: python
has answer: http://stackoverflow.com/a/51168743
tagged with: edit
type: AnsweredQuestion
upvote count: 0
score: -1
has comment: http://stackoverflow.com/comment/89320265
has title: Removing last page of PDF using Python or Bash
type: Question
has comment: http://stackoverflow.com/comment/89320779

http://stackoverflow.com/q/51192511
upvote count: 1
answer count: 1
has body: I have downloaded 240 genomes from NCBI and when downloaded they get a filename according to their assembly numbers. I would like to rename the files according to their species name, instead of their assembly numbers, as this will make interpretation of the data much easier. I know some (very little) python, and I haven't really been able to google myself out of the problem. So what I would like to do is to write a loop that goes into each file in my folder and rewrites the file name according to the fasta header Example of filename: GCF_000014225.1_ASM1422v1_genomic.fna Example of fasta header: >NC_008228.1 Pseudoalteromonas atlantica T6c, complete genome Obviously I would be happy if I could ret rid of the NC_008228.1 and, complete genome, but just the fasta header as filename would make my life much easier (alternative is doing it manually...but I know it can be done with some coding) Thank you so much in advance!
has title: Renaming files according to fasta header
tagged with: file-rename
type: UnansweredQuestion
downvote count: 0
score: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/51193023
tagged with: python
tagged with: fasta

http://stackoverflow.com/q/51324075
score: 7
upvote count: 7
type: Question
has answer: http://stackoverflow.com/a/51325426
has body: I need to assert an error message using py.test, import pandas as pd import numpy as np from inv_exception_store import InvAmtValError MAX_INV_VAL = 10000000.0 MIN_INV_VAL = 0.0 class Invoices: def __init__(self, data=None): if data is None: self.__invoices = pd.Series([], dtype=np.float32) else: self.__invoices = pd.Series(pd.Series(data).astype(np.float32)) def addInvoice(self, amount): try: if self.__invoices.size &gt; MAX_INV_SIZE: raise InvNumError elif amount &gt; MAX_INV_VAL or amount &lt; MIN_INV_VAL: raise InvAmtValError(amount) else: self.__invoices = self.__invoices.append(pd.Series(amount).astype(np.float32), ignore_index=True) except (InvNumError, InvAmtValError) as e: print(str(e)) class InvAmtValError(Exception): def __init__(self, amount, message=None): if message is None: if amount &gt; 100000000.0: message = 'The invoice amount(s) {} is invalid since it is &gt; $100,000,00.00'.format(amount) elif amount &lt; 0.0: message = 'The invoice amount(s) {} is invalid since it is &lt; $0.00'.format(amount) else: message = 'The invoice amount(s) {} is invalid'.format(amount) super(InvAmtValError, self).__init__(str(self.__class__.__name__) + ': ' + message) self.message = message def __str__(self): return self.message class TestInvoice(object): def test_invalid_inv_amount_err(self): with pytest.raises(InvAmtValError) as e: invoices = Invoices() invoices.addInvoice(-1.2) assert str(e) == 'The invoice amount(s) -1.2 is invalid since it is &lt; $0.00' invoices.addInvoice(100000000.1) assert str(e) == 'The invoice amount(s) 100000000.1 is invalid since it is &gt; $100,000,00.00' by running the test, I got, self = &lt;ExceptionInfo AttributeError tblen=2&gt; def __str__(self): &gt; entry = self.traceback[-1] E AttributeError: 'ExceptionInfo' object has no attribute 'traceback' I am wondering how to make py.test work for asserting exception here. UPDATE. Tried the solution suggested, def test_invalid_min_inv_amount_err(self): with pytest.raises(InvAmtValError) as …
tagged with: pandas
answer count: 1
has title: AttributeError: 'ExceptionInfo' object has no attribute 'traceback' when using pytest to assert exceptions
downvote count: 0
favorite count: 0
tagged with: python-3.x
tagged with: exception
tagged with: python
accepted answer: http://stackoverflow.com/a/51325426
type: AnsweredQuestion
tagged with: pytest

http://stackoverflow.com/q/51169322
tagged with: pandas
linked to: http://stackoverflow.com/q/25559202
tagged with: python
accepted answer: http://stackoverflow.com/a/51169509
possible better answer: http://stackoverflow.com/a/51169828
tagged with: list
linked to: http://stackoverflow.com/q/44393344
upvote count: 1
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/44758596
has body: I have a dataframe that looks like this: df = pd.DataFrame( {'tod': [[('a',10),('b',6),('h',3),('p',2)], [('x',11),('e',2),('l',2)], [('r',5),('l',5)], [('n',15)]]}) tod 0 [(a, 10), (b, 6), (h, 3), (p, 2)] 1 [(x, 11), (e, 2), (l, 2)] 2 [(r, 5), (l, 5)] 3 [(n, 15)] I want to expand list of tuples to new columns to get: tod l1 n1 l2 n2 l3 n3 l4 n4 0 [(a, 10), (b, 6), (h, 3), (p, 2)] a 10 b 6 h 3 p 2 1 [(x, 11), (e, 2), (l, 2)] x 11 e 2 l 2 - nan 2 [(r, 5), (l, 5)] r 5 l 5 - nan - nan 3 [(n, 15)] n 15 - nan - nan - nan I want to end up with missing values in the corresponding columns if the tuples do not exist. I'm having trouble as the length of each list (number of tuples) within each cell is different for each row, so I want to dynamically assign new column values as they appear. Also each cell contains a list of tuple pairs, not a single tuple. I tried something like in this question, but this only allowed expansion of a single tuple into multiple columns (when you know the columns before hand). Then i looked at this and this but again, the number of columns is unknown so I ended up with: pd.DataFrame.from_records([{k: v for v, k in row} for row in df.tod]) Out[171]: 2 3 5 6 10 11 15 0 p h NaN b a NaN NaN 1 l NaN NaN NaN NaN x NaN 2 NaN NaN l NaN NaN NaN NaN 3 NaN NaN NaN NaN NaN NaN n Then I looked at splitting cells which contain tuples here and here which looked at converting the tuples to a series, but again, this did not work, as these examples only deal with single tuples of known length, not lists of tuples How can I approach this problem? Note: I realise I've not put up a lot of code for "What have you tried" - my console is a heap of garbage that has yielded continuous errors. In the interests of keeping this clean I've left this off.
score: 1
tagged with: dataframe
has title: Split Column of list of Tuples from Apply to New Columns
linked to: http://stackoverflow.com/q/29550414
type: Question
has answer: http://stackoverflow.com/a/51169509
answer count: 2
downvote count: 0
favorite count: 0
linked to: http://stackoverflow.com/q/45122154
tagged with: tuples
linked to: http://stackoverflow.com/q/16236684
has answer: http://stackoverflow.com/a/51169828

http://stackoverflow.com/comment/89693086
comment on: http://stackoverflow.com/a/51357820
type: AnswerComment
score: 0
type: Comment
has text: "but you can use any given set of colors @Dan, who cares?". Sure, you can do whatever you want. But if you want people to be able to understand what you create it's worthwhile building off of the work others have already done. This is not a case of just using different colours, it's a case of how the interpolation is done which your code has no control over.

http://stackoverflow.com/comment/89489824
comment on: http://stackoverflow.com/a/51255330
score: 1
type: AnswerComment
has text: I tried to write a simple explanation for 15 minutes, but failed. Found almost same problem already solved and explained. Hope it helps. https://stackoverflow.com/a/19414553/1921796
type: Comment

http://stackoverflow.com/q/51314305
type: Question
has answer: http://stackoverflow.com/a/51315056
tagged with: python
has comment: http://stackoverflow.com/comment/89605539
tagged with: oop
has body: I have a subclass that needs to inherit from two parents differing only in methods and a single property. When instantiating this class, I'm getting an error stating I'm using to many parameters. When removing a param it says I'm not using enough. Ball class Ball: """ base class for bouncing objects """ def __init__(self, bounds, position, velocity, color, radius): self.position = position self.velocity = velocity self.bounds = bounds self.color = color self.radius = radius def update(self): # bounce at edges. TODO: Fix sticky edges if self.position.x &lt; 0 + self.radius or self.position.x &gt; self.bounds[0] - self.radius: # screen width self.velocity.x *= -1 if self.position.y &lt; 0 + self.radius or self.position.y &gt; self.bounds[1] - self.radius: # screen height self.velocity.y *= -1 self.position += self.velocity def draw(self, screen, pygame): # cast x and y to int for drawing pygame.draw.circle(screen, self.color, [int(self.position.x), int(self.position.y)], self.radius) BouncingBall class BouncingBall(Ball): """ ball effected by gravity """ def __init__(self, bounds, position, velocity, color, radius, weight): super().__init__(bounds, position, velocity, color, radius) self.weight = weight def update(self): KineticBall class KineticBall(Ball): """ A ball that collides with other collidable balls using simple elastic circle collision """ def __init__(self, bounds, position, velocity, color, radius, object_list): super().__init__(bounds, position, velocity, color, radius) self.object_list = object_list KineticBouncing class KineticBouncing(BouncingBall, KineticBall): def __init__(self, bounds, position, velocity, color, radius, weight, object_list): super().__init__(bounds, position, velocity, color, radius, weight, object_list) ball => KineticBouncing # super().__init__(bounds, position, velocity, color, radius, weight, object_list) TypeError: __init__() takes 7 positional arguments but 8 were given ball = KineticBouncing(SCREEN_SIZE, Vector2(50, 50), Vec…
has title: Python: trouble inheriting from multiple parent classes
score: 0
answer count: 2
upvote count: 1
has comment: http://stackoverflow.com/comment/89605674
downvote count: 1
has answer: http://stackoverflow.com/a/51314690
has comment: http://stackoverflow.com/comment/89605412
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89605489
tagged with: class
has comment: http://stackoverflow.com/comment/89605435
favorite count: 0

http://stackoverflow.com/comment/89410027
type: Comment
has text: @KrishnaPatel the code I included utilizes a grid search with 10 fold stratified cross validation. Perhaps you are confused about cross validation? The point of cross validation isn't to build multiple estimators and get the most accurate one. The point of cross validation is to build an estimator against different cross sections of your data to gain an aggregate understanding of performance across all sections. This way you can avoid choosing a model based on a potentially biased split. See [sklearn's cross validation module](http://scikit-learn.org/stable/modules/cross_validation.html).
comment on: http://stackoverflow.com/a/51196815
score: 0
type: AnswerComment

http://stackoverflow.com/comment/89438475
type: QuestionComment
type: Comment
has text: You can use `cv2.inRange()` and pass a tuple of HSV values
comment on: http://stackoverflow.com/q/51229355
score: 0

http://stackoverflow.com/comment/89448460
score: 0
has text: @bluesmonk i ,mean i remove the serial library and install pyserial
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51182316

http://stackoverflow.com/q/51216310
tagged with: python
has body: I have a typical newbie problem of getting the result of a function into the global scope and I can usually follow how local and global variables work in simple examples but I can having a trouble understanding what happens when there are if statements nested in for loops. Below is the original code I am working with. I am trying to the the result of thisItem in to the global scope. def getTheFirstPoint(selection): for thisItem in selection: if type(thisItem) == GSNode: print 'LOCAL', thisItem return thisItem return None I have been trying things like this: thisItem = '' def getTheFirstPoint(selection): global thisItem for thisItem in selection: if type(thisItem) == GSNode: print 'LOCAL', thisItem #return thisItem #return None getTheFirstPoint(thisItem) print 'GLOBAL:', thisItem I've seen at times the global variable doesn't need to be explicitly set outside of the function – do I need the " thisItem = ' ' "? Are the returns necessary? What do I need to do to access thisItem globally? Any help will be appreciated.
tagged with: global-variables
has title: Making variable global from if statement nested in for loop
tagged with: variables
type: UnansweredQuestion
tagged with: scope
score: 2
has answer: http://stackoverflow.com/a/51216373
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/51216495
type: Question
upvote count: 2
answer count: 2

http://stackoverflow.com/q/51175841
type: Question
tagged with: qtablewidget
possible better answer: http://stackoverflow.com/a/51176473
tagged with: pyqt4
has body: I'm trying to make a paint event that updates my GUI every 1 minute.. here is the code for main.py : # -*- coding: utf-8 -*- from PyQt4 import QtGui, QtCore import sys import main3, report import MySQLdb db = MySQLdb.connect(host="localhost", # your host, usually localhost user="root", # your username passwd="**************", # your password db="health", port=3306) # name of the data base cur = db.cursor() class report(QtGui.QMainWindow, report.Ui_Report1): def __init__(self, p_id, parent=None): super(report, self).__init__(parent) self.setupUi(self) self.lineEdit.setText('ID: ' + str(p_id)) cur.execute("SELECT * FROM patient WHERE id = '%s'"%(p_id)) pt_row_report = cur.fetchall() for row in pt_row_report: pt_name_report = row[1] pt_age_report = row[2] cur.execute("SELECT * FROM clinic WHERE p_id = '%s'"%(p_id)) clinic_row = cur.fetchone() d_id = clinic_row[2] ray_type1 = clinic_row[6] ray_type = ray_type1[17:] cur.execute("SELECT * FROM staff WHERE id = '%s'"%(d_id)) staff_row = cur.fetchall()[0] doctor_name = staff_row[1] doctor_id = staff_row[0] self.lineEdit_2.setText('Name: ' + str(pt_name_report)) self.lineEdit_3.setText('Age: ' + str(pt_age_report)) self.lineEdit_6.setText(str(ray_type)) self.lineEdit_7.setText('Dr. ' + str(doctor_name)) cur.execute("SELECT Name FROM staff WHERE id = 48588") ray_dr_name = cur.fetchone()[0] self.lineEdit_4.setText('Dr. ' + str(ray_dr_name)) self.pushButton.clicked.connect(lambda: self.update_report(p_id, ray_type,doctor_id)) def update_report(self, name, ray, d_id): x = self.textEdit.toPlainText() sql = "UPDATE clinic SET Extra_Notice = (%s) WHERE p_id=(%s)" cur.execute(sql,(x,name)) db.commit() cur.execute("INSERT INTO rays (p_ID, Ray_Type, Report, D_ID, RS_ID) VALUES (%s,%s,%s,%s,%s)", (int(name), ray, x, d_id, 48588)) db.commit() def get_text(self, x): x = self.textEdit.text() return x class First(QtGui.QMainWindow, main3.Ui_MainWindow): def __init__(self, parent=None): super(First, self).__init__(parent) self.setupUi(self)…
has title: update table with database every time interval
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/51176473
tagged with: pyqt
has answer: http://stackoverflow.com/a/51180058
accepted answer: http://stackoverflow.com/a/51180058
tagged with: python
type: AnsweredQuestion
tagged with: mysql
has comment: http://stackoverflow.com/comment/89342259
has comment: http://stackoverflow.com/comment/89342512

http://stackoverflow.com/a/51250446
type: Answer
answers question: http://stackoverflow.com/q/51249024
has body: Another alternative is to define a custom function: def transform_sentiment(x): if x &lt; 0: return 'Negative' elif x == 0: return 'Neutral' else: return 'Positive' df['Sentiment_new'] = df['Sentiment'].apply(lambda x: transform_sentiment(x))
score: 0

http://stackoverflow.com/q/51255560
answer count: 2
accepted answer: http://stackoverflow.com/a/51255663
has title: Numpy: Indices of multiple values
has answer: http://stackoverflow.com/a/51256430
possible better answer: http://stackoverflow.com/a/51256430
tagged with: python
tagged with: indices
tagged with: indexing
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51255663
type: Question
tagged with: numpy
has body: I would like to set some values of a 2D array to a specific number by indexing them efficiently. Say I have a 2D numpy array, A = array([[1, 6, 6], [9, 7, 7], [10, 2, 2]]) and I would like to get the indices in the array that belong to a set of numbers, say indList=[10, 1] so that I can set them to zero. However, indList can be a huge list. Is there a faster way for doing this without a for loop? As a for loop it would be, indList = [10, 1] for i in indList: A[A==i] = 0 But this can get inefficient when indList is large.
has comment: http://stackoverflow.com/comment/89490161
score: 0

http://stackoverflow.com/comment/89377301
type: Comment
has text: in this is your problem, simple rename it, the name of your module don't need to be equal to the name of some of the packages
comment on: http://stackoverflow.com/q/51197683
score: 0
type: QuestionComment

http://stackoverflow.com/q/51241363
has comment: http://stackoverflow.com/comment/89462160
answer count: 1
has answer: http://stackoverflow.com/a/74392147
type: UnansweredQuestion
tagged with: python
has body: How to check account API limit when using sendgrid python API? I need to know the limits and according will tweak my program to avoid hitting the API limits. Probably the limit is 600 calls per minute. But I want to know the python api endpoint which will retrieve that. The only documentation I found is: https://sendgrid.com/docs/API_Reference/Web_API_v3/How_To_Use_The_Web_API_v3/rate_limits.html How do I implement this in python API client?
has title: How to check account API limit when using sendgrid python API?
tagged with: sendgrid
type: Question
has comment: http://stackoverflow.com/comment/89461704
linked to: http://stackoverflow.com/q/17301938
score: 0

http://stackoverflow.com/comment/89439351
comment on: http://stackoverflow.com/a/51226912
type: AnswerComment
score: 0
type: Comment
has text: Thanks a lot, your solution works! I have to admit that the code I posted above is not my own. I would prefer using pandas and a more refined way of cleaning the data. But at the moment I am just experimenting with a machine translation model (of which this code is a part), to see what kind of translations it can do. And I have got some results thanks too your help.

http://stackoverflow.com/comment/89522574
type: Comment
comment on: http://stackoverflow.com/a/51271323
type: AnswerComment
has text: Thank you for suggesting the bar.shape- very helpful in reshaping and checking the result. I got it to work.
score: 0

http://stackoverflow.com/comment/89776573
has text: `py::init<...>()` works just like the "name" of the method representing the constructor (like `__init__` in Python), so I don't really know where it could go wrong. Also, why would you want argument names for a constructor without arguments (if that is what you mean with "without inputs")?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51352302
type: AnswerComment

http://stackoverflow.com/comment/89420889
has text: It does indeed. I didn't see this perspective before. I think I wouldn't be able to simply apply a ``MaxPool`` though because the output *mask* is sliced right next. That is, the position of the `0`'s and `1`'s play a part in this model.
comment on: http://stackoverflow.com/q/51218189
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51193834
answer count: 1
score: 0
tagged with: pandas
tagged with: datetime
tagged with: python
tagged with: time
type: UnansweredQuestion
tagged with: subset
has answer: http://stackoverflow.com/a/51193885
type: Question
has title: Subsetting Pandas Datetime Column (With Time Stamp) to Show Only Rows Before 3AM
has body: I have the following sample pandas data frame: ID Datetime_Col 1 2014-08-08 00:32:00 2 2016-01-25 23:25:00 3 2018-05-04 06:04:00 I want to subset it so that only rows with datetime before 3AM gets shown. I originally tried extracting out the hour from datetime and creating a new column from that to later subset on .... but I think there's a more efficient way?

http://stackoverflow.com/a/51188996
answers question: http://stackoverflow.com/q/51187751
has comment: http://stackoverflow.com/comment/89378990
type: AcceptedAnswer
downvote count: 0
has body: Your output has no newlines in the value for Pagargaph, for that you would need to have a block-style literal scalar (the dash trims the final newline, you would normally get when loading such a scalar): Pagargaph: |- Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. You should use ruamel.yaml (disclaimer: I am the author of that package), which is specifically developed to support this kind of round-tripping. To get what you want do e.g.: import sys import ruamel.yaml from ruamel.yaml.scalarstring import PreservedScalarString as L yaml_str = """\ ToGoFirst: aaa Second: 'bbb' # insert after this one Integer: 25 """ yaml = ruamel.yaml.YAML() yaml.preserve_quotes = True d = yaml.load(yaml_str) # yaml.indent(mapping=4, sequence=4, offset=2) try: before_integer = [k for k in d].index('Integer') except ValueError: before_integer = len(d) d.insert(before_integer, 'Pagargaph', L('''Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.''')) d.insert(before_integer, 'Something', 'extra', comment='with a comment') yaml.dump(d, sys.stdout) resulting in: ToGoFirst: aaa Second: 'bbb' # insert after this one Something: extra # with a comment Pagargaph: |- Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Integer: 25 Please note: the order is preserved in any version of Python supported by ruamel.yaml (2.7, 3.4+) the comment is preserved the quotes that I added around bbb are preserved only if you specify yaml.preserve_quotes = True since we insert twice at position 2, the latter bumps the former to position 3. Your users will have to be a bit disciplined for them to be able to edit a YAML file and not break it. They should also know some of the caveats, such as that plain (non-quoted) scalars, cannot start with some special characters or contain special character se…
has comment: http://stackoverflow.com/comment/89386765
has comment: http://stackoverflow.com/comment/89383850
type: Answer
has comment: http://stackoverflow.com/comment/89390326
score: 1
has comment: http://stackoverflow.com/comment/89379826
upvote count: 1
accepted answer of: http://stackoverflow.com/q/51187751

http://stackoverflow.com/comment/89520719
type: QuestionComment
has text: Well, entropy is computed using `-p*log(p)`. Looking into `inputY`, I would venture you're getting NaNs from to `log(0)` calls.
comment on: http://stackoverflow.com/q/51270927
score: 0
type: Comment

http://stackoverflow.com/comment/89605353
has text: @alexnord doing df'B','E','C'.values instead of df.values
type: Comment
comment on: http://stackoverflow.com/a/51308337
type: AnswerComment
score: 0

http://stackoverflow.com/comment/89489478
type: Comment
type: QuestionComment
has text: Do you want to do this in Python or in PHP?
comment on: http://stackoverflow.com/q/51255230
score: 0

http://stackoverflow.com/a/51312673
has comment: http://stackoverflow.com/comment/89606670
has comment: http://stackoverflow.com/comment/89609422
upvote count: 0
has comment: http://stackoverflow.com/comment/89603926
has body: You should define employee_dict as global: def employee_dictonary(self): global employee_dict Without the global keyword you are assigning to local variable. The second problem is using employee_dict = {self.id: self} for assigning to employee_dict. With that, you overwriting the variable with each call. That line should be employee_dict[self.id] = self. With that change, the output is: Employee ID:1 Salary:10 Using global variables is strongly discouraged in most cases, see Why are global variables evil?.
type: Answer
answers question: http://stackoverflow.com/q/51312587
has comment: http://stackoverflow.com/comment/89602279
has comment: http://stackoverflow.com/comment/89602132
has comment: http://stackoverflow.com/comment/89606563
has comment: http://stackoverflow.com/comment/89602166
downvote count: 1
has comment: http://stackoverflow.com/comment/89606518
has comment: http://stackoverflow.com/comment/89603880
score: -1
has comment: http://stackoverflow.com/comment/89606618

http://stackoverflow.com/a/68443271
downvote count: 1
has body: You can use a ml based solution but in such use cases I prefer to use light weight solutions which are based on opencv's features. You may use regular text detection and pair it with morphological transformations to detect header text.
type: Answer
score: 0
answers question: http://stackoverflow.com/q/51320121
upvote count: 1

http://stackoverflow.com/comment/89420230
has text: https://www.fullstackpython.com/websockets.html might be one place to start for background on the streaming part.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51219565
score: 0

http://stackoverflow.com/comment/89486050
score: 0
type: Comment
type: QuestionComment
has text: Update the question with the complete error stack trace please
comment on: http://stackoverflow.com/q/51246962

http://stackoverflow.com/comment/89407480
comment on: http://stackoverflow.com/a/51213247
score: 1
type: AnswerComment
type: Comment
has text: it's as if i did not write wait = WebDriverWait(driver, 10) , i dont know but i think it's a problem with the software not the code

http://stackoverflow.com/a/51181277
score: 3
has body: If you want to take a mean of Value for each Valuegroup and show them with line chart, use csv_loader.groupby('Valuegroup')['Value'].mean().plot() There are various chart types available, please refer to pandas documentation on plot
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/51181171
has comment: http://stackoverflow.com/comment/89441244
answers question: http://stackoverflow.com/q/51181171
upvote count: 3
has comment: http://stackoverflow.com/comment/89438666

http://stackoverflow.com/comment/89371888
has text: Hey, i have posted an edit on top of the code message as it is to big to post here? Is that how I would do it? I don't know how I would make the bot tell if a command is executed
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51191963

http://stackoverflow.com/comment/89383037
score: 0
type: AnswerComment
has text: Entering ``aapl`` yields an empty list
type: Comment
comment on: http://stackoverflow.com/a/51200716

http://stackoverflow.com/q/51242638
tagged with: arrays
score: 0
has answer: http://stackoverflow.com/a/51242811
tagged with: http://stackoverflow.com/tag/csv
answer count: 1
type: UnansweredQuestion
tagged with: python
has title: Reading and writing to/from csv files
has body: I want my program to read 2 columns (the first and the second one) and add them to an array. They are dependent on eachother - so they need to be written alongside eachother, as in the first row (both columns) next to eachother, and then the second row and so on. I have managed to write the first column (containing the names) to the array, however have not managed to write the second column to the array. rownum=1 array=[] for row in reader: if row[1] != '' and row[1] != 'Score': array.append(row[1]) rownum=rownum+1 if rownum==11: break I attempted to append more than one row however it returns the error message 'only accepts one argument'. Any ideas how I can do this so i can reference the score for each name from the csv file
type: Question

http://stackoverflow.com/comment/89480238
comment on: http://stackoverflow.com/a/51246946
score: 1
type: AnswerComment
has text: Great effort...I really did not know that
type: Comment

http://stackoverflow.com/q/51278619
linked to: http://stackoverflow.com/q/41064286
has comment: http://stackoverflow.com/comment/89534928
has answer: http://stackoverflow.com/a/51278814
has comment: http://stackoverflow.com/comment/89534878
tagged with: pandas
has comment: http://stackoverflow.com/comment/89534880
upvote count: 1
has comment: http://stackoverflow.com/comment/89534955
linked to: http://stackoverflow.com/q/2400643
answer count: 1
has comment: http://stackoverflow.com/comment/89535067
has comment: http://stackoverflow.com/comment/89534840
favorite count: 0
has comment: http://stackoverflow.com/comment/89534826
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/89534770
tagged with: python
has body: For my project I have to parse two big JSON files, one is 19.7 GB and another 66.3 GB. The structure of the JSON data is too complex. First Level Dictionary and again in 2nd level there might be List or Dictionary. These are all Network Log files, I have to parse those log files and do analysis. Is converting such big JSON file to CSV is advisable? When I am trying to convert the smaller 19.7 GB JSON file to CSV file, it is having around 2000 columns and 0.5 millions of rows. I am using Pandas to parse those data. I have not touched the bigger file 66.3 GB. Whether I am going in right direction or not? When I 'll convert that bigger file, how many columns and rows will come out, there is no idea. Kindly suggest any other good options if exists. Or is it advisable to directly read from JSON file and apply OOPs concept over it. I have already read these articles: article 1 from Stack Overflow and article 2 from Quora
downvote count: 0
has title: What are the efficient ways to parse / process huge JSON files in Python?
score: 1
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/89534942
type: Question

http://stackoverflow.com/comment/89345739
type: QuestionComment
has text: Please read `groupby`'s implementation-equivalent python code: https://docs.python.org/3/library/itertools.html#itertools.groupby , which costs just O(n), while your implementation costs O(n^2).
score: 2
type: Comment
comment on: http://stackoverflow.com/q/51181674

http://stackoverflow.com/a/51310965
has body: Simply create open grids, that are basically 1D arrays extended to more dims and add into input array leveraging broadcasting - m,n,r = a.shape I,J,K = np.ogrid[:m,:n,:r] out = a + I*n*r + J*r + K Hence, in terms of memory occupancy, we are creating only 9 (=m+n+r) more elements as opposed to 27 (= m * n * r) elements with the range-based soltuion. Sample run - In [41]: a Out[41]: array([[[0, 0, 0], [1, 1, 1], [0, 0, 0]], [[1, 0, 1], [1, 0, 1], [1, 0, 1]], [[1, 0, 0], [1, 1, 0], [1, 1, 1]]]) In [42]: m,n,r = a.shape In [43]: I,J,K = np.ogrid[:m,:n,:r] In [44]: a + I*n*r + J*r + K Out[44]: array([[[ 0, 1, 2], [ 4, 5, 6], [ 6, 7, 8]], [[10, 10, 12], [13, 13, 15], [16, 16, 18]], [[19, 19, 20], [22, 23, 23], [25, 26, 27]]]) N-dim array case For a generic n-dim array, a to add into itself - shp = a.shape grid = np.ogrid[tuple(map(slice, shp))] scale = np.r_[np.array(shp)[::-1].cumprod()[::-1][1:],1] for i,j in zip(grid,scale): a += i*j
type: Answer
upvote count: 3
has comment: http://stackoverflow.com/comment/89598807
accepted answer of: http://stackoverflow.com/q/51310712
score: 3
answers question: http://stackoverflow.com/q/51310712
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/51167506
has comment: http://stackoverflow.com/comment/89318277
type: Question
tagged with: python
tagged with: object-detection
has body: I have a pretrained CocoModel from Tensorflow OD, and retrained it on a kitti dataset. I just wanted to try a classification on a croped Image, but there is no clear documentation what er the names of the tensors. When I tried to use the classify script by Tensorflow, it says that there are no Tensors named like this in the inceptionV3 model. Is there anyone that has already tried it and know the name of the tensors? The Result should be a list of possible labels/classes with their scores! Thanks in advance for your help Hi! thank you for the fast reply. To get a overview: I have used a pertained model from MSCOCO for object detection I have trained the model on a KITTI Dataset with 100 Images I have exported the inference_graph an classified the other images. I provided a Labeling tool for Users to get the Machinelabeled Images and correct them. As a feature I wanted to implement : a) Drawing own bounding boxes and Label them (works fine with Canvas and Angular) b) Send this cropped Bounding Box to my server and get Class Suggestions from my model => here is the problem !!! I need the names of the tensor to do a classification. I tried to rewrite a own of tensorflows classify_image.py https://github.com/tensorflow/models/blob/master/tutorials/image/imagenet/classify_image.py
upvote count: 1
tagged with: tensorflow
tagged with: mscoco
has comment: http://stackoverflow.com/comment/89366646
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51216916
has title: Getting a classification on a croped image from tensorflow with inceptionV3 Model
downvote count: 0
answer count: 1
score: 1
favorite count: 0

http://stackoverflow.com/comment/92524068
type: QuestionComment
has text: Sorry, I thought that was obvious. I reopened and gave an answer.
type: Comment
comment on: http://stackoverflow.com/q/51231320
score: 0

http://stackoverflow.com/comment/89518533
comment on: http://stackoverflow.com/q/51270197
type: Comment
has text: Try uninstalling it and re-installing it
score: 0
type: QuestionComment

http://stackoverflow.com/comment/89619537
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51277895
score: 0
has text: @phd it's seems here is Miniconda installed in system, not sure but this could be the cause of error. I have Uninstalled it and tried again which shows me successful installation message of Ride.

http://stackoverflow.com/q/51242987
score: 0
has body: I am trying to use the skimage.transform image modules to find and assess the fluorescence of circles on a slide. So far the modules are working very well indeed. However I have one small issue I cannot seem to fix. When using skimage.transform.hough_circle_peaks() I found the same pots were being identified multiple times, instead of all spots across the slide. Whole slide image: enter image description here Screen shot of where circles are being stacked on the same spots: enter image description here I tried to remedy this by using the following: min_xdistance : int, optional Minimum distance separating centers in the x dimension. min_ydistance : int, optional Minimum distance separating centers in the y dimension. I set these both to 1000 pixels, which given that each circle has a radius of ~33 pixels, should mean no circle will be identified twice, and no circles adjacent should be selected either. However I now see this: enter image description here You can see that while fewer circles are found, two are still places on top of each other. Does anyone have any thoughts or experience with this?
tagged with: python
has title: Python: skimage.transform.hough_circle_peaks() min_xdistance and min_ydistance errors
has comment: http://stackoverflow.com/comment/89473506
has comment: http://stackoverflow.com/comment/89493438
answer count: 0
type: UnansweredQuestion
tagged with: image-processing
type: Question
has comment: http://stackoverflow.com/comment/89493397
has comment: http://stackoverflow.com/comment/89498560
tagged with: scikit-image

http://stackoverflow.com/comment/89454096
type: Comment
score: 0
comment on: http://stackoverflow.com/q/51237537
type: QuestionComment
has text: You can try `df = pd.read_csv('csvfile.csv' ,na_filter=False)` but that will not detect any missing value markers.

http://stackoverflow.com/comment/89529768
type: Comment
comment on: http://stackoverflow.com/a/51263991
type: AnswerComment
has text: when I do `@on_ready.error` it spits out `AttributeError: 'function' object has no attribute 'error'`
score: 0

http://stackoverflow.com/comment/89319756
comment on: http://stackoverflow.com/q/51168268
has text: You might like to consider a LUT... https://stackoverflow.com/a/50598388/2836621
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/q/51287665
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/20109391
score: 1
has comment: http://stackoverflow.com/comment/89554234
upvote count: 1
type: Question
tagged with: indexing
has comment: http://stackoverflow.com/comment/89552958
tagged with: date
has comment: http://stackoverflow.com/comment/89553770
has title: Get index of where group starts and ends pandas
answer count: 2
tagged with: pandas
has answer: http://stackoverflow.com/a/51288247
tagged with: grouping
downvote count: 0
has comment: http://stackoverflow.com/comment/89628382
has answer: http://stackoverflow.com/a/51288339
favorite count: 0
has body: I grouped my data by month. Now I need to know at which observation/index my group starts and ends. What I have is the following output where the second column represents the number of observation in each month: date 01 145 02 2232 03 12785 04 16720 Name: date, dtype: int64 with this code: leave.groupby([leave['date'].dt.strftime('%m')])['date'].count() What I want though is an index range I could access later. Somehow like that (the format doesn't really matter and I don't mind if it returns a list or a data frame) date 01 0 - 145 02 146 - 2378 03 2378 - 15163 04 15164 - 31884

http://stackoverflow.com/a/51240098
upvote count: 5
has body: This below code worked import jenkins import os os.environ.setdefault("PYTHONHTTPSVERIFY", "0") jen = jenkins.Jenkins(url="https://&lt;hostname&gt;:9080/" ,username="user", password="&lt;password/API token&gt;") print jen.get_whoami()
downvote count: 0
answers question: http://stackoverflow.com/q/51210340
type: Answer
score: 5

http://stackoverflow.com/comment/89472117
has text: Can you update the question with _Selenium_, _Python_ and _GeckoDriver_ and _Firefox_ version information?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51223809

http://stackoverflow.com/q/51318263
has title: How to use user's pipenv via systemd? Python is installed via SCL
type: Question
tagged with: systemd
tagged with: pipenv
has comment: http://stackoverflow.com/comment/89612477
answer count: 1
downvote count: 0
favorite count: 0
has body: On a CentOS 7 server, I have installed Python 3.6 via SCL. ( https://www.softwarecollections.org/en/scls/rhscl/rh-python36/) I have this line in .bashrc to enable SCL's Python 3.6 source scl_source enable rh-python36 I have installed pipenv: pip install --user pipenv I run Python programs via the command line: pipenv run python myprogram.py All these work great. I have a Flask application that uses the user's pipenv. I am trying to create a systemd unit file to start/stop/reload the Flask web application. How can I get the sytemd unit file to use the user's pipenv installed via SCL's Python and pip? I tried to execute the command line from root and I get this error: [root@localhost ~]# source scl_source enable rh-python36 [root@localhost ~]# /home/user/.local/bin/pipenv run python /home/user/hello.py Traceback (most recent call last): File "/home/user/.local/bin/pipenv", line 7, in &lt;module&gt; from pipenv import cli ModuleNotFoundError: No module named 'pipenv' However, I am able to execute the command via su -c by loading user's bash shell: su -c 'bash -lc /home/user/.local/bin/pipenv run python hello.py' user But this line seems awkward. What is a the correct line I could use in systemd unit file's ExecStart line? What environment variables should be included in order to use the user's pipenv?
tagged with: software-collections
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/51374200
score: 2
upvote count: 2

http://stackoverflow.com/q/51174718
has comment: http://stackoverflow.com/comment/89332803
has body: I accidentally deleted my migrations folders for all my apps including __init__.py. Is there any way to reset or retrieve these? Thank you!
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/51175021
favorite count: 0
has comment: http://stackoverflow.com/comment/89332848
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/89332820
type: AnsweredQuestion
score: 3
upvote count: 3
accepted answer: http://stackoverflow.com/a/51175021
type: Question
has title: Deleted Django Migrations Folder
has comment: http://stackoverflow.com/comment/89332170

http://stackoverflow.com/comment/90881124
type: AnswerComment
comment on: http://stackoverflow.com/a/51948979
score: 0
has text: Thanks Scott, the syntax is a bit complex for me, but this does work, great!
type: Comment

http://stackoverflow.com/a/51315890
type: Answer
score: 0
answers question: http://stackoverflow.com/q/51315746
has body: Another way to do it: reversed = ''.join([word[len(word) - count] for count in range(1,len(word)+1)]) (replace range with xrange for Python 2)

http://stackoverflow.com/comment/89555281
has text: When `g` is being defined, the scope of `f` has already been established, allowing the parser to recognize if `x` is in scope, even if `f` itself doesn't actually provide an assignment until *after* `def g` is parsed. (I'm assuming it's not strictly a syntax error in the sense of the code not being parseable, but rather a static analysis step taken after the source for `f` is actually fully parsed.)
comment on: http://stackoverflow.com/a/51288548
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/89488000
type: Comment
has text: i have internet permissions enabled in the .spec
comment on: http://stackoverflow.com/a/51247449
score: 0
type: AnswerComment

http://stackoverflow.com/comment/139737931
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51213767
has text: Help! I followed this advice and got my tests working with these full relative paths, but now my main code won't run from terminal as I get `ModuleNotFoundError: No module named 'python'` when importing modules like `python/src/functions.csv`

http://stackoverflow.com/q/51243465
has title: How to integrate Stripe payments gateway with Django Oscar?
type: Question
possible better answer: http://stackoverflow.com/a/51246987
has answer: http://stackoverflow.com/a/51246987
downvote count: 0
tagged with: django-oscar
tagged with: stripe-payments
has answer: http://stackoverflow.com/a/51348350
has answer: http://stackoverflow.com/a/78595990
answer count: 3
tagged with: python
favorite count: 0
tagged with: stripe.js
linked to: http://stackoverflow.com/q/33238655
tagged with: django
upvote count: 7
accepted answer: http://stackoverflow.com/a/51348350
type: AnsweredQuestion
has body: I am trying to integrate the Stripe payment gateway to Django oscar for an e-commerce site which sells physical goods like groceries online.I use python 3.6.3, Django 2.0, Django-oscar 1.6, stripe 1.82.2. Method 1: So I followed this link in django-oscar groups: https://groups.google.com/forum/#!searchin/django-oscar/handle_payment$20override%7Csort:date/django-oscar/Cr8sBI0GBu0/PHRdXX2uFQAJ I have signed up for a stripe account and used my publishable key and test key to configure stripe.The problem is, when I try to pay using the button provided with label "Pay with Card",it collects my card information and then when I click the button, it shows "Some money will be debited from the card" like in this image: Image of Preview page Then after I click the place order button,it shows me this: Image of confirmation page Though I have paid using my card. I guess oscar doesn't seem to know that the payment has been done through stripe already?But I'm not sure how to solve this. Method 2: I tried to use dj-stripe,found here: https://github.com/dj-stripe/dj-stripe But I read the whole documentation on https://dj-stripe.readthedocs.io/en/stable-1.0/ , it seems like I can use it only for products that need subscriptions, mine don't require subscribing and the docs for dj-stripe aren't fully complete. I tried with the official django-oscar repo, the link is here: https://github.com/django-oscar/django-oscar-stripe , this repository is like five years old and I don't think it would be compatible to use with my version of Django oscar. Method 3: I tried using the stripe.js and elements and created my form to accept cards: < script src = "https://js.stripe.com/v3/" > < /script> < script > var stripe = Stripe('your_stripe_publishable_key'); var elements = stripe.elements(); // Custom styling can be passed to options when creating an Element. var style = { base: { color: '#32325d', lineHeight: '18px', fontFamily: '"Helvetica Neue", Helvetica, sans-serif', fontSmoothing: 'antialiase…
score: 7
has comment: http://stackoverflow.com/comment/89502105

http://stackoverflow.com/comment/89482292
comment on: http://stackoverflow.com/a/51251620
score: 0
type: AnswerComment
type: Comment
has text: @abarnert I know It's not speed-wise ideal way to do it, but for inspiration It could be useful.

http://stackoverflow.com/q/51291281
downvote count: 1
tagged with: python
has body: So I have many lists of tuples pulled from a database in the format: dataA = [('A', 'B', 'C', D, E, F), ('A', 'B', 'C', D, E, F), ...] Then I have a list of tuples in the format: dataB = [('X', 'A', 'B', 'C', Y), ('X', 'A', 'B', 'C', Y), ...] I need to match the tuples from dataA to dataB by matching 'A' = 'A', 'B' = 'B', 'C' = 'C' and where D > Y > E. Where the tuples match, I will use the values 'X' and 'F'. 'A', 'B', 'C', 'X' are strings up to 16 characters. D, E, F, Y are integers. I've tried many ways to do this (string compare, nested for-loops, set intersection) but they all are very slow. What would be the best way to accomplish this? Thank you very much
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89561131
tagged with: list
tagged with: performance
has comment: http://stackoverflow.com/comment/89560427
has comment: http://stackoverflow.com/comment/89560301
has comment: http://stackoverflow.com/comment/89561507
type: Question
has comment: http://stackoverflow.com/comment/89561483
answer count: 1
tagged with: sorting
has title: Fast search of lists of tuples
tagged with: tuples
score: 0
has comment: http://stackoverflow.com/comment/89561091
has answer: http://stackoverflow.com/a/51291806
upvote count: 1

http://stackoverflow.com/a/51182809
score: 0
has comment: http://stackoverflow.com/comment/89352676
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51182776
answers question: http://stackoverflow.com/q/51182776
type: Answer
has body: If minz is already a tuple type, you can assign x,y,z to each tuple value. z, y, x = minz

http://stackoverflow.com/q/51237507
tagged with: python-3.x
has title: Which is better - execute(INSERT) or executemany(INSERT)
upvote count: 3
has body: Situation: Need to insert quite a bit of data into a SQLite database. Problem: There are two statements we can use to insert data - data = [("111", "222", "333"), ("AAA", "BBB", "CCC"), ("XXX", "YYY", "ZZZ")] #method1 for item in data: cursor.execute("INSERT INTO table(value1, value2, value3) VALUES (?,?,?)", item) conn.commit() #method2 cursor.execute("INSERT INTO table(value1, value2, value3) VALUES(?,?,?)", data) conn.commit() Question: If ignoring speeds, which one is better practice from a programming point of view? And if possible, explain why as well.
tagged with: pysqlite
type: Question
type: AnsweredQuestion
score: 3
accepted answer: http://stackoverflow.com/a/51237552
downvote count: 0
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/51237552
tagged with: sqlite
tagged with: python

http://stackoverflow.com/comment/89592333
has text: @WilliamZimmermann How do they expect you to be productive while blocking access to mandatory development tools? I can't see how you could develop a decent django application without being able to have your own local database. Does that mean that every developer shares the same database during development?
score: 0
comment on: http://stackoverflow.com/q/51307379
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89574108
comment on: http://stackoverflow.com/q/51285457
score: 0
type: Comment
type: QuestionComment
has text: I would try playing with https://docs.djangoproject.com/en/2.0/ref/contrib/admin/#django.contrib.admin.ModelAdmin.get_search_results

http://stackoverflow.com/q/51214057
tagged with: jupyter-notebook
has comment: http://stackoverflow.com/comment/89586731
tagged with: tkinter
downvote count: 0
answer count: 0
score: 1
has comment: http://stackoverflow.com/comment/89585420
has comment: http://stackoverflow.com/comment/89409117
type: Question
has title: call an external program from the tab tkinter notebook
upvote count: 1
favorite count: 0
has body: I created a widget with python tkinter notebook. I have to manage a tab on an external program, in this case a table maintenance proscram in MySQL. com do you recall the external program and manage it in the tab.
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/a/51315470
has comment: http://stackoverflow.com/comment/89778957
score: 0
has comment: http://stackoverflow.com/comment/89643493
has comment: http://stackoverflow.com/comment/89755175
accepted answer of: http://stackoverflow.com/q/51309808
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51309808
type: Answer
has comment: http://stackoverflow.com/comment/89795133
has comment: http://stackoverflow.com/comment/89619701
has body: From the URL in your question, it might be the URL of the web published spreadsheet. If my understanding is not wrong, unfortunately, the URL cannot be directly retrieved by Drive API and other APIs. But the same link can be created using file ID of spreadsheet. If you can retrieve the file ID, could you please try the following URL? You can select one of them. https://docs.google.com/spreadsheet/pub?key=### fileId ### or https://docs.google.com/spreadsheets/d/### fileId ###/pubhtml If I misunderstand your question, I'm sorry.
has comment: http://stackoverflow.com/comment/89732600

http://stackoverflow.com/comment/89430538
comment on: http://stackoverflow.com/q/51224609
has text: The one you look for is within `script` tag. There are several `script` tags available in that page. Try `soup.find_all("script")[-3]` which will fetch you the third last `script` in which you will get necessary information you are trying to parse. If you think of any alternative then try using any browser simulator like `selenium`.
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/a/51232397
has comment: http://stackoverflow.com/comment/89455004
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/89444031
type: Answer
accepted answer of: http://stackoverflow.com/q/51232315
answers question: http://stackoverflow.com/q/51232315
upvote count: 3
has comment: http://stackoverflow.com/comment/89443984
score: 3
has body: I believe you are looking for inspect.getsourcefile() As per the documentation, inspect.getsourcefile(object) Return the name of the Python source file in which an object was defined. This will fail with a TypeError if the object is a built-in module, class, or function. Here is what I get when tested with join function: &gt;&gt;&gt; import inspect &gt;&gt;&gt; from os.path import join &gt;&gt;&gt; inspect.getsourcefile(join) 'C:\\Users\\ankit\\...\\Python\\Python36\\lib\\ntpath.py'

http://stackoverflow.com/comment/89481176
type: Comment
type: QuestionComment
has text: Thanks for that useful comment.
comment on: http://stackoverflow.com/q/51251095
score: 0

http://stackoverflow.com/comment/89614388
comment on: http://stackoverflow.com/a/51278690
score: 0
type: AnswerComment
type: Comment
has text: @jezrael yeah u are right...pattern change can create probelm in the data.

http://stackoverflow.com/q/51196874
favorite count: 0
tagged with: beautifulsoup
tagged with: python
has answer: http://stackoverflow.com/a/51197147
accepted answer: http://stackoverflow.com/a/51197147
type: AnsweredQuestion
score: 1
tagged with: web-scraping
upvote count: 1
type: Question
has title: Python BeautifulSoup searching
answer count: 1
downvote count: 0
has body: Is there a way to find a single div with more classes? Div classes are: class="srp-main-content clearfix srp-main-content--flex". Thank you in advance!

http://stackoverflow.com/comment/89504075
score: 1
type: AnswerComment
has text: Thanks a lot!. :) I was just doing the astype(str) conversion. Thanks!
type: Comment
comment on: http://stackoverflow.com/a/51262507

http://stackoverflow.com/q/51238387
has body: I am getting this error on Heroku: 2018-07-09T04:37:55.732211+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=newcri.herokuapp.com request_id=b04ee149-4ed1-442f-beb1-4b71c9fd492f fwd="49.34.129.7" dyno= connect= service= status=503 bytes= protocol=https Project url is https://github.com/ravikkanani/newapi
tagged with: deployment
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89532622
tagged with: heroku
has comment: http://stackoverflow.com/comment/89456496
type: Question
has title: On heroku app not working code=H10
score: 0
tagged with: python

mongodb
tags question: http://stackoverflow.com/q/51223570
tags question: http://stackoverflow.com/q/51244329
tags question: http://stackoverflow.com/q/51176651
tags question: http://stackoverflow.com/q/51277787
tag name: mongodb
tags question: http://stackoverflow.com/q/51316992
tags question: http://stackoverflow.com/q/51312891
type: Tag
tags question: http://stackoverflow.com/q/51322535
tags question: http://stackoverflow.com/q/51246163
tags question: http://stackoverflow.com/q/51270810
tags question: http://stackoverflow.com/q/51203628
tags question: http://stackoverflow.com/q/51240581
tags question: http://stackoverflow.com/q/51242939
tags question: http://stackoverflow.com/q/51210367
tags question: http://stackoverflow.com/q/51295266
tags question: http://stackoverflow.com/q/51258258
tags question: http://stackoverflow.com/q/51220364
tags question: http://stackoverflow.com/q/51232936

http://stackoverflow.com/q/51261926
tagged with: python
has answer: http://stackoverflow.com/a/51262730
has comment: http://stackoverflow.com/comment/89502424
type: AnsweredQuestion
tagged with: screen-scraping
possible better answer: http://stackoverflow.com/a/51262730
tagged with: web-scraping
tagged with: scrapy
accepted answer: http://stackoverflow.com/a/51263847
type: Question
has title: Crawled 0 pages (at 0 pages/min), scraped 0 items
has body: Hello beautiful programmers! I am facing an issue which i am unable to resolve.Please help me. I am trying to scrape an olx.com.pk using this link but i am getting no result at all.Please help me, I would be very thankful to you. I have tried different things but it won't work.PLEASE HELP ME. P.S : I have checked it on scrapy shell import scrapy from scrapy.spiders import CrawlSpider, Rule from scrapy.linkextractors import LinkExtractor from olx.items import OlxItem class ElectronicsSpider(CrawlSpider): name = "electronics" allowed_domains = ["www.olx.com.pk"] start_urls = [ 'https://www.olx.com.pk/computers-accessories/' ] rules = ( Rule(LinkExtractor(allow=(), restrict_css=('.pageNextPrev',)), callback="parse_item", follow=False),) def parse_item(self, response): item_links = response.css('.large &gt; .detailsLink::attr(href)').extract() for a in item_links: yield scrapy.Request(a, callback=self.parse_detail_page) def parse_detail_page(self, response): title = response.css('h1::text').extract()[0].strip() price = response.css('.pricelabel &gt; strong::text').extract()[0] item = OlxItem() item['title'] = title item['price'] = price item['url'] = response.url yield item OUPUT IS LIKE THIS : scrapy crawl electronics 2018-07-10 14:29:33 [scrapy] INFO: Scrapy 1.0.3 started (bot: olx) 2018-07-10 14:29:33 [scrapy] INFO: Optional features available: ssl, http11, boto 2018-07-10 14:29:33 [scrapy] INFO: Overridden settings: {'NEWSPIDER_MODULE': 'olx.spiders', 'FEED_FORMAT': 'csv', 'SPIDER_MODULES': ['olx.spiders'], 'FEED_URI': 'logs/%(name)s/%(time)s.csv', 'BOT_NAME': 'olx'} 2018-07-10 14:29:34 [scrapy] INFO: Enabled extensions: CloseSpider, FeedExporter, TelnetConsole, LogStats, CoreStats, SpiderState 2018-07-10 14:29:34 [boto] DEBUG: Retrieving credentials from metadata server. 2018-07-10 14:29:35 [boto] ERROR: Caught exception reading instance data Traceback (most recent call last): File "/usr/lib/python2.7/dist-packages/boto/utils.py", line 210, in retry_url r = opener.…
tagged with: python-2.7
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/51263847

http://stackoverflow.com/q/51317953
favorite count: 0
has answer: http://stackoverflow.com/a/51318632
answer count: 5
has answer: http://stackoverflow.com/a/51318113
tagged with: python
has answer: http://stackoverflow.com/a/51319518
tagged with: python-3.x
score: 1
accepted answer: http://stackoverflow.com/a/51318053
has comment: http://stackoverflow.com/comment/89612443
has comment: http://stackoverflow.com/comment/89611908
tagged with: loops
upvote count: 1
type: Question
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/51318112
has body: I want to do the looping with condition. In [1] : data_1 Out [1] : text1 text2 In [2] : data_2 Out [2] : a b c d e I want every text in data_1 only works for 2 text in data_2. So, the output will be like this. text1, a text1, b text2, c text2, d and it will be stop if data_1 didn't have any data. I typed the script like this, but didn't work. for i in range(len(data_1)): for j in range(0, len(data_2)): print(i, j) and the output showed like this. 0 0 0 1 0 2 0 3 0 4 1 0 1 1 1 2 1 3 1 4
has answer: http://stackoverflow.com/a/51318112
has title: Looping with condition
downvote count: 0
has answer: http://stackoverflow.com/a/51318053

http://stackoverflow.com/comment/89448503
comment on: http://stackoverflow.com/q/51234758
type: Comment
type: QuestionComment
score: 0
has text: What have you tried so far? Including a snippet of your html and other code to create a [minimal, complete, and verifiable example](https://stackoverflow.com/help/mcve) will help us understand your specific situation.

http://stackoverflow.com/comment/89525428
score: 3
has text: Hm, I think I just fixed my problem by merely making `pool` a global variable. Memory usage stays constant now.
type: AnswerComment
comment on: http://stackoverflow.com/a/51273554
type: Comment

http://stackoverflow.com/q/51199565
score: 2
answer count: 1
downvote count: 0
has title: Python: Group list of objects based on id and timeframe
favorite count: 0
upvote count: 2
tagged with: datetime
tagged with: python
has answer: http://stackoverflow.com/a/51199830
type: AnsweredQuestion
has body: I am working with a list of objects which has sys_id and datetime as two of its fields. I would like to group these objects based on sys_id and datetime if the time gap between each object is less than 5 minutes. For instance, if my data is test_id sys_id time 1 11 1/1/2018 6:03 2 11 1/1/2018 6:07 3 11 1/1/2018 6:11 4 11 1/1/2018 6:14 5 12 1/2/2018 15:25 6 12 1/3/2018 15:30 7 12 1/4/2018 15:33 8 12 1/5/2018 15:37 I would like to group test_ids 01,02,03,04 as one list as they have same sys_id and time gap between each of the tests is less than 5 minutes and test_ids 05,06,07,08 as another group.
has comment: http://stackoverflow.com/comment/89380812
accepted answer: http://stackoverflow.com/a/51199830
type: Question
tagged with: python-itertools
tagged with: group-by
tagged with: sorting

http://stackoverflow.com/a/51211212
score: 2
has comment: http://stackoverflow.com/comment/89424221
type: Answer
upvote count: 2
has comment: http://stackoverflow.com/comment/89423579
answers question: http://stackoverflow.com/q/51210505
has comment: http://stackoverflow.com/comment/89787706
downvote count: 0
has body: there have been a lot of similar problems reported on https://community.plone.org/ the problem most probably is the migration from in pypi.python.org to pypi.org you can add: index = https://pypi.org/simple/ and if you are using allowed hosts you need 2 new ones and can skip *.python.org: allow-hosts = pypi.org files.pythonhosted.org alternatively you can use a current versions of setuptools and zc.buildout attention: for setuptools > 38.7.0 you need to pin plone.recipe.zope2instance = 4.4.0 (see https://github.com/plone/plone.recipe.zope2instance/blob/4.4.0/CHANGES.rst)

http://stackoverflow.com/q/51263783
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89511204
tagged with: pairwise
type: Question
upvote count: 2
tagged with: numpy
has answer: http://stackoverflow.com/a/51269426
accepted answer: http://stackoverflow.com/a/51269426
tagged with: arrays
downvote count: 0
has comment: http://stackoverflow.com/comment/89514118
answer count: 1
favorite count: 0
tagged with: tuples
has comment: http://stackoverflow.com/comment/89512105
tagged with: python
has comment: http://stackoverflow.com/comment/89512084
has title: Creating tuples of multiples from pairs of indices
has body: Given a numpy array, which can be subset to indices for array elements meeting given criteria. How do I create tuples of triplets (or quadruplets, quintuplets, ...) from the resulting pairs of indices ? In the example below, pairs_tuples is equal to [(1, 0), (3, 0), (3, 1), (3, 2)]. triplets_tuples should be [(0, 1, 3)] because all of its elements (i.e. (1, 0), (3, 0), (3, 1)) have pairwise values meeting the condition, whereas (3, 2) does not. a = np.array([[0. , 0. , 0. , 0. , 0. ], [0.96078379, 0. , 0. , 0. , 0. ], [0.05498203, 0.0552454 , 0. , 0. , 0. ], [0.46005028, 0.45468466, 0.11167813, 0. , 0. ], [0.1030161 , 0.10350956, 0.00109096, 0.00928037, 0. ]]) pairs = np.where((a &gt;= .11) &amp; (a &lt;= .99)) pairs_tuples = list(zip(pairs[0].tolist(), pairs[1].tolist())) # [(1, 0), (3, 0), (3, 1), (3, 2)] How to get to the below? triplets_tuples = [(0, 1, 3)] quadruplets_tuples = [] quintuplets_tuples = []
has comment: http://stackoverflow.com/comment/89513229
score: 2

http://stackoverflow.com/q/51178256
type: Question
linked to: http://stackoverflow.com/q/9097994
has comment: http://stackoverflow.com/comment/89354362
tagged with: dataframe
accepted answer: http://stackoverflow.com/a/51186621
tagged with: typeerror
answer count: 2
tagged with: pandas
downvote count: 0
favorite count: 0
has body: I try to translate a column of a Pandas Data Frame into int values using a mapping like this (asuming a given dataframe: my_dataframe and a colum: target_column): targets = my_dataframe[target_column].unique() map_to_int = {name: n for n, name in enumerate(targets)} Using Python 3.6 with Pandas I wonder why A) my_dataframe['Integer-Column'] = map_to_int[my_dataframe[target_column]] causes a TypeError: 'Series' objects are mutable, thus they cannot be hashed whileas B) my_dataframe['Integer-Column'] = my_dataframe[target_column].replace(map_to_int) works fine. I would like to understand why this happens. Is there any magic in replace that the TypeError is not thrown or am I missing something else? I already got the fact, that dict-keys are not allowed to be changeable. But still I have a hard time understanding this for real, since: words = my_dataframe[target_column].unique() # words = ['car' 'bike' 'plain'] foo = 'car' map_to_int[foo] = 0 foo = 'bike' map_to_int["bike"] = 1 Any attempt to help me understand why B) works without the trouble of A) would be appreciated.
linked to: http://stackoverflow.com/q/49259580
has title: TypeError while mapping DataFrame Columns using Python dict
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/51186621
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/51187066
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/51187066

http://stackoverflow.com/comment/89422333
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51220732
has text: @PRMoureu I see. I know this can be achieved easily through selenium but its slow. Can this be done in any way through web scraping?

http://stackoverflow.com/comment/89454266
type: QuestionComment
comment on: http://stackoverflow.com/q/51237591
has text: I doubt that you might have multiple python env or your PATH is incorrect.Use virtual environment(Google:venv) and install all the requirements in the venv and it may solve your problem.
score: 0
type: Comment

http://stackoverflow.com/q/51278380
has answer: http://stackoverflow.com/a/51279667
has comment: http://stackoverflow.com/comment/89534578
has answer: http://stackoverflow.com/a/51280371
has answer: http://stackoverflow.com/a/51278717
has answer: http://stackoverflow.com/a/51279734
answer count: 8
has comment: http://stackoverflow.com/comment/89534790
has comment: http://stackoverflow.com/comment/89536990
type: Question
has answer: http://stackoverflow.com/a/51278676
has answer: http://stackoverflow.com/a/51279100
has answer: http://stackoverflow.com/a/60236289
has comment: http://stackoverflow.com/comment/89534437
score: 0
has body: Problem statement: Have the function LetterChanges(str) take the str parameter being passed and modify it using the following algorithm. Replace every letter in the string with the letter following it in the alphabet (ie. c becomes d, z becomes a). Then capitalize every vowel in this new string (a, e, i, o, u) and finally return this modified string. My Python program is: def LetterChanges(str): for i in range(0,len(str)): a=ord(str[i]) if a==122: str=str.replace(str[i],'a',1) elif a==90: str=str.replace(str[i],'a',1) elif (a&gt;=65 and a&lt;=90) or (a&gt;=97 and a&lt;=122): a=a+1 char=chr(a) str=str.replace(str[i],char,1) for i in range(0,len(str)): if str[i]=='a': str=str.replace(str[i],'A',1) elif str[i]=='e': str=str.replace(str[i],'E',1) elif str[i]=='i': str=str.replace(str[i],'I',1) elif str[i]=='o': str=str.replace(str[i],'O',1) elif str[i]=='u': str=str.replace(str[i],'U',1) return(str) print LetterChanges(raw_input()) The problem with my code is that, when I input sen, the output was tfo which was correct. But when I gave sent as my input, I got the wrong output.
has answer: http://stackoverflow.com/a/51279502
tagged with: python
has title: Letter Change using Python
type: UnansweredQuestion

http://stackoverflow.com/comment/89493856
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/51257538
has text: When I run this in Python 2, it crashes on the `copytree` line, saying `OSError: [Errno 2] No such file or directory: 'A/b/b1'`

http://stackoverflow.com/q/51316508
accepted answer: http://stackoverflow.com/a/51316959
possible better answer: http://stackoverflow.com/a/51316888
has title: funcCalling arbitrary class functions for all members of a list of instances
has answer: http://stackoverflow.com/a/51316888
tagged with: python-3.x
has body: I am trying to create a wrap for a class _class1_ (probably, another class) that will have inside a list of several instances of _class1_, some additional variables, some functions that will operate with this list and also wraps for (nearly) all the functions of _class1_, that should actually just call the corresponding functions for all the _class1_ objects stored in the list with the same set of parameters. Could anyone suggest a better way to do that then just to implement all this functions (that will iterate through a list and call the corresponding functions from List_class1) by hand? Example class class2: def __init__(self, N): self._N = N self.List_class1 = [] for i in range(0, self._N): self.List_class1.append(class1()) def function1(self, params) for i in range(0, self._N): List_class1[i].function1(params) def function2(self, params) ret = [] for i in range(0, self._N): ret.append(List_class1[i].function2(params)) return ret So if a have a number of functions in class1 that I wand to adapt like that, maybe someone can suggest a way to do that wo just rewriting?
linked to: http://stackoverflow.com/q/1810526
tagged with: python
tagged with: design-patterns
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51316959
type: Question
answer count: 2
tagged with: function
has comment: http://stackoverflow.com/comment/89642567
tagged with: class
has comment: http://stackoverflow.com/comment/89609443
score: 0

http://stackoverflow.com/q/51282353
tagged with: python
has comment: http://stackoverflow.com/comment/89542628
has title: Python Class handling txtfiles
tagged with: text
has body: I need to write a class, named "data" which handles the processing of a (txt)file into an object. It needs to take in the classvariable "filename" which will be manipulated with the following 3 functions: function "init": takes in a string and allocates it to the class variable "filename". function "reset": produces a new empty file with the name of the class variable. Existing files will be overwritten. function "save": takes in a string and puts it in the end of the file This is what I have so far: class File: filename = [] def __init__(self, filename): self.filename = filename def Reset (self, filename): self.filename = open('test.txt').close() def Save (self, input): self.input = raw_input() text_file = open("test.txt", "w") text_file.write(self.input) text_file.close() I am very new to programming and already tried it to word by myself and hours of googling, but I just can´t get it to work. I would be very thankfull for any help!
downvote count: 3
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/89542110
score: -2
has comment: http://stackoverflow.com/comment/89542164
has answer: http://stackoverflow.com/a/51360103
has comment: http://stackoverflow.com/comment/89542807
has comment: http://stackoverflow.com/comment/89542107
tagged with: class
answer count: 1
has comment: http://stackoverflow.com/comment/89542245
favorite count: 0
has comment: http://stackoverflow.com/comment/89552235
type: UnansweredQuestion

http://stackoverflow.com/comment/89474224
has text: @ubuntu_noob, You can also try jezrael's solution. But this is just a warning (not an error), it's not a problem *per se*. You should test both methods to see which is actually faster.
comment on: http://stackoverflow.com/a/51246426
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/51220859
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: reshape
tagged with: python
tagged with: choropleth
has title: How to reshape data in pandas to plot with Choropleth
score: 1
has body: I'm trying to plot with Choropleth some data (particularly this dataset from GitHub (terrorism in EU countries). I have something like this: year country1 countr2 country3 1970 10 20 30 1971 40 50 60 1972 70 80 90 And as far as I know, should have something like this: year country value 1970 country1 10 1970 country2 20 1970 country3 30 1971 country1 40 1971 country2 50 1971 country3 60 1972 country1 70 1972 country2 80 1972 country3 90 How can I achieve this with Pandas? Is this a good approach to solve the problem? Thank you very much.
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/51221027
tagged with: dataframe
tagged with: pandas
answer count: 1

http://stackoverflow.com/comment/130744008
type: Comment
comment on: http://stackoverflow.com/a/51194149
has text: Also raises `TypeError: sequence item 0: expected str instance, int found` on numbered columns.
score: 0
type: AnswerComment

http://stackoverflow.com/q/51224752
type: Question
has title: "Failed to connect to the SC2 websocket. Is it up?"
score: 0
has body: I am trying to run the Deepmind Environment for Starcraft II, following this tutorial After running: $ python -m pysc2.bin.play --map Simple64 I get this error: raise ConnectError("Failed to connect to the SC2 websocket. Is it up?") within the pysc2.lib.remote_controller Any idea how to fix this?
accepted answer: http://stackoverflow.com/a/51225121
answer count: 1
favorite count: 0
tagged with: starcraftgym
tagged with: python
tagged with: connection
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51225121
upvote count: 1
downvote count: 1

http://stackoverflow.com/comment/89560030
has text: Thank you for the advice, you are right I should just get it working first and then profile. I do this so many times I am very confident the speedup will be huge, but that doesn't change that you are correct. anyways thank you for the concise answer!
comment on: http://stackoverflow.com/a/51291106
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/89436507
has text: The actual code for Box-Mueller is in the C file - https://github.com/numpy/numpy/blob/2afa142ae6ee121f6c75f28403526e35473ee6d5/numpy/random/mtrand/randomkit.c#L619 I want to know how this links to the method in the pyx file. Is this easy to trace?
comment on: http://stackoverflow.com/a/51228197
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/89326442
comment on: http://stackoverflow.com/a/51171773
type: AnswerComment
type: Comment
has text: @Amadan Modified to work with iterators of unequal length
score: 0

http://stackoverflow.com/comment/89510395
type: QuestionComment
comment on: http://stackoverflow.com/q/51266055
has text: I agree with @Marcus.Aurelianus, but we do not know your exact scenario. How many times do you read an element? If you add element rarely and read many times then 1st might be better. I would also consider using Binary Search Tree.
score: 0
type: Comment

http://stackoverflow.com/a/51278330
upvote count: 0
has body: try to assign separate indices by using Dataframe.set_index(keys,inplace=True) please refer to this documentation https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.set_index.html
type: Answer
answers question: http://stackoverflow.com/q/51278212
downvote count: 1
score: -1

http://stackoverflow.com/comment/89358736
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51188368
has text: Thank for your rely , but it doesn't work . it throw error : Message: no such element: Unable to locate element: {"method":"css selector","selector":".side-button-test middle>div"}
score: 0

timer
tag name: timer
tags question: http://stackoverflow.com/q/51315488
type: Tag

http://stackoverflow.com/comment/89476288
score: 0
type: AnswerComment
has text: @Datanovice, Once you map the values from `d` with `, ` separated strings, the solution splits the strings with `, ` and fetches the last value from the list. Consider the edit and that would solve the extra space problem.
comment on: http://stackoverflow.com/a/51248433
type: Comment

http://stackoverflow.com/q/51319769
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/89615662
has comment: http://stackoverflow.com/comment/89620117
has comment: http://stackoverflow.com/comment/89615379
tagged with: arrays
has comment: http://stackoverflow.com/comment/89620671
has comment: http://stackoverflow.com/comment/89615499
score: 0
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/51320011
type: UnansweredQuestion
has body: I have a nested array of complex numbers, xi: [[[ 2.51325641-2.34963293j 2.17949212-1.57079633j 2.51325641-0.79195972j] [ 2.15322703+3.14159265j 0.00000000+1.57079633j 2.15322703+0.j ] [ 2.51325641+2.34963293j 2.17949212+1.57079633j 2.51325641+0.79195972j]] [[ 2.44651048-2.3486959j 2.11452586-1.57079633j 2.44651048-0.79289676j] [ 2.08450333+3.14159265j 0.00000000+1.57079633j 2.08450333+0.j ] [ 2.44651048+2.3486959j 2.11452586+1.57079633j 2.44651048+0.79289676j]]] and taking numpy.exp gives me the following: np.exp(xi): [[[ -8.67181418e+00 -8.78636871e+00j 5.41404995e-16 -8.84181457e+00j 8.67181418e+00 -8.78636871e+00j] [ -8.61260674e+00 +1.05474013e-15j 6.12323400e-17 +1.00000000e+00j 8.61260674e+00 +0.00000000e+00j] [ -8.67181418e+00 +8.78636871e+00j 5.41404995e-16 +8.84181457e+00j 8.67181418e+00 +8.78636871e+00j]] [[ -8.10419460e+00 -8.22665532e+00j 5.07350124e-16 -8.28565631e+00j 8.10419460e+00 -8.22665532e+00j] [ -8.04059693e+00 +9.84689130e-16j 6.12323400e-17 +1.00000000e+00j 8.04059693e+00 +0.00000000e+00j] [ -8.10419460e+00 +8.22665532e+00j 5.07350124e-16 +8.28565631e+00j 8.10419460e+00 +8.22665532e+00j]]] However the real parts of some of the elements are incorrect when I check them individually, e.g. the 2nd column of the first row of the first nested array: In [1]: np.exp(2.17949212-1.57079633j) Out[1]: (-2.833893031963725e-08-8.8418145374224597j) but others are fine (e.g. array 1 row 1 column 1). In [2]: np.exp(2.51325641-2.34963293j) Out[2]: (-8.671814171261488-8.7863687332566318j) This makes no sense to me, because the numpy.exp documentation seems to imply that e^(a+ib) is calculated as e^a*(cos(b) + i sin(b)), so I don't see how the imaginary part can be correct while the real part is not. Is it possible to make numpy.exp work consistently for my array? EDIT: It's been pointed out that defining xi as above does give the correct result with np.exp; it also works in my python environment when I define it as a standalone array of the values above. Howeve…
has comment: http://stackoverflow.com/comment/89615465
upvote count: 1
tagged with: python
downvote count: 1
has title: Why is numpy.exp on a complex meshgrid array giving the wrong real part?
has comment: http://stackoverflow.com/comment/89620922
tagged with: complex-numbers
has comment: http://stackoverflow.com/comment/89622358
has comment: http://stackoverflow.com/comment/89615883

http://stackoverflow.com/comment/89405334
type: AnswerComment
score: 0
type: Comment
has text: This code does not produce the results needed. It will constantly print "I'm working 24/7 and doing some important stuff here!" and "Very important!" and ignores `sleep(5)`
comment on: http://stackoverflow.com/a/51211750

http://stackoverflow.com/q/51293632
answer count: 8
has comment: http://stackoverflow.com/comment/89565009
accepted answer: http://stackoverflow.com/a/51294302
has comment: http://stackoverflow.com/comment/89565035
has comment: http://stackoverflow.com/comment/89564828
has comment: http://stackoverflow.com/comment/89564938
linked to: http://stackoverflow.com/q/993358
tagged with: datetime
has comment: http://stackoverflow.com/comment/89564973
has comment: http://stackoverflow.com/comment/122790064
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51294957
has answer: http://stackoverflow.com/a/66374481
has title: How do I divide a date range into months in Python?
has answer: http://stackoverflow.com/a/51294307
tagged with: python
has answer: http://stackoverflow.com/a/60870172
has answer: http://stackoverflow.com/a/72957789
has answer: http://stackoverflow.com/a/51294302
type: AnsweredQuestion
has body: I have the following date range: begin: 2018-02-15 end: 2018-04-23 I want to achieve the following: ["2018-02-15 - 2018-02-28", "2018-03-01 - 2018-03-31", "2018-04-01 - 2018-04-23"] Essentially, I want to divide a given date range into months. I can't think of a way to accomplish this in Python. I have considered the solution here, however, this splits the date range based on a specified interval. I want to be able to split a date range dynamically. Hence, given a date range from 15 February 2018 to 23 April 2018, I want to be able to get the individual months in the range, like so: 15 February 2018 to 28 February 2018 01 March 2018 to 31 March 2018 01 April 2018 to 23 April 2018
linked to: http://stackoverflow.com/q/42950
has answer: http://stackoverflow.com/a/64228528
possible better answer: http://stackoverflow.com/a/51294307
linked to: http://stackoverflow.com/q/29721228
has comment: http://stackoverflow.com/comment/107505181
upvote count: 10
downvote count: 1
has comment: http://stackoverflow.com/comment/89564892
has comment: http://stackoverflow.com/comment/89564794
has comment: http://stackoverflow.com/comment/89564839
has answer: http://stackoverflow.com/a/66269717
has comment: http://stackoverflow.com/comment/89564821
type: Question
score: 9

http://stackoverflow.com/comment/89341581
type: AnswerComment
has text: No there is not a downside using a pkl file. I guess if you only want to save the data and not the objects then a csv is more appropriate though. If your question is answered please remember to mark it as accepted.
comment on: http://stackoverflow.com/a/51177054
score: 0
type: Comment

http://stackoverflow.com/comment/89480436
comment on: http://stackoverflow.com/a/51250645
has text: @thestateofmay That's because Python evaluates the codes at run time and when you execute a block of code they evaluates all at the same time from your perspective but from interpreter's perspective it's how it's showed in disassembled bytecodes.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/51311602
score: 2
accepted answer of: http://stackoverflow.com/q/51310464
has body: I am using python 3.6 and pandas 0.23.0 and got it to work by using flavor='bs4' for pd.read_html. This results in it using html5lib instead of the default which is lxml, so you would have to install hmtl5lib (I have version 1.0.1). Python 3.6.6 |Anaconda, Inc.| (default, Jun 28 2018, 17:14:51) Type 'copyright', 'credits' or 'license' for more information IPython 6.4.0 -- An enhanced Interactive Python. Type '?' for help. In [1]: import pandas as pd In [2]: df = pd.read_html('http://en.wikipedia.org/wiki/List_of_countries_by_GDP_(nominal)', flavor='bs4') In [3]: df[2] Out[3]: 0 1 2 0 Rank Country GDP(US$MM) 1 NaN World[19] 79865481 2 1 United States 19390600 3 — European Union[n 1][19] 17308862 4 2 China[n 2] 12014610 5 3 Japan 4872135 6 4 Germany 3684816 7 5 United Kingdom 2624529 8 6 India 2611012 9 7 France 2583560 10 8 Brazil 2054969 11 9 Italy 1937894 12 10 Canada 1652412 13 11 South Korea 1538030 14 12 Russia[n 3] 1527469 15 13 Australia 1379548 16 14 Spain 1313951 17 15 Mexico 1149236 18 16 Indonesia 1015411 19 17 Turkey 849480 20 18 Netherlands 825745 21 19 Saudi Arabia 683827 22 20 Switzerland 678575 23 21 Argentina 637717 24 22 Taiwan 579302 25 23 Sweden 538575 26 24 Poland 524886 27 25 Belgium 494733 28 26 Thailand 455378 29 27 Iran 431920 .. ... ... ... 165 162 Lesotho 2721 166 163 Timor-Leste 2716 167 164 Bhutan 2321 168 165 Liberia 2140 169 166 Djibouti 2082 170 167 Central African Republic 1992 171 168 Belize 1819 172 169 Cape Verde 1728 173 170 St. Lucia 1717 174 171 San Marino 1592 175 172 Antigua and Barbuda 1535 176 173 Seychelles 1479 177 174 Guinea-Bissau 1295 178 175 Solomon Islands 1273 179 176 Grenada 1111 180 177 The Gambia 1038 181 178 St. Kitts and Nevis 939 182 179 Samoa 844 183 180 Vanuatu 837 184 181 St. Vincent and the Grenadines 815 185 182 Comoros 659 186 183 Dominica 608 187 184 Tonga 437 188 185 São Tomé and Príncipe 372 189 186 Federated States of Micronesia 329 190 187 Palau 321 191 188 Marshall Islands 199 192 189 Kiribati 186 1…
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 2
answers question: http://stackoverflow.com/q/51310464

http://stackoverflow.com/a/51300128
has body: We had a similar task once and ended up implementing the rather simple Möller-Trumbore-Algorithm. The code can be stolen from printrun: def ray_triangle_intersection(ray_near, ray_dir, v123): """ Möller–Trumbore intersection algorithm in pure python Based on http://en.wikipedia.org/wiki/M%C3%B6ller%E2%80%93Trumbore_intersection_algorithm """ v1, v2, v3 = v123 eps = 0.000001 edge1 = v2 - v1 edge2 = v3 - v1 pvec = numpy.cross(ray_dir, edge2) det = edge1.dot(pvec) if abs(det) &lt; eps: return False, None inv_det = 1. / det tvec = ray_near - v1 u = tvec.dot(pvec) * inv_det if u &lt; 0. or u &gt; 1.: return False, None qvec = numpy.cross(tvec, edge1) v = ray_dir.dot(qvec) * inv_det if v &lt; 0. or u + v &gt; 1.: return False, None t = edge2.dot(qvec) * inv_det if t &lt; eps: return False, None return True, t For the angle calculation you can use e.g. angle_between_vectors() from transformations.py
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/89593993
answers question: http://stackoverflow.com/q/51285624
has comment: http://stackoverflow.com/comment/89598198
has comment: http://stackoverflow.com/comment/89592299
type: Answer
has comment: http://stackoverflow.com/comment/89598267
has comment: http://stackoverflow.com/comment/89586644
has comment: http://stackoverflow.com/comment/89616183
has comment: http://stackoverflow.com/comment/89586439
upvote count: 3
has comment: http://stackoverflow.com/comment/89595360
has comment: http://stackoverflow.com/comment/89592669
accepted answer of: http://stackoverflow.com/q/51285624
has comment: http://stackoverflow.com/comment/89598157
score: 3

http://stackoverflow.com/q/51295724
tagged with: label
has comment: http://stackoverflow.com/comment/89586530
has comment: http://stackoverflow.com/comment/89591503
score: 0
has comment: http://stackoverflow.com/comment/89596918
has body: As the title says, I am trying to run the svc algorithm on a dataset but I keep getting the error : Unknown Label Type : unknown error The code is as below : import numpy as np import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn import svm path1 = r'C:\Users\Ahmed Ismail Khalid\Desktop\Training.csv' path2 = r'C:\Users\Ahmed Ismail Khalid\Desktop\Testing.csv' training = pd.read_csv(path1) testing = pd.read_csv(path1) training = training.drop('created_at',axis=1) training = training.fillna(0) testing = testing.drop('created_at',axis=1) testing = testing.fillna(0) labels = (training['Count of aantonop_tweets.csv'],['Count of adam3us_tweets.csv'],['Count of alansilbert_tweets.csv'],['Count of alexsunnarborg_tweets.csv'],['Count of alextapscott_tweets.csv'],['Count of anondran_tweets.csv'],['Count of AnselLindner_tweets.csv'],['Count of AriannaSimpson_tweets.csv'],['Count of AriDavidPaul_tweets.csv'],['Count of arrington_tweets.csv'],['Count of barrysilbert_tweets.csv'],['Count of bendavenport_tweets.csv'],['Count of bgarlinghouse_tweets.csv'],['Count of bitcoinbyte_tweets.csv'],['Count of bobbyclee_tweets.csv'],['Count of brian_armstrong_tweets.csv'],['Count of brockpierce_tweets.csv'],['Count of CarpeNoctom_tweets.csv'],['Count of cburniske_tweets.csv'],['Count of certainassets_tweets.csv'],['Count of CharlieShrem_tweets.csv'],['Count of chrislarsensf_tweets.csv'],['Count of CremeDeLaCrypto_tweets.csv'],['Count of cryptomanran_tweets.csv'],['Count of dahongfei_tweets.csv'],['Count of dan_pantera_tweets.csv'],['Count of DerinCag_tweets.csv'],['Count of derose_tweets.csv'],['Count of desantis_tweets.csv'],['Count of dieguito_tweets.csv'],['Count of dinisguarda_tweets.csv'],['Count of dtapscott_tweets.csv'],['Count of eiaine_tweets.csv'],['Count of eric_lombrozo_tweets.csv'],['Count of ErikVoorhees_tweets.csv'],['Count of ethereumjoseph_tweets.csv'],['Count of FEhrsam_tweets.csv'],['Count of francispouliot__tweets.csv'],['Count of fredwilso…
answer count: 1
tagged with: scikit-learn
has title: Unkown Label Type : unknown error while running svc algorithm in sklearn python
has comment: http://stackoverflow.com/comment/89593712
has answer: http://stackoverflow.com/a/51310142
has comment: http://stackoverflow.com/comment/89601942
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89587234
tagged with: svc
has comment: http://stackoverflow.com/comment/89586457
has comment: http://stackoverflow.com/comment/89579995
type: Question
accepted answer: http://stackoverflow.com/a/51310142

http://stackoverflow.com/comment/89433600
comment on: http://stackoverflow.com/q/51215051
type: Comment
type: QuestionComment
has text: If you can possibly upgrade to 3.6 or 3.7, do so. The 'connection error' message has been updated. The current IDLE doc gives more reasons and fixes in https://docs.python.org/3/library/idle.html#startup-failure. In a terminal/console or Command Prompt, `python -m idlelib` starts IDLE. If on Windows, you should have a clickable icon in start menu, which you can copy to desktop or pin to taskbar. You can also use 'py' or 'py -x.y' instead of 'python'.
score: 0

http://stackoverflow.com/comment/89546344
type: QuestionComment
has text: That name *isn't* defined; it can't be, function annotations are evaluated in the scope in which the function is defined, not the scope of the function itself. This may be possible with [postponed evaluation](https://www.python.org/dev/peps/pep-0563/), but in general these things are better solved with [*generic types*](https://docs.python.org/3/library/typing.html#generics) - `f` takes a parameter of type `T` and returns type `T`.
score: 2
comment on: http://stackoverflow.com/q/51284524
type: Comment

http://stackoverflow.com/comment/89526346
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51273113
has text: A dozen things could be going wrong. I recommend trying out [`pyinstaller`](https://www.pyinstaller.org/) if you can't get `cx_Freeze` to work.

http://stackoverflow.com/q/51184276
answer count: 2
accepted answer: http://stackoverflow.com/a/51184386
downvote count: 0
favorite count: 0
has title: Generate a view to identify first entry and last entry of a particular value in a column in python
has comment: http://stackoverflow.com/comment/89350474
has body: The sheet is 150 000 entries long and there are five columns. In a particular column, there are many repeated entries. The column name is "CNumber'. And the entries are like: 123 334 233 123 224 .. so on. I want to generate a view so that for a particular CNumber say 123, I want to identify the first entry and its last entry. Meaning: There is a column which says "Time". So in a particular day, say CNumber "123" was used for 12 times and hence it is input 12 times in the sheet. But I just want to identify the first and the last time it was used so that I can calculate the time it was there in the company premises on a particular day.
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/51184790
upvote count: 2
has answer: http://stackoverflow.com/a/51184790
has answer: http://stackoverflow.com/a/51184386
tagged with: python
score: 2
type: AnsweredQuestion
type: Question

http://stackoverflow.com/a/51266680
has comment: http://stackoverflow.com/comment/89548193
accepted answer of: http://stackoverflow.com/q/51265578
answers question: http://stackoverflow.com/q/51265578
has comment: http://stackoverflow.com/comment/89511966
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89586139
downvote count: 0
has comment: http://stackoverflow.com/comment/89551239
type: Answer
has comment: http://stackoverflow.com/comment/89538601
has comment: http://stackoverflow.com/comment/89551020
score: 6
has body: Warning about your shapes: If your kernel size is (11,11), and assuming you have 64 input channels and 1 output channel, your final kernel shape must be (11,11,64,1). You should probably be going for a[None,None] and b[:,:,:,None,None]. class CustomConv2D(Conv2D): def __init__(self, filters, kernel_size, kernelB = None, **kwargs): super(CustomConv2D, self).__init__(filters, kernel_size,**kwargs) self.kernelB = kernelB def build(self, input_shape): #use the input_shape to calculate the shapes of A and B #if needed, pay attention to the "data_format" used. #this is an actual weight, because it uses `self.add_weight` self.kernelA = self.add_weight( shape=shape_of_kernel_A + (1,1), #or (1,1) + shape_of_A initializer='glorot_uniform', #or select another name='kernelA', regularizer=self.kernel_regularizer, constraint=self.kernel_constraint) #this is an ordinary var that will participate in the calculation #not a weight, not updated if self.kernelB is None: self.kernelB = K.constant(....) #use the shape already containing the new axes #in the original conv layer, this property would be the actual kernel, #now it's just a var that will be used in the original's "call" method self.kernel = K.sum(self.kernelA * self.kernelB, axis=2) #important: the resulting shape should be: #(kernelSizeX, kernelSizeY, input_channels, output_channels) #the following are remains of the original code for "build" in Conv2D #use_bias is True by default if self.use_bias: self.bias = self.add_weight(shape=(self.filters,), initializer=self.bias_initializer, name='bias', regularizer=self.bias_regularizer, constraint=self.bias_constraint) else: self.bias = None # Set input spec. self.input_spec = InputSpec(ndim=self.rank + 2, axes={channel_axis: input_dim}) self.built = True Hints for custom layers When you create a custom layer from zero (derived from Layer), you should have these methods: __init__(self, ... parameters ...) - this is the creator, it's called when you create a new instance of your lay…
upvote count: 6

db2
tags question: http://stackoverflow.com/q/51169926
tag name: db2
tags question: http://stackoverflow.com/q/51273579
type: Tag

http://stackoverflow.com/q/51190656
tagged with: boto3
has comment: http://stackoverflow.com/comment/89388710
tagged with: aws-security-group
tagged with: python
has comment: http://stackoverflow.com/comment/89373365
favorite count: 0
has answer: http://stackoverflow.com/a/51254837
type: UnansweredQuestion
downvote count: 2
has comment: http://stackoverflow.com/comment/89488628
has title: How to fetch instance security group name dynamically via Boto3
type: Question
upvote count: 0
score: -2
answer count: 1
tagged with: amazon-ec2
has body: I made image of source instance and now i had to clone new instance, Thus i hardcoded the security group name of source instance in target instance creation. now I want it to be dynamically. Below is my code: ec2 = boto3.resource('ec2',region_name='region') instance = ec2.create_instances( ImageId=image, InstanceType='t2.micro', KeyName='keyName', SecurityGroups=['sgr-ssh-http-public'], MaxCount=1, MinCount=1 )

aws-security-group
type: Tag
tags question: http://stackoverflow.com/q/51190656
tag name: aws-security-group

http://stackoverflow.com/comment/89522959
type: Comment
type: QuestionComment
has text: What does `pip --version` say? Try use search: https://stackoverflow.com/questions/46967488/getting-error-403-while-installing-package-with-pip/46979531#46979531
comment on: http://stackoverflow.com/q/51272437
score: 0

http://stackoverflow.com/q/51278519
has comment: http://stackoverflow.com/comment/89554726
score: 1
tagged with: multiprocessing
type: Question
answer count: 2
upvote count: 1
has comment: http://stackoverflow.com/comment/89554182
has comment: http://stackoverflow.com/comment/89540745
favorite count: 0
has title: Python how to read from and write to different files using multiprocessing
tagged with: python
has comment: http://stackoverflow.com/comment/89575357
has answer: http://stackoverflow.com/a/51279112
downvote count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51279859
has body: I have several files and I would like to read those files, filter some keywords and write them into different files. I use Process() and it turns out that it takes more time to process the readwrite function. Do I need to separate the read and write to two functions? How I can read multiple files at one time and write key words in different files to different csv? Thank you very much. def readwritevalue(): for file in gettxtpath(): ##gettxtpath will return a list of files file1=file+".csv" ##Identify some variable ##Read the file with open(file) as fp: for line in fp: #Process the data data1=xxx data2=xxx .... ##Write it to different files with open(file1,"w") as fp1 print(data1,file=fp1 ) w = csv.writer(fp1) writer.writerow(data2) ... if __name__ == '__main__': p = Process(target=readwritevalue) t1 = time.time() p.start() p.join() Want to edit my questions. I have more functions to modify the csv generated by the readwritevalue() functions. So, if Pool.map() is fine. Will it be ok to change all the remaining functions like this? However, it seems that it did not save much time for that. def getFormated(file): ##Merge each csv with a well-defined formatted csv and generate a final report with writing all the csv to one output csv csvMerge('Format.csv',file,file1) getResult() if __name__=="__main__": pool=Pool(2) pool.map(readwritevalue,[file for file in gettxtpath()]) pool.map(GetFormated,[file for file in getcsvName()]) pool.map(Otherfunction,file_list) t1=time.time() pool.close() pool.join()

http://stackoverflow.com/a/51176080
has body: The easiest and cleanest way is to just create 2 outputs layers: sigmoid_out = layers.dense(inputs=inp, units=2, activation=tf.nn.sigmoid) relu_out = layers.dense(inputs=inp, units=1, activation=tf.nn.relu) You can then concat both layers if you want : out = tf.concat([sigmoid_out, relu_out], axis=1)
downvote count: 0
answers question: http://stackoverflow.com/q/51175117
type: Answer
score: 1
upvote count: 1

http://stackoverflow.com/comment/89609006
type: Comment
type: QuestionComment
score: 0
has text: As I said, I don't think there's a way to do this. The reason is probably because conda environments are so much more than virtualenv environments... they can have their own compiliers, run scripts to set environment variables on execution, etc. Why not recreate the virtualenv as a conda env and add uwsgi to it?
comment on: http://stackoverflow.com/q/51310767

http://stackoverflow.com/comment/89592699
comment on: http://stackoverflow.com/q/51307587
type: Comment
type: QuestionComment
has text: I'm trying to see the most efficient way to approach this problem
score: 0

http://stackoverflow.com/comment/89438563
comment on: http://stackoverflow.com/q/51229274
has text: @Michael Doubez, ssh tunnel is to connect remote server, that is possible using stardard paramiko module, again from from remote server I have to establish another remote connection ..
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89496268
has text: Awesome. Thanks Rakesh. That's great.
comment on: http://stackoverflow.com/a/51258195
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/89354623
comment on: http://stackoverflow.com/q/51186167
type: QuestionComment
has text: Can you try with context manager. ie, `with Pool(12) as p :` then `p.starmap( _get_price_df, [(ticker, start_date, end_date) for ticker in tickers]`
score: 0
type: Comment

http://stackoverflow.com/comment/89360813
score: 1
has text: @JoeannYen how is `'AAA':[[UK, ADJ, N], [ES,N]]` computed? If there's 3 AAA's, why are both lists not 3 elements?
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51189483

http://stackoverflow.com/comment/89580045
score: 0
comment on: http://stackoverflow.com/q/51301395
type: Comment
type: QuestionComment
has text: Personally, if JPG is small I would convert the binary data with `Base64` and store it as a text. https://docs.python.org/3/library/base64.html

http://stackoverflow.com/q/51248322
duplicate of: http://stackoverflow.com/q/47152691
has comment: http://stackoverflow.com/comment/89475661
favorite count: 0
type: UnansweredQuestion
tagged with: python
score: 3
upvote count: 3
linked to: http://stackoverflow.com/q/47152691
type: Question
downvote count: 0
has answer: http://stackoverflow.com/a/51248415
has body: Is there a built-in way to convert a list of objects in Python to a Pandas DataFrame. myList = [ { name:'ABC', value:35, date:2018-01-01 }, { name:'ABC', value:30, date:2018-01-02 }, { name:'DEF', value:70, date:2018-01-01 }, { name:'DEF', value:22, date:2018-01-02 } ] Convert to
tagged with: pandas
has title: Python pandas list of objects to DataFrame
answer count: 1

http://stackoverflow.com/comment/89546529
type: AnswerComment
type: Comment
has text: Why do you think it should do?
comment on: http://stackoverflow.com/a/51284666
score: 0

http://stackoverflow.com/a/51246383
type: Answer
answers question: http://stackoverflow.com/q/51245098
score: 0
has body: It can be done by using Step Slicing in Python. Here, have a look. myList = ["Sprite", "Fanta", "Coke", "7up"] print(myList[::3]) Output: ['Sprite', '7up']

http://stackoverflow.com/a/51203654
type: Answer
answers question: http://stackoverflow.com/q/51200900
upvote count: 1
score: 1
has body: Consider using eager execution. It is perfectly tailored for this kind of dynamic tempering with your network. import random import tensorflow as tf tf.enable_eager_execution() x = tf.constant(1) for _ in range(10): dev = random.choice(['/cpu:0', '/gpu:0']) with tf.device(dev): x = x + 1 print('res {} computed on {}'.format(x.numpy(), x.device))
downvote count: 0

http://stackoverflow.com/comment/89509984
score: 0
has text: I can't connect to it directly. I need to take a remote login to a machine and then open the SQL Assistant client there to access it manually.
comment on: http://stackoverflow.com/q/51265668
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89455346
type: QuestionComment
comment on: http://stackoverflow.com/q/51237591
score: 0
has text: @Woody Johnson I think I have the path right. It worked before now.
type: Comment

http://stackoverflow.com/q/51207906
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/70118468
tagged with: python
has body: I have my x-axis values in this format : ['May 23 2018 06:31:52 GMT', 'May 23 2018 06:32:02 GMT', 'May 23 2018 06:32:12 GMT', 'May 23 2018 06:32:22 GMT', 'May 23 2018 06:32:32 GMT'] and corresponding values for the y-axis which are some numbers. But when I am plotting these using plotly , x-axis show only part of the date (May 23 2018) for each point. Time for each point is not shown. I tried setting up tickformat also in layout, but it does not seems to work. layout = go.Layout( title=field+ "_its diff_value chart", xaxis = dict( tickformat = '%b %d %Y %H:%M:%S' ) ) any help is appreciated. This is the screenshot of the graph made.
score: 2
upvote count: 2
tagged with: plotly
type: Question
has title: time on xaxis in plotly
has comment: http://stackoverflow.com/comment/89635003
answer count: 2
has answer: http://stackoverflow.com/a/51231209
downvote count: 0
favorite count: 0

http://stackoverflow.com/comment/100437964
type: AnswerComment
type: Comment
score: 2
has text: @A.J. Example in [docs](https://www.django-rest-framework.org/api-guide/viewsets/#reversing-action-urls): `view.reverse_action('set-password', args=['1'])`
comment on: http://stackoverflow.com/a/51317608

http://stackoverflow.com/comment/89341488
type: AnswerComment
comment on: http://stackoverflow.com/a/51179433
type: Comment
has text: @AliHalawa please edit the question and add your updated code to the end. If you get empty list maybe the status_code is not 200, that would cause the `append()` part to never execute because of the `if`
score: 0

http://stackoverflow.com/q/51204573
score: 0
answer count: 2
has title: composite two foreign key in sqlalchemy?
tagged with: flask-sqlalchemy
has body: I am using SQLALchemy in flask. And I am confused how to define composite key with two foreign keys. One foreign key from one table and second from another table. class Store_category_mapping(db.Model): __tablename__ = 'store_category_mapping' category_id = db.Column(db.Integer, nullable=False) store_id = db.Column(db.Integer, nullable=False) store_name = db.Column(db.String(50), nullable=False) __table_args__ = ( db.ForeignKeyConstraint( [category_id, store_id], [Category_master.category_id, Store_master.store_id] ), ) It gives this error: sqlalchemy.exc.ArgumentError: ForeignKeyConstraint on store_category_mapping(category_id, store_id) refers to multiple remote tables: category_master and store_master
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/77438477
has answer: http://stackoverflow.com/a/51206768
type: Question
tagged with: sqlalchemy

http://stackoverflow.com/q/51217524
has body: I need to do repetitive coding for many years, for instance, G1990 = pd.read_csv("map_1990.csv") G1991 = pd.read_csv("map_1991.csv") ". . ." G2015 = pd.read_csv("map_2015.csv") Other examples are, path2001=dict(nx.all_pairs_shortest_path_length(G2001)) path2002=dict(nx.all_pairs_shortest_path_length(G2002)) path2003=dict(nx.all_pairs_shortest_path_length(G2003)) ". . . " path2015=dict(nx.all_pairs_shortest_path_length(G2015)) and df2001.to_csv("path2001.csv") df2002.to_csv("path2002.csv") df2003.to_csv("path2003.csv") ". . . " df2015.to_csv("path2015.csv") it would be nice if I can use a loop to simplify my code, such that for i in range(1990:2015), G[i] = pd.read_csv("map_[i].csv") or for i in range(2001:2015), path[i]=dict(nx.all_pairs_shortest_path_length(G[i])) and for i in range(1990:2015), df[i].to_csv("path[i].csv") Help me please :)
has answer: http://stackoverflow.com/a/51217559
tagged with: loops
has comment: http://stackoverflow.com/comment/89416541
type: Question
has answer: http://stackoverflow.com/a/51217547
score: 0
answer count: 3
has answer: http://stackoverflow.com/a/51217636
tagged with: python-3.x
has title: iterating through names by loop in python
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/89362247
comment on: http://stackoverflow.com/a/51189214
has text: If you using `sklearn` then it will not be a problem to instantiate any of the classifiers. But, you need to make sure the parameters match in your call. So, the above approach will work. Just you need to send right parameters to your `function`. Like I did above using `dict`.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/51557142
upvote count: 4
has comment: http://stackoverflow.com/comment/90081706
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/90081501
has body: You need to specify path mappings for particular run configuration or interpreter. After that your local files will point to the remote ones. E.g. /User/local/project= /User/remote/project Path mappings for the interpreter: Pycharm > Preferences > Project > Project Interpreter > Click on Project Path mappings for run configurations: Run > Edit configuration > Choose run cofig > Choose remote interperter > Fill in mappings Just to be clear it will still cache some files: https://intellij-support.jetbrains.com/hc/en-us/community/posts/206593675-Path-Mappings-does-not-work-for-me
answers question: http://stackoverflow.com/q/51284700
score: 4

http://stackoverflow.com/a/74470318
score: -1
answers question: http://stackoverflow.com/q/51279570
upvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/131534272
has body: Create a tuple and use it as a normal variable so you can add two or more variable in one tuple and transfer them with button:
downvote count: 1

http://stackoverflow.com/q/51197760
accepted answer: http://stackoverflow.com/a/52282083
has comment: http://stackoverflow.com/comment/89377381
has comment: http://stackoverflow.com/comment/89379267
type: AnsweredQuestion
upvote count: 5
has comment: http://stackoverflow.com/comment/89379096
has comment: http://stackoverflow.com/comment/89382202
type: Question
score: 5
answer count: 3
possible better answer: http://stackoverflow.com/a/54715057
has comment: http://stackoverflow.com/comment/89379142
downvote count: 0
has answer: http://stackoverflow.com/a/54715057
has body: import csv import os import pandas as pd os.chdir(r'C:\Users\khalha\Desktop\AllSalesForecasting') dataframe12 = pd.read_csv('54.csv') june18 = pd.read_csv('54.csv', index_col="Customer") print(june18) Even if I dont have the last 2 lines, I am recieveing an error: FileNotFoundError: File b'54.csv' does not exist I have no idea why this is happening for I have done many problems using this format, but now it does not seem to work.
favorite count: 0
has comment: http://stackoverflow.com/comment/89377712
has answer: http://stackoverflow.com/a/52151400
has comment: http://stackoverflow.com/comment/89377881
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has answer: http://stackoverflow.com/a/52282083
has title: Filenotfounderror File b'.csv' does not exist

http://stackoverflow.com/q/51271709
tagged with: python
type: AnsweredQuestion
score: 3
has title: Interpolate PANDAS df
upvote count: 3
has answer: http://stackoverflow.com/a/51271791
accepted answer: http://stackoverflow.com/a/51271791
has body: I know this subject was brought up a few times on stack overflow, however I'm still stumbling upon an interpolation problem. I have a complex dataframe of a set of columns, which could look something like this if simplified: df_new = pd.DataFrame(np.random.randn(5,7), columns=[402.3, 407.2, 412.3, 415.8, 419.9, 423.5, 428.3]) wl = np.array([400.0, 408.2, 412.5, 417.2, 420.5, 423.3, 425.0]) So what I need to do is to interpolate column-wise, to the new assigned values of cols (wl), for each row. And how to get the new dataframe with columns ONLY containing values presented in the wl array?
type: Question
linked to: http://stackoverflow.com/q/25918149
downvote count: 0
tagged with: pandas
answer count: 1
favorite count: 0
tagged with: interpolation

http://stackoverflow.com/q/51205949
has body: So I'm creating a sorting machine using a USB scanner and raspberry pi. The bar code value scanned must be checked in the database. If its marked as pass then machine continues to move, else if its marked as fail in database then the machine stops. Now I dont want the scanner input to be printed on the screen, how can I use the bar code value in the program without printing on screen. Im using python to program. from Tkinter import * import Tkinter as tk import MySQLdb #creating window and entry box root=Tk() root.title("PCBA Registration") entry=Entry(root,fg="black",bg="white",width=15) entry.grid(row=0,column=4,sticky=W) entry_value=entry.get() #label label1=Label(root,bg="black",fg="white",text="SCAN HERE").grid(row=0,column=2,stick=W) def check(): db=MySQLdb.connect (host='localhost', user = "root", passwd = "passwd", db = "server") #creation of cursor to access database cur=db.cursor() do1="SELECT Workorder_No FROM pcba_registration where PCB_Sno='%s'" %(entry.get()) cur.execute(do1) workorder=cur.fetchall() for row1 in workorder: print row1[0] workorder_value=row1[0] do2=("SELECT approval_Status FROM workorder_release where workOrder_No='%s'" %(workorder_value)) cur.execute(do2) status=cur.fetchall() print status for row2 in status: print row2[0] check=Button(root,text="CHECK",width=5,command=check).grid(row=2,column=4,stick=W) #to run main loop if __name__ == '__main__': root.mainloop() For now I have created an interface using Tkinter to to print out the scanned bar code. But I dont want that. Im an absolute beginner and new to stack overlflow too. Please help me! Thanks!
downvote count: 0
favorite count: 0
type: UnansweredQuestion
has title: how to obtain value from scanner without printing on screen
tagged with: python
has comment: http://stackoverflow.com/comment/89461959
tagged with: tkinter
answer count: 0
score: 1
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/89456114
has comment: http://stackoverflow.com/comment/89393440

http://stackoverflow.com/comment/94299955
type: Comment
has text: Did you change anything besides adding an `if` statement?`I figured out the issue on my end was related to the way linux handles multiple jobs.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51190906

http://stackoverflow.com/a/51315465
has body: Then you want something like this (and please change the name of the list variable, see comment) def check_endpoint(): endpoint = "" req = requests.get(endpoint) reqJson = json.loads(req.text) for id in reqJson['threads']: # For each id in threads list PID = id['product']['globalPid'] # Get current PID if PID in list: print('checking for new products') else: try: title = (id['product']['title']) Image = (id['product']['imageUrl']) ReleaseType = (id['product']['selectionEngine']) Time = (id['product']['effectiveInStockStartSellDate']) except KeyError as e: print("... ", e) else: # When all OK ... send(title, PID, Image, ReleaseType, Time) print ('added to database: {}'.format(PID)) list.append(PID) # Add PID to the list How you want it precise is up to you. You can handle things in different ways.
answers question: http://stackoverflow.com/q/51315264
accepted answer of: http://stackoverflow.com/q/51315264
score: 0
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/89607936

http://stackoverflow.com/a/51249120
has comment: http://stackoverflow.com/comment/89477238
has body: As roganjosh pointed out, you're doing your replacement in 3 steps - this is causing a problem because after step 1, you end up with a column of mixed dtypes, so subsequent equality checks start to fail. You can either assign to a new column, or use numpy.select. condlist = [ test['sentiment_score'] &gt; 0, test['sentiment_score'] &lt; 0 ] choicelist = ['pos', 'neg'] test['sentiment_score'] = np.select( condlist, choicelist, default='neutral')
type: AcceptedAnswer
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/51249024
upvote count: 6
score: 6
has comment: http://stackoverflow.com/comment/89478336
accepted answer of: http://stackoverflow.com/q/51249024

http://stackoverflow.com/q/51217358
tagged with: django-rest-framework
has comment: http://stackoverflow.com/comment/92646354
favorite count: 0
has body: I have a serializer class that raises a ValidationError in the validate() method. This ValidationError may have multiple error messages for multiple fields which seems to work alright. Some of my fields in the serializer have constraints which will also cause ValidationErrors to be raised, such as: start_date = DateField(input_formats=DATE_FORMATS_INPUT, error_messages=DATE_ERRORS) My problem is that when any of the errors caused by some sort of field argument (like having an invalid date format) is raised, the ValidationError from my validate() method is not raised. I was wondering if there is a way to get all of the ValidationErrors without creating custom validation methods for each field. The code is similar to this: field1 = serializers.IntegerField(min_value=1) field2 = serializers.IntegerField() field3 = serializers.IntegerField() def validate(self, data): err = {} if data['field2'] == None and data['field3'] != None: err['field2'] = ['Enter a value for this field'] if data['field3'] == None and data['field2'] != None: err['field3'] = ['Enter a value for this field'] if len(err) &gt; 0: raise serializers.ValidationError(err) else: return data In this code if field1 has a value that is less than 1, a field level error will be raised for it. This prevents a Validation error from being raised for field2 or field3 in validate(). I would like to be able to get errors for field1 and field2/3 at the same time.
tagged with: python
score: 4
linked to: http://stackoverflow.com/q/49226763
answer count: 0
has comment: http://stackoverflow.com/comment/89416010
type: UnansweredQuestion
has title: How to Raise Multiple ValidationErrors (including custom ones) in Django Serializer Validation
tagged with: django
tagged with: django-serializer
type: Question
upvote count: 4
has comment: http://stackoverflow.com/comment/89416248
downvote count: 0

http://stackoverflow.com/comment/89479400
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51219139
has text: Okay, your explanation at the end makes sense; I had meant to write `image_name` instead of `fname` in that last line.
score: 0

http://stackoverflow.com/q/51299228
answer count: 3
tagged with: python
has body: I want to convert a text file into a string and I was given this function to start with, which was written in Python 2: def parseOutText(f): f.seek(0) all_text = f.read() content = all_text.split("X-FileName:") words = "" if len(content) &gt; 1: text_string = content[1].translate(string.maketrans("", ""), string.punctuation) words = text_string ### split the text string into individual words, stem each word, ### and append the stemmed word to words (make sure there's a single ### space between each stemmed word) return words As you can see I have to add some code to this function, but it does not compile (compiler gives error, saying 'string' does not have function 'maketrans'). I am sure this code can easily be translated to Python 3 but I dont really understand what it does until the comment line. Does it simply omit punctuation and convert text to string?
tagged with: text
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51299510
has answer: http://stackoverflow.com/a/51299624
has comment: http://stackoverflow.com/comment/89575459
type: Question
has comment: http://stackoverflow.com/comment/89575765
possible better answer: http://stackoverflow.com/a/51299510
has comment: http://stackoverflow.com/comment/89575802
accepted answer: http://stackoverflow.com/a/51299624
has answer: http://stackoverflow.com/a/52179407
has title: Turning text file into a string (Python 3)
has comment: http://stackoverflow.com/comment/89575504
score: 0

http://stackoverflow.com/comment/89342908
comment on: http://stackoverflow.com/q/51180191
has text: The more elegant way is not to include lists or `dicts` in a `DataFrame` records. Pandas is best suited for vectorized data and their operations, nesting data structures within it contradicts its purpose and you lose many of the features. I would advise against this.
type: Comment
type: QuestionComment
score: 2

http://stackoverflow.com/a/51209920
downvote count: 0
score: 1
has body: you are adding an extra comma in the end for profile_url array. The proper json should be [{ "company": [ "ABCD" ], "fullname": [ "Bruce Lamont", "Ariel Zilist", "Bruce Lamont", "Bobby Ramirez" ], "position": [ " The Hesh", " Server", " HESH", " Production Assistant" ], "profile_url": [ "http://www.url1.com", "http://www.url2.com", "http://www.url3.com", "http://www.url4.com" ] }] Use https://jsonformatter.curiousconcept.com/ to check for JSON formatting errors next time.
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/51209598

http://stackoverflow.com/q/51227541
answer count: 0
favorite count: 0
has body: Why doesn't the following example using parameter ? substitution variable use an index? I've tried a few different methods for but none of them work, what am I missing here? Python 2.7.15 (default, Jun 17 2018, 12:51:03) [GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.42.1)] on darwin &gt;&gt;&gt; import sqlite3 &gt;&gt;&gt; sqlite3.sqlite_version_info (3, 24, 0) &gt;&gt;&gt; sqlite3.version_info (2, 6, 0) &gt;&gt;&gt; con = sqlite3.connect("/Users/Ade/test.db") &gt;&gt;&gt; csr = con.cursor() &gt;&gt;&gt; artist = 'half man half biscuit' &gt;&gt;&gt; # This works &gt;&gt;&gt; csr.execute('EXPLAIN QUERY PLAN SELECT Tracktitle FROM tracks WHERE CleanName LIKE ' + '"' + artist + '%' + '"' + '').fetchone() (3, 0, 0, u'SEARCH TABLE tracks USING INDEX tracks_CleanName_NoCase (CleanName&gt;? AND CleanName&lt;?)') &gt;&gt;&gt; # This doesn't work &gt;&gt;&gt; csr.execute('EXPLAIN QUERY PLAN SELECT TrackTitle FROM tracks WHERE CleanName LIKE ?', [artist+'%']).fetchone() (2, 0, 0, u'SCAN TABLE tracks')
type: Question
tagged with: python
has title: Python Sqlite LIKE not using index with parameter ? substitution variable
upvote count: 2
tagged with: sql-like
tagged with: substitution
linked to: http://stackoverflow.com/q/37845854
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/37845854
score: 2
tagged with: sql
tagged with: sqlite
downvote count: 0

http://stackoverflow.com/a/51180696
has comment: http://stackoverflow.com/comment/89370652
upvote count: 2
has comment: http://stackoverflow.com/comment/89393853
has comment: http://stackoverflow.com/comment/89365472
answers question: http://stackoverflow.com/q/51176474
downvote count: 0
has body: SSLError: ("bad handshake: Error([('SSL routines', 'ssl3_read_bytes', 'sslv3 alert bad certificate')],)",) This likely means that the server is expecting you to authenticate with a client certificate. My guess is that the specific certificate is in the Windows certificate store and will be automatically used by your VB script the same as it is used automatically by the browser. Only, Python does not use the windows certificate store. This mean you need to somehow extract the specific certificates from the store and use these explicitly as client certificates in your Python program as documented.
type: Answer
has comment: http://stackoverflow.com/comment/89397579
score: 2

http://stackoverflow.com/comment/90029317
comment on: http://stackoverflow.com/q/51253538
type: Comment
score: 0
has text: You should open a new question for this issue. Is `ROBOTSTXT_OBEY` set to `False` in your settings?
type: QuestionComment

http://stackoverflow.com/a/76196732
has body: Just check the indentation. There should be more space between @{list}= and Read Csv...
score: 0
has comment: http://stackoverflow.com/comment/134469835
type: Answer
answers question: http://stackoverflow.com/q/51284141

http://stackoverflow.com/q/51323272
has answer: http://stackoverflow.com/a/51323411
has title: Setting function parameter as global variable
has answer: http://stackoverflow.com/a/51323613
score: 0
has comment: http://stackoverflow.com/comment/89622125
answer count: 2
has comment: http://stackoverflow.com/comment/89621751
accepted answer: http://stackoverflow.com/a/51323411
tagged with: python
has comment: http://stackoverflow.com/comment/89621661
type: AnsweredQuestion
type: Question
has body: I'm trying to simply make a parameter received by a function accesible for all other functions in a file, or be set as a global variable, and not have to pass it as an argument for all other functions. So far I've tried to set it as a global variable but apparently cannot have a parameter be also a global. Here would be a simple example of what I would like: def add(a,b, verbose): global verbose return a + b result = add(2,3, False) print(verbose) In my case the called function is on another file, so cannot set verbose as a global beforehand. Any help would be appreciated!
tagged with: function
possible better answer: http://stackoverflow.com/a/51323613

http://stackoverflow.com/comment/89428000
comment on: http://stackoverflow.com/a/51223792
score: 1
type: AnswerComment
type: Comment
has text: Thank You very much for help!

http://stackoverflow.com/a/51229676
type: Answer
score: 1
has body: It makes sense from a CUDA perspective to disallow assignment of individual indices as it negates all performance benefits of heterogeneous parallel computing. I know this adds a bit of computational overhead but it works. import tensorflow as tf v = [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0] n = len(v) a = tf.Variable(v, name = 'a',dtype=tf.float32) def cond(i, a): return i &lt; n def body(i, a1): e = tf.eye(n,n)[i] a1 = a1 + e *(a1[i-1] + a1[i-2]) return i + 1, a1 i, b = tf.while_loop(cond, body, [2, a]) with tf.Session() as sess: sess.run(tf.global_variables_initializer()) print('i: ',sess.run(i)) print('b: ',sess.run(b))
answers question: http://stackoverflow.com/q/51225805
upvote count: 1
downvote count: 0

http://stackoverflow.com/comment/128013778
comment on: http://stackoverflow.com/a/51283979
type: AnswerComment
type: Comment
score: 1
has text: Take into account that in this case, the whole file must fit your computer's RAM

graph
tags question: http://stackoverflow.com/q/51288184
tags question: http://stackoverflow.com/q/51274491
tag name: graph
tags question: http://stackoverflow.com/q/51262395
tags question: http://stackoverflow.com/q/51287807
tags question: http://stackoverflow.com/q/51290182
tags question: http://stackoverflow.com/q/51254686
tags question: http://stackoverflow.com/q/51274995
tags question: http://stackoverflow.com/q/51235315
tags question: http://stackoverflow.com/q/51267096
tags question: http://stackoverflow.com/q/51220805
tags question: http://stackoverflow.com/q/51288530
type: Tag
tags question: http://stackoverflow.com/q/51277061

http://stackoverflow.com/q/51306881
has title: sklearn RidgeClassifierCV: unexpected keyword argument 'random_state'
score: 0
has comment: http://stackoverflow.com/comment/89604875
answer count: 0
has comment: http://stackoverflow.com/comment/89604414
has body: Why does RidgeClassifierCV from sklearn.linear_model not have a random_state keyword argument? It cross-validates RidgeClassifier, which does have random_state. Should this keyword not be passed on? Or am I missing something here? --------------------------------------------------------------------------- TypeError Traceback (most recent call last) &lt;ipython-input-612-4d3d523acbab&gt; in &lt;module&gt;() 1 # Apply ridge regression ----&gt; 2 model = linear_model.RidgeClassifierCV(cv=3, normalize=True, random_state=random_state) 3 model.fit(Xtrain, ytrain) 4 model = linear_model.RidgeClassifier(alpha=model.alpha_, normalize=True, 5 random_state=random_state) TypeError: __init__() got an unexpected keyword argument 'random_state'
type: UnansweredQuestion
tagged with: python
type: Question
tagged with: scikit-learn

http://stackoverflow.com/comment/89393233
has text: I want that end at the end of the loop
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51206090

http://stackoverflow.com/q/51220121
linked to: http://stackoverflow.com/q/51225805
type: UnansweredQuestion
tagged with: python
has title: Proper use of tf.while_loop during inference?
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/89421342
type: Question
has comment: http://stackoverflow.com/comment/89421175
has comment: http://stackoverflow.com/comment/89421257
has answer: http://stackoverflow.com/a/51220454
score: 0
answer count: 1
has body: Is it possible to use tf.TensorArray's for reading and writing inside of the body of a tf.while_loop, but not pass them all through loop_vars? I want to use tf.while_loop as part of a graph for WaveNet sound generation, which is a sequential generation mechanism that that generates the next amplitude value based on a window of previously generated ones. But, I want to use this just during inference, so no need for gradients, and would call with back_prop=False. Besides this, the loop body function must read and write intermediate values that must be remembered across time steps. It looks like tf.TensorArray is the only option for reading and writing values in this way, but I notice that tf.TensorArray.write() returns a new tf.TensorArray that is meant to be returned by the body and used in the loop_vars argument. Is this the best way to do this? If I don't have a need for gradients, is there a simpler way to preserve state over the loop?

http://stackoverflow.com/comment/89544646
type: Comment
comment on: http://stackoverflow.com/a/51283438
score: 1
has text: with `df = pd.concat([df] * 1000, ignore_index=True)`
type: AnswerComment

http://stackoverflow.com/comment/89424228
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51221465
has text: where is the pexpect('hello')?
score: 0

http://stackoverflow.com/a/51234066
has body: You need to parse the html to get images and the commments. The comments are in different pages than the images, so you need to generate the link for each image and then parse the comments there. To pull the links for articles, you need to get the id of each image and use it to generate the new link. If the id of an image is avOXW7d then your url needs to be https://9gag.com/gag/avOXW7d. I would suggest using an API and not parsing the html for this task since it is very time consuming to parse html. Doing a quick Google search, I found out that there are some unofficial APIs for 9gag. Here are some links that you can use. Link 1. Link 2.
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/51225357
type: Answer
upvote count: 1

http://stackoverflow.com/q/51245824
accepted answer: http://stackoverflow.com/a/51245924
upvote count: 1
tagged with: tensorflow
has title: E1120:No value for argument 'y' in function call on Tensorflow
type: Question
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/51245924
downvote count: 0
answer count: 1
favorite count: 0
has body: I am building a neural network with tensorflow and this is the code I am working with - import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("/tmp/data", one_hot = True) n_nodes_hl1 = 500 n_nodes_hl2 = 500 n_nodes_hl3 = 500 n_classes = 10 batch_size = 100 x = tf.placeholder('float', [None, 784]) y = tf.placeholder('float') def neural_network_model(data): hidden_layer_1 = {'weights': tf.Variable(tf.random_normal(784,n_nodes_hl1)), 'biases': tf.Variable(tf.random_normal(n_nodes_hl1))} hidden_layer_2 = {'weights': tf.Variable(tf.random_normal(n_nodes_hl1, n_nodes_hl2)), 'biases': tf.Variable(tf.random_normal(n_nodes_hl2))} hidden_layer_3 = {'weights': tf.Variable(tf.random_normal(n_nodes_hl2, n_nodes_hl3)), 'biases': tf.Variable(tf.random_normal(n_nodes_hl3))} output_layer = {'weights': tf.Variable(tf.random_normal(n_nodes_hl3, n_classes)), 'biases': tf.Variable(tf.random_normal(n_classes))} l1 = tf.add(tf.matmul(data,hidden_layer_1['weights']) + hidden_layer_1['biases']) l1 = tf.nn.relu(l1) l2 = tf.add(tf.matmul(l1, hidden_layer_2['weights']) + hidden_layer_2['biases']) l2 = tf.nn.relu(l2) l3 = tf.add(tf.matmul(l2, hidden_layer_3['weights']) + hidden_layer_3['biases']) l3 = tf.nn.relu(l3) output = tf.matmul(l3, output_layer['weights'] + output_layer['biases']) return output the lines with tf.add(lines) show the error "E1120:No value for argument 'y' in function call". I am using pytlint linter on vscode. May be it's a linter issue. Does anyone have any suggestion how to resolve this
tagged with: python
has comment: http://stackoverflow.com/comment/89470238
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89482693

http://stackoverflow.com/q/51223978
has comment: http://stackoverflow.com/comment/89437250
has body: Recently I have created a dummy android app using Python2 and Kivy. Binded it using buildozer but when I installed it on my android device everything going good so far but app is not loading the screen. It opens and instantly closed it, and no error(s) displayed :( I am using kivy 1.11.0 and buildozer version is 0.34. Application is working before binding it to .apk Python Code import kivy kivy.require('1.11.0') #from kivy.core.window._window_sdl2 import _WindowSDL2Storage from kivy.app import App from kivy.uix.label import Label from kivy.uix.gridlayout import GridLayout class screen1(GridLayout): def __init__(self, **kwargs): super(screen1, self).__init__(**kwargs) self.cols = 2 self.add_widget(Label(text="hello world!")) self.add_widget(Label(text="bye world!")) class SampleKivy(App): def build(self): return screen1() if __name__ == "__main__": SampleKivy().run()
has comment: http://stackoverflow.com/comment/89435130
score: 1
has comment: http://stackoverflow.com/comment/89448804
type: Question
has comment: http://stackoverflow.com/comment/89428302
has comment: http://stackoverflow.com/comment/89428498
has comment: http://stackoverflow.com/comment/89437187
downvote count: 0
has comment: http://stackoverflow.com/comment/89431526
favorite count: 0
has title: Python Kivy Android
has comment: http://stackoverflow.com/comment/89455549
tagged with: android
tagged with: kivy
answer count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: python

http://stackoverflow.com/comment/89483979
has text: @tadman So you would recommend using Bcrypt for user in my case?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51251668

http://stackoverflow.com/comment/89487723
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/51250626
has text: There we go, I didn't see the "share" button before, learn something new every day.
type: Comment

http://stackoverflow.com/q/51296567
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51308812
has comment: http://stackoverflow.com/comment/89590750
tagged with: python
has comment: http://stackoverflow.com/comment/89586148
has comment: http://stackoverflow.com/comment/89590324
score: 1
tagged with: setuptools
upvote count: 1
has title: How to be able to access data files in all install and distribution cases with setuptools?
type: Question
has body: I'm kind of lost in all the locations you can add data files. First, there is the MANIFEST.in file. As I understand, this is only to specify source files to be included in "source distribution". Then, there is the data_files argument to setup() function, where you list files that should be installed, but it's from the root (either /, either ~user/.local). And finally, there is package_data that pretends to do what I want... But on a bdist, I don't see any difference with data_files I have a data file, say "default_conf.cfg". my MANIFEST.in contains : include default_conf.cfg and my setup.py : setup( # ... package_data={ '': ['default_conf.cfg'], } ) When I do a ./setup.py sdist, the file is included, same with ./setup.py bdist (as expected) However, if I try to install as editable package (pip install --user -e .), I can't access it with pkg_resources.resource_string(__name__, 'default_conf.cfg') What am I missing to be able to access it from any kind on distribution/install ? (The documentation is quite verbose, and information are dispersed across several pages so it's easy to miss something.) EDIT I put my data file as a subdir of my module and it seems to be better : my_pkg/ |-my_pkg/ | |-__init__.py | |-data/ | | |-default_conf.cfg | |-setup.py setup.py : setup( # ... package_data={ 'my_module': ['data/default_conf.cfg'], } ) However, when I try to pip install --user -e ., the content of the .egg-link is /.../my_pkg/build/lib instead of /.../my_pkg, then of course, it is not live-editable... Why does setuptools use this path ?
has comment: http://stackoverflow.com/comment/89585857
has comment: http://stackoverflow.com/comment/89590303
has comment: http://stackoverflow.com/comment/89590466
has comment: http://stackoverflow.com/comment/89582514
answer count: 1
downvote count: 0
tagged with: pkg-resources
linked to: http://stackoverflow.com/q/51306780
tagged with: packaging
favorite count: 0
has comment: http://stackoverflow.com/comment/89588814
tagged with: python-3.x

http://stackoverflow.com/comment/89601561
type: QuestionComment
has text: Yes, I did read through that example. And it says that in python 3.x I should import a module. But I didn't quite see how to use the module to call those functions in the doc.
comment on: http://stackoverflow.com/q/51311521
score: 0
type: Comment

http://stackoverflow.com/comment/89628302
comment on: http://stackoverflow.com/q/51294340
score: 0
type: Comment
type: QuestionComment
has text: I figured it out. The endpoint for post via mod_wsgi requires a trailing slash! For running the web app on dev flask server that's not required however, going through Apache and mod_wsgi it is.

http://stackoverflow.com/q/51263167
has title: Patch library functions for testing
score: 1
tagged with: unit-testing
type: Question
has body: I am currently writing some tests for an application and I want to test error handling. For instance , I want to check behavior of the application when shutil.copyfile() throws an exception. Since the src and dst for this function is build up inside the function calling shutil.copyfile(), I cannot trigger a failure from my test. What I currently do is the following. import shutil as f def __patch(): def my_func(*args, **kwargs): raise f.SameFileError f.copyfile = my_func Now, I would expect that anytime copyfile is called within my application, it would throw a SameFileError error. But this does not happen at the moment. The copyfile function from shutil is still being executed. On the otherhand, if I do the same for a library that has a function to be patched inside a class, the patching works and my custom function replaces the function from the library. This works for patching extractall() function in the zipfile library because the function to be patched is inside a class. from zipfile import ZipFile, BadZipFile def __patch(): def my_func(*args, **kwargs): raise BadZipFile ZipFile.extractall = my_func Can anyone please tell me how I can get this running for the copyfile() from shutil as well. Unfortunately, I cannot use the mock library here. Thanks in advance
tagged with: mocking
has answer: http://stackoverflow.com/a/51264426
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/89504307
has comment: http://stackoverflow.com/comment/89537961
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89505549
downvote count: 0

http://stackoverflow.com/q/51311809
linked to: http://stackoverflow.com/q/20196159
has title: Simplifying a few rows of code using a for loop?
has answer: http://stackoverflow.com/a/51311937
score: 0
answer count: 3
tagged with: python
has body: While attempting to make a sudoku solving program, I encountered a small problem. That is, the amount of rows (lists) I want to append into a list. # These are the lists that i have to append row0 = [5,3,0, 0,7,0, 0,0,0] row1 = [6,0,0, 1,9,5, 0,0,0] row2 = [0,9,8, 0,0,0, 0,6,0] row3 = [8,0,0, 0,6,0, 0,0,3] row4 = [4,0,0, 8,0,3, 0,0,1] row5 = [7,0,0, 0,2,0, 0,0,6] row6 = [0,6,0, 0,0,0, 2,8,0] row7 = [0,0,0, 4,1,9, 0,0,5] row8 = [0,0,0, 0,8,0, 0,7,9] # And this, is what i want to avoid doing. rows.append(row0) rows.append(row1) rows.append(row2) rows.append(row3) rows.append(row4) rows.append(row5) rows.append(row6) rows.append(row7) rows.append(row8) Is it possible to append all those lists, with help of a for loop or something similar?
favorite count: 0
has comment: http://stackoverflow.com/comment/89600785
type: AnsweredQuestion
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/51311853
has answer: http://stackoverflow.com/a/51312026
has answer: http://stackoverflow.com/a/51311853
upvote count: 1
accepted answer: http://stackoverflow.com/a/51311937
downvote count: 1
type: Question

http://stackoverflow.com/q/51171974
score: -1
type: Question
tagged with: numpy
answer count: 2
tagged with: pandas
has answer: http://stackoverflow.com/a/51172695
upvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/57217677
has body: my dataframe urm has a shape of (96438, 3) user_id anime_id user_rating 0 1 20 7.808497 1 3 20 8.000000 2 5 20 6.000000 3 6 20 7.808497 4 10 20 7.808497 i'm trying to build an item-user-rating matrix : X = urm"user_id", "anime_id".as_matrix() y = urm["user_rating"].values n_u = len(urm["user_id"].unique()) n_m = len(urm["anime_id"].unique()) R = np.zeros((n_u, n_m)) for idx, row in enumerate(X): R[row[0]-1, row[1]-1] = y[idx] if the code succes the matrix looks like that : (i filled NaN with 0) with in index user_id, anime_id in columns and rating for the value (i got this matrix from pivot_table) is in some tutorial it works but there i got an --------------------------------------------------------------------------- IndexError Traceback (most recent call last) &lt;ipython-input-278-0e06bd0f3133&gt; in &lt;module&gt;() 15 R = np.zeros((n_u, n_m)) 16 for idx, row in enumerate(X): ---&gt; 17 R[row[0]-1, row[1]-1] = y[idx] IndexError: index 5276 is out of bounds for axis 1 with size 5143
has title: User-Item rating matrix : IndexError
type: UnansweredQuestion
downvote count: 2
tagged with: python
linked to: http://stackoverflow.com/q/51082879
has comment: http://stackoverflow.com/comment/89326770
tagged with: indexoutofboundsexception

http://stackoverflow.com/comment/89628382
type: Comment
type: QuestionComment
has text: This question would benefit from a [reproducible example](https://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples)
comment on: http://stackoverflow.com/q/51287665
score: 0

http://stackoverflow.com/a/51168781
type: Answer
has comment: http://stackoverflow.com/comment/89320602
has comment: http://stackoverflow.com/comment/89320446
score: 1
upvote count: 1
has body: Yes, on windows you can create a bat-file like this: start /B your_file.exe add this code to your app: import ctypes import os import win32process hwnd = ctypes.windll.kernel32.GetConsoleWindow() if hwnd != 0: ctypes.windll.user32.ShowWindow(hwnd, 0) ctypes.windll.kernel32.CloseHandle(hwnd) _, pid = win32process.GetWindowThreadProcessId(hwnd) os.system('taskkill /PID ' + str(pid) + ' /f')
has comment: http://stackoverflow.com/comment/89320492
has comment: http://stackoverflow.com/comment/89320585
downvote count: 0
answers question: http://stackoverflow.com/q/51168728
has comment: http://stackoverflow.com/comment/89320704

http://stackoverflow.com/q/51238604
has comment: http://stackoverflow.com/comment/89456094
tagged with: raspberry-pi
has comment: http://stackoverflow.com/comment/109243581
answer count: 1
score: 0
linked to: http://stackoverflow.com/q/33258802
tagged with: fabric
tagged with: python
has comment: http://stackoverflow.com/comment/89456240
has comment: http://stackoverflow.com/comment/89456216
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89456166
type: Question
tagged with: network-programming
has title: Python - How to set env.variables in Fabric module
has body: I'm trying to run commands in parallel on a few raspberry Pis using the Fabric module. I've read the documentation but I'm still a bit confused. import fabric env.hosts = [ "pi@192.168.3.151", "pi@192.168.3.123" ] env.password = "Raspberry" @parallel def command(cmd): sudo(cmd) command("touch /Desktop/new_filename.txt") When I run that code I get the error env is not defined, how am I supposed to define env here to use those hosts? The documentation is beyond me at this stage.
has answer: http://stackoverflow.com/a/51374537
has comment: http://stackoverflow.com/comment/89456138
has comment: http://stackoverflow.com/comment/89456081

http://stackoverflow.com/q/51290275
has comment: http://stackoverflow.com/comment/89558303
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89558597
has body: I have a pandas series called min_time_diff which has time differences calculated.Now I want to calculate the row where the time difference is minimum so I did df3.loc[min_time_diff.idxmin()]. But I just want to return a particular column from the row which is called 'Date'.Is that possible?
type: Question
has title: idxmin return a particular column
answer count: 1
score: 0
tagged with: pandas
has answer: http://stackoverflow.com/a/51290463
accepted answer: http://stackoverflow.com/a/51290463
tagged with: python

http://stackoverflow.com/comment/89472867
type: QuestionComment
type: Comment
has text: This is the first time I use Stack, but I already correct the indentation. what I mean by the question is that when I run the code either in atom or sublime, the program doesn't run, and when I run it in a web editor(Udacity web page) it shows me the error "Program shut down for using 13 CPU second on the web editor"
comment on: http://stackoverflow.com/q/51224741
score: 0

filter
tags question: http://stackoverflow.com/q/51239425
tags question: http://stackoverflow.com/q/51298698
tags question: http://stackoverflow.com/q/51272446
tags question: http://stackoverflow.com/q/51289747
tag name: filter
tags question: http://stackoverflow.com/q/51202181
tags question: http://stackoverflow.com/q/51225781
type: Tag
tags question: http://stackoverflow.com/q/51282400

http://stackoverflow.com/a/51283441
upvote count: 2
accepted answer of: http://stackoverflow.com/q/51283245
type: AcceptedAnswer
downvote count: 0
has body: My guess is that the docs just haven't been updated yet (not that rolling a http request and calling the API would be hard anyway), because if you look at the code for the BigQuery Python client library, it does indeed appear to support specifying the field when creating a partitioned table:
type: Answer
score: 2
answers question: http://stackoverflow.com/q/51283245

http://stackoverflow.com/a/51200834
has comment: http://stackoverflow.com/comment/89383354
upvote count: 1
has comment: http://stackoverflow.com/comment/89383326
score: 1
answers question: http://stackoverflow.com/q/51200805
has body: All of your program variables are, by definition, local to the scope of your program. When you exit the program, the operating system gets to reclaim the space. To make data persist after program end, you need to store it somewhere else, such as in a file -- a resource outside the volatile existence of the Python run-time system. I trust that you can look up file operations.
downvote count: 0
type: Answer

http://stackoverflow.com/comment/89547894
comment on: http://stackoverflow.com/q/51285073
type: Comment
has text: @hootnot, that has nothing at all to do with the issue. `subprocess` behaves equivalently to `execlp()`, doing PATH lookups; moreover with `shell=True`, the shell it starts is doing another lookup layer as well.
score: 0
type: QuestionComment

http://stackoverflow.com/a/51224213
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/51224092
score: 1
has body: model=model.DO_NOTHING try this hope this work
upvote count: 1

http://stackoverflow.com/q/51211416
accepted answer: http://stackoverflow.com/a/51255349
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89404270
possible better answer: http://stackoverflow.com/a/51214319
has comment: http://stackoverflow.com/comment/89403997
tagged with: python
has answer: http://stackoverflow.com/a/51214319
type: AnsweredQuestion
has body: I am trying to break a long sequence into sub-sequence with a smaller window size by using the get_slice function defined by me. Then I suddenly realized that my code is too clumsy, since my raw data is already a numpy array, then I need to store it into a list in my get_slice function. After that, when I read each row in the data_matrix, I need another list to stored the information again. The code works fine, yet the conversion between numpy array and list back and forth seems non-pythonic to me. I wonder if I am doing it right. If not, how to do it more efficiently and more pythonic? Here's my code: import numpy as np ##Artifical Data Generation## X_row1 = np.linspace(1,60,60,dtype=int) X_row2 = np.linspace(101,160,60,dtype=int) X_row3 = np.linspace(1001,1060,60,dtype=int) data_matrix = np.append(X_row1.reshape(1,-1),X_row2.reshape(1,-1),axis=0) data_matrix = np.append(data_matrix,X_row3.reshape(1,-1,),axis=0) ##---------End--------------## ##The function for generating time slice for sequence## def get_slice(X,windows=5, stride=1): x_slice = [] for i in range(int(len(X)/stride)): if i*stride &lt; len(X)-windows+1: x_slice.append(X[i*stride:i*stride+windows]) return np.array(x_slice) ##---------End--------------## x_list = [] for row in data_matrix: temp_data = get_slice(row) #getting time slice as numpy array x_list.append(temp_data) #appending the time slice into a list X = np.array(x_list) #Converting the list back to numpy array
has answer: http://stackoverflow.com/a/51255349
has comment: http://stackoverflow.com/comment/89405209
type: Question
has comment: http://stackoverflow.com/comment/89405649
has answer: http://stackoverflow.com/a/51211968
tagged with: numpy
score: 0
has title: Is putting a numpy array inside a list pythonic?
answer count: 3

http://stackoverflow.com/q/51235641
has title: Incremental XML generation inheriting root namespace map
tagged with: python
tagged with: xml-namespaces
score: 2
answer count: 0
type: Question
tagged with: contextmanager
has body: I'm using LXML's incremental XML generation to build a large XML file. I need to apply a namespace to some child elements that is defined as part of the root element (rss below), but it seems the context manager provided by the incremental XML generation feature doesn't pass the root namespace map to the child nodes. Here is an example: from lxml import etree FILENAME = "somefile.xml" NSMAP = {"myns": "http://example.com/"} with open(FILENAME, "wb") as f: # create XML streamer with etree.xmlfile(f) as xf: # root element with xf.element("root", version="1.0", nsmap=NSMAP): with xf.element("channel"): title = etree.Element("{http://example.com/}title", nsmap=NSMAP) title.text = "some text" xf.write(title) This yields the following XML file: &lt;root xmlns:myns="http://example.com/" version="1.0"&gt; &lt;channel&gt; &lt;myns:title xmlns:myns="http://example.com/"&gt;some text&lt;/myns:title&gt; &lt;/channel&gt; &lt;/root&gt; In the above, the xmlns:myns attribute is set twice, both on root and on title. Ideally, this would be defined only once, on the root node: &lt;root xmlns:myns="http://example.com/" version="1.0"&gt; &lt;channel&gt; &lt;myns:title&gt;some text&lt;/myns:title&gt; &lt;/channel&gt; &lt;/root&gt; Normally when building XML documents you would simply pass the root node to the child with etree.SubElement, and so the child element can look up the root namespace map, but in this case the context manager appears to prevent this from happening. Is there a way to achieve this when using incremental XML generation?
tagged with: lxml
downvote count: 0
tagged with: http://stackoverflow.com/tag/xml
favorite count: 0
upvote count: 2
type: UnansweredQuestion

http://stackoverflow.com/comment/90145954
type: AnswerComment
type: Comment
score: 2
comment on: http://stackoverflow.com/a/51280444
has text: I tested it and it didn't work because it lacked the PPA...

export-to-csv
tags question: http://stackoverflow.com/q/51313171
type: Tag
tags question: http://stackoverflow.com/q/51302922
tags question: http://stackoverflow.com/q/51289507
tag name: export-to-csv
tags question: http://stackoverflow.com/q/51272730
tags question: http://stackoverflow.com/q/51225909

http://stackoverflow.com/comment/89615601
score: 1
comment on: http://stackoverflow.com/q/51319979
type: Comment
type: QuestionComment
has text: Can you add [minimal, complete, and verifiable example](http://stackoverflow.com/help/mcve) ?

http://stackoverflow.com/a/51254513
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/51254431
has comment: http://stackoverflow.com/comment/89487941
has body: Use transform('last') instead of last, then simply divide: df'B', 'C'.div(df.groupby('key').A.transform('last'), axis=0) B C 0 2.000 1.000 1 1.750 1.750 2 1.500 0.500 3 1.250 1.500 4 0.500 0.500 5 0.375 0.250 6 0.250 0.250 7 0.125 0.125 To show why this works: df.groupby('key').A.transform('last') 0 4 1 4 2 4 3 4 4 8 5 8 6 8 7 8 Name: A, dtype: int64 By using transform('last') instead of last, every element in the series is "transformed" to the last value in each group. Then we can simply divide each row by the equivalent value in this result.
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51254431
score: 3
has comment: http://stackoverflow.com/comment/89488108
upvote count: 3
has comment: http://stackoverflow.com/comment/89488073

http://stackoverflow.com/a/51181310
has body: As long as your string is an integer multiple of 4, you can use NumPy in a very efficient way: import numpy as np data = np.fromstring(textdata, dtype='&gt;u4') # array([1952999795, 543781664, 1836654708, 1702065184, 1684108385]) '&gt;u4' means 'big-endian unsigned 4-byte integer'. Edit: If you use NumPy >= 1.14, then np.fromstring is deprecated, and the right way to process your text is by calling np.frombuffer(textdata.encode(), dtype='&gt;u4').
answers question: http://stackoverflow.com/q/51181193
has comment: http://stackoverflow.com/comment/89345075
upvote count: 1
type: Answer
downvote count: 0
score: 1

http://stackoverflow.com/q/51296770
answer count: 3
has answer: http://stackoverflow.com/a/51297268
linked to: http://stackoverflow.com/q/15221473
tagged with: pip
has comment: http://stackoverflow.com/comment/89571523
has comment: http://stackoverflow.com/comment/89571634
has comment: http://stackoverflow.com/comment/93959571
tagged with: ubuntu-18.04
has comment: http://stackoverflow.com/comment/89571113
has comment: http://stackoverflow.com/comment/89571670
possible better answer: http://stackoverflow.com/a/53168206
has answer: http://stackoverflow.com/a/53168206
has answer: http://stackoverflow.com/a/51296875
upvote count: 15
accepted answer: http://stackoverflow.com/a/51297268
type: AnsweredQuestion
downvote count: 0
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89571392
type: Question
has title: How can I update pip3 to its latest version in Ubuntu 18.04?
tagged with: python
has body: I get this error when running pip3 install -U pip Output: Requirement already up-to-date: pip in ./dlenv/lib/python3.6/site-packages (10.0.1) launchpadlib 1.10.6 requires testresources, which is not installed. I have searched in apt and testresources seems to be installed already. apt search testresources Sorting... Done Full Text Search... Done python-testresources/bionic,bionic 2.0.0-2 all PyUnit extension for managing expensive test fixtures - Python 2.x python3-testresources/bionic,bionic 2.0.0-2 all PyUnit extension for managing expensive test fixtures - Python 3. I've gone through this GitHub issue, which was not clear with a solution.
has comment: http://stackoverflow.com/comment/89571411
score: 15

http://stackoverflow.com/q/51214726
accepted answer: http://stackoverflow.com/a/51214750
answer count: 1
has title: How can I create a dictionary from a list of lists and another list?
tagged with: python
tagged with: dictionary
type: AnsweredQuestion
tagged with: list
linked to: http://stackoverflow.com/q/7257588
type: Question
duplicate of: http://stackoverflow.com/q/7257588
tagged with: arrays
has answer: http://stackoverflow.com/a/51214750
has body: I have this array: [[330.0, 539.0, 241.0, 387.0], [544.0, 754.0, 243.0, 387.0], [1190.0, 1279.0, 241.0, 386.0], [545.0, 754.0, 393.0, 445.0], [1190.0, 1279.0, 99.0, 196.0], [544.0, 754.0, 98.0, 195.0], [330.0, 539.0, 393.0, 444.0], [760.0, 969.0, 143.0, 194.0], [760.0, 969.0, 242.0, 391.0], [329.0, 539.0, 100.0, 142.0], [759.0, 968.0, 492.0, 695.0], [975.0, 1185.0, 491.0, 642.0], [975.0, 1183.0, 242.0, 387.0], [1189.0, 1279.0, 491.0, 642.0], [975.0, 1184.0, 99.0, 141.0], [55.0, 307.0, 568.0, 626.0], [330.0, 527.0, 534.0, 576.0], [329.0, 539.0, 586.0, 642.0], [55.0, 228.0, 203.0, 240.0], [55.0, 227.0, 164.0, 200.0], [100.0, 308.0, 0.0, 106.0], [545.0, 754.0, 493.0, 549.0], [55.0, 274.0, 611.0, 639.0], [336.0, 527.0, 501.0, 543.0]] And this one: [0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 3, 3, 1, 1, 1, 2, 0, 1, 3] They are both the same dimention, how can I merge them into a dictionary like {[330.0, 539.0, 241.0, 387.0]:0, [544.0, 754.0, 243.0, 387.0]:0 etc...}
score: 0

http://stackoverflow.com/q/51240878
has comment: http://stackoverflow.com/comment/89461114
downvote count: 0
possible better answer: http://stackoverflow.com/a/51246799
score: 7
has comment: http://stackoverflow.com/comment/89460593
accepted answer: http://stackoverflow.com/a/51241776
type: Question
tagged with: discord.py
has comment: http://stackoverflow.com/comment/89461594
has answer: http://stackoverflow.com/a/51241776
answer count: 3
upvote count: 7
has comment: http://stackoverflow.com/comment/89462037
has comment: http://stackoverflow.com/comment/89461130
tagged with: discord
favorite count: 0
has title: Discord bot check if user is admin
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51246799
has answer: http://stackoverflow.com/a/62570587
tagged with: python
has body: Hi i'm new to python coding with discord and I have tried to make a command that tells the user if they are a admin or not but well... its not working in the slightest @client.command(name="whoami",description="who are you?") async def whoami(): if message.author == client.user: return if context.message.author.mention == discord.Permissions.administrator: msg = "You're an admin {0.author.mention}".format(message) await client.send_message(message.channel, msg) else: msg = "You're an average joe {0.author.mention}".format(message) await client.send_message(message.channel, msg) I then get this when I try to type whoami Ignoring exception in command whoami Traceback (most recent call last): File "/home/python/.local/lib/python3.6/site-packages/discord/ext/commands/core.py", line 50, in wrapped ret = yield from coro(*args, **kwargs) File "&lt;stdin&gt;", line 3, in whoami NameError: name 'message' is not defined The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/python/.local/lib/python3.6/site-packages/discord/ext/commands/bot.py", line 846, in process_commands yield from command.invoke(ctx) File "/home/python/.local/lib/python3.6/site-packages/discord/ext/commands/core.py", line 374, in invoke yield from injected(*ctx.args, **ctx.kwargs) File "/home/python/.local/lib/python3.6/site-packages/discord/ext/commands/core.py", line 54, in wrapped raise CommandInvokeError(e) from e discord.ext.commands.errors.CommandInvokeError: Command raised an exception: NameError: name 'message' is not defined
has comment: http://stackoverflow.com/comment/89461174
type: AnsweredQuestion

pickle
tags question: http://stackoverflow.com/q/51307275
tags question: http://stackoverflow.com/q/51237591
tags question: http://stackoverflow.com/q/51316106
tags question: http://stackoverflow.com/q/51264460
tags question: http://stackoverflow.com/q/51198238
type: Tag
tags question: http://stackoverflow.com/q/51194214
tags question: http://stackoverflow.com/q/51236028
tags question: http://stackoverflow.com/q/51216470
tags question: http://stackoverflow.com/q/51235713
tags question: http://stackoverflow.com/q/51205868
tag name: pickle
tags question: http://stackoverflow.com/q/51202053

http://stackoverflow.com/q/51217300
accepted answer: http://stackoverflow.com/a/51218633
has comment: http://stackoverflow.com/comment/89417393
tagged with: python
has title: Python program still running but PID can't be found
type: AnsweredQuestion
tagged with: subprocess
tagged with: nohup
score: 1
type: Question
has comment: http://stackoverflow.com/comment/89418437
has comment: http://stackoverflow.com/comment/89416434
tagged with: pid
upvote count: 1
answer count: 1
downvote count: 0
favorite count: 0
has body: I am running a detached child program in background from my parent program. After i exited the parent program, i would expect the child program to continuing running and logging into OUTPUT_PATH. And indeed, i can see the log file updating. However as i was trying to find the PID from ps aux i can't find it. can anyone explain this behavior? what am i doing wrong? shellCommand = "nohup python PYTHON_PROGRAM ARGS &gt;OUTPUT_PATH 2&gt;&amp;1 &amp;" subprocess.Popen(shellCommand, shell=True, preexec_fn=os.setpgrp)
has answer: http://stackoverflow.com/a/51218633

http://stackoverflow.com/q/51175450
tagged with: dataframe
type: UnansweredQuestion
has body: I have a dataframe with several different columns where I would like to sum the counts of where a df[x] = df[y]. So to make an example of what I'm trying to do, I'll use two example columns. Imagine a DF with a column FAVORITE_COLORS and a column COUNTRY. I would like to sum all the different combinations of these, I.e how many times England has the favorite color "Blue", "Yellow" etc. and store this in a df. So my desired output would be COUNTRY BLUE YELLOW COLOR... 0 England 1232 3312 Sum 1 Hungary 5543 7661 Sum 2 ETC ETC ETC I tried using the pandas groupby and count, using pythons len(df) when I created a new df containing only the matches, but it seemed very cumbersome and I couldn't get it to work properly. Any thoughts on how to approach this? Thanks in advance
tagged with: pandas
has comment: http://stackoverflow.com/comment/89333790
type: Question
tagged with: count
tagged with: python
linked to: http://stackoverflow.com/q/39132742
has comment: http://stackoverflow.com/comment/89333754
score: 0
duplicate of: http://stackoverflow.com/q/39132742
has title: Dataframe containing counts where column conditions are met
answer count: 0

http://stackoverflow.com/a/58961635
answers question: http://stackoverflow.com/q/51294999
type: Answer
upvote count: 4
downvote count: 0
has body: In your Test.kv file, after FileChooserIconView: add multiselect: True FileChooserIconView: multiselect: True This will allow the selection of multiple files. If you use FileChooserListView instead of FileChooserIconView, the file chooser window will not discriminate selected/not selected files visually. You can still select multiple files, but you need to remember the selected files. The first click selects and the second click deselects. I hope the developers of this widget will correct this issue soon.
score: 4

http://stackoverflow.com/comment/89621610
type: Comment
score: 2
comment on: http://stackoverflow.com/a/51323112
type: AnswerComment
has text: Wow! This is excellent :) I have gone with the 3rd solution for now. But will use the first solution in the future.

http://stackoverflow.com/comment/89436697
comment on: http://stackoverflow.com/a/51228197
type: Comment
score: 1
has text: Yes, `rk_normal` in `normal` and then you get https://github.com/numpy/numpy/blob/bb5d666e84e2eb294543a67c6143d7e9124d1c73/numpy/random/mtrand/distributions.c#L105
type: AnswerComment

http://stackoverflow.com/comment/89586586
type: AnswerComment
comment on: http://stackoverflow.com/a/51303150
type: Comment
score: 0
has text: Thanks, but doesn't work. I had same problem :-( **Output: ** table ahahave the chber be breakn chewillolhahave be plie in the street I hahave a lot of cat.

http://stackoverflow.com/a/51322446
answers question: http://stackoverflow.com/q/51322338
accepted answer of: http://stackoverflow.com/q/51322338
has body: You can render your form fields manually in django, here is how. {% for field in form %} {{ field.errors }} {{ field.label_tag }} {{ field }} {% if field.help_text %} {% endif %} {% endfor %} EDIT: I didn't get the question properly You could have your form tag attributes in a dictionary and iterate through your forms in a structure like this: Python: forms = { form_object: {"name": "upload", "action": "foo", "method": "POST"} } Template: {% for form, tag_attributes in forms.items %} Do stuff with your {{form}} {% endfor %}
score: 0
has comment: http://stackoverflow.com/comment/89621786
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/89620506
has comment: http://stackoverflow.com/comment/89621993
has comment: http://stackoverflow.com/comment/89621879

http://stackoverflow.com/comment/89550668
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51285593
has text: If my answer solves your question consider accepting it as the correct answer.

http://stackoverflow.com/a/51321047
has comment: http://stackoverflow.com/comment/89623696
score: 0
type: Answer
has body: Argh, the answer is simply to put the WHOLE or absolute path: pullData = open('/Users/nrsmoll/PycharmProjects/SeaofStats/sampleData.csv', "r").read() So simple. But if anyone knows how to make it so I don't have to put the absolute path in there, that would be great, I suspect that will be needed when making a standalone project.
has comment: http://stackoverflow.com/comment/89618489
answers question: http://stackoverflow.com/q/51320783

http://stackoverflow.com/comment/89527968
type: Comment
type: QuestionComment
has text: @jcruzer: I know how mRNA transcription to proteins works. I also know that there's more than one codon for each amino acid. The possibilities are listed in your d[] data (up to 4 codons for some AAs, with some codons not matching any AA, these are used as 'frames markers' in DNA/RNA). I can't figure out what is it that you are looking for, though. BTW: I checked that the (full-length) xAA sequence is NOT coded for anywhere in xmRNA. A sequence that codes for the first 39 AAs in xAA can be found at position 487 in xmRNA, that's the longest one I found (looking for xAA[0:x] only).
comment on: http://stackoverflow.com/q/51274388
score: 0

http://stackoverflow.com/comment/89573904
has text: If the question is rather how to have that big of a data set that contains only integers, you can always use array.array which would be slower but more memory efficient.
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/51297602

http://stackoverflow.com/q/51304490
tagged with: time
possible better answer: http://stackoverflow.com/a/51304607
has title: Grouping images by time interval python
tagged with: python
accepted answer: http://stackoverflow.com/a/51304735
type: AnsweredQuestion
tagged with: image
has comment: http://stackoverflow.com/comment/89585534
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/51304735
has body: I have a script with taking out exif data from images, and putting it into to the list, I sort my list after and that's what i have its a list of lists, on first position its a image time in seconds and 2nd place its a image path, its my list, [[32372, 'F:\rubish\VOL1\cam\G0013025.JPG'], [32373, 'F:\rubish\VOL1\cam\G0013026.JPG'], [32373, 'F:\rubish\VOL1\cam\G0013027.JPG'],.... etc etc etc That a script with grouping my images made by @blhsing , with works great, but I want to start my grouping , not from first image , start grouping by given position That a script: groups = [] for r in img: if groups and r[0] - groups[-1][-1][0] &lt;= 5: groups[-1].append(r) else: groups.append([r]) for g in groups: print(g[0][1], g[0][0], g[-1][0], g[-1][1]) And that what I have and , its does not work well , its taking only one image, , does no create a group , did somebody can help me please to fix it ?? groups = [] print(iii, "iii") #print(min_list, " my min list ") img.sort() cnt = 0 mili = [32372, 34880] for n in min_list: #print(n, "mili") for i in img: #print(i[0]) if n == i[0]: if groups and i[0] - groups[-1][-1][0] &lt;= 5: groups[-1].append(i) else: groups.append([i]) for ii in groups: print(ii[0][1], ii[0][0], ii[-1][0], ii[-1][1]) Over here I have my min_list with 2 position means I want to create only 2 groups , and classifier only images starting from those 2 position , with interval as before 5 seconds.
score: 0
has answer: http://stackoverflow.com/a/51304607

http://stackoverflow.com/comment/89578391
type: QuestionComment
comment on: http://stackoverflow.com/q/51279846
has text: If the evaluation has precise rules and you can explain them properly in a new question, on SO you'll find someone able to help you.
score: 0
type: Comment

nlp
tags question: http://stackoverflow.com/q/51300268
tags question: http://stackoverflow.com/q/51244489
tags question: http://stackoverflow.com/q/51259007
tags question: http://stackoverflow.com/q/51309278
tags question: http://stackoverflow.com/q/51317259
tags question: http://stackoverflow.com/q/51185830
tags question: http://stackoverflow.com/q/51252914
tags question: http://stackoverflow.com/q/51295141
tags question: http://stackoverflow.com/q/51256297
tags question: http://stackoverflow.com/q/51283580
tags question: http://stackoverflow.com/q/51239434
tags question: http://stackoverflow.com/q/51201830
tags question: http://stackoverflow.com/q/51316438
tags question: http://stackoverflow.com/q/51221525
tags question: http://stackoverflow.com/q/51186004
tags question: http://stackoverflow.com/q/51269058
tags question: http://stackoverflow.com/q/51189880
tags question: http://stackoverflow.com/q/51220868
tag name: nlp
tags question: http://stackoverflow.com/q/51233632
type: Tag
tags question: http://stackoverflow.com/q/51214026
tags question: http://stackoverflow.com/q/51302903
tags question: http://stackoverflow.com/q/51208986
tags question: http://stackoverflow.com/q/51231588
tags question: http://stackoverflow.com/q/51237716
tags question: http://stackoverflow.com/q/51189483
tags question: http://stackoverflow.com/q/51324178

http://stackoverflow.com/comment/123655041
score: 0
type: AnswerComment
type: Comment
has text: Hey, the docs say "probplot generates a probability plot, which should not be confused with a Q-Q or a P-P plot. Statsmodels has more extensive functionality of this type, see statsmodels.api.ProbPlot" which might be worth bearing in mind if you explicitly want a qq plot (docs = https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.probplot.html)
comment on: http://stackoverflow.com/a/51439172

http://stackoverflow.com/q/51323038
tagged with: pandas
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/51323104
score: 8
has answer: http://stackoverflow.com/a/51323112
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89621297
upvote count: 8
answer count: 5
tagged with: python
possible better answer: http://stackoverflow.com/a/51323215
type: AnsweredQuestion
has title: Pandas: Replace a string with 'other' if it is not present in a list of strings
type: Question
has answer: http://stackoverflow.com/a/51323223
has answer: http://stackoverflow.com/a/70086322
has answer: http://stackoverflow.com/a/51323215
accepted answer: http://stackoverflow.com/a/51323112
has body: I have the following data frame, df, with column 'Class' Class 0 Individual 1 Group 2 A 3 B 4 C 5 D 6 Group I would like to replace everything apart from Group and Individual with 'Other', so the final data frame is Class 0 Individual 1 Group 2 Other 3 Other 4 Other 5 Other 6 Group The dataframe is huge, with over 600 K rows. What is the best way to optimally look for values other than 'Group' and 'Individual' and replace them with 'Other'? I have seen examples for replace, such as: df['Class'] = df['Class'].replace({'A':'Other', 'B':'Other'}) but since the sheer amount of unique values i have are too many i cannot individually do this. I want to rather just use the exclude subset of 'Group' and 'Individual'.

http://stackoverflow.com/a/67536537
score: 0
answers question: http://stackoverflow.com/q/51293378
type: Answer
has body: The issue you are seeing is that the maximum lag length is too high. First, your data has a strong trend so you should initially include trend="ct". This improves the test statistic but it is not enough. When you different, the differenced data has a non-zero mean and so the trend should be "c". This still does not reject, and so a double difference is needed. The double difference is probably needed because the series is persistent but also because ADF tests have low power. You should set the maximum lags to be less than the square root of the sample size. What is happening here is that too many lags are being used which reduces the effective sample size so that the model fit is near perfect. The produces a spuriously high number of lags being chosen. from arch.unitroot import ADF import pandas as pd import numpy as np y = [3126.0, 3321.0, 3514.0, 3690.0, 3906.0, 4065.0, 4287.0, 4409.0, 4641.0, 4812.0, 4901.0, 5028.0, 5035.0, 5083.0, 5183.0, 5377.0, 5428.0, 5601.0, 5705.0, 5895.0, 6234.0, 6542.0, 6839.0] y = pd.Series(y) max_lags = int(np.sqrt(y.shape[0])) print(f"max_lags: {max_lags}") ADF(y, trend="ct", max_lags=max_lags).summary() The outputs max_lags: 4 Augmented Dickey-Fuller Results ===================================== Test Statistic -2.009 P-value 0.596 Lags 2 ------------------------------------- Trend: Constant and Linear Time Trend Critical Values: -4.50 (1%), -3.66 (5%), -3.27 (10%) Null Hypothesis: The process contains a unit root. Alternative Hypothesis: The process is weakly stationary. Next, the difference, ADF(y.diff().dropna(), trend="c", max_lags=max_lags).summary() which returns Augmented Dickey-Fuller Results ===================================== Test Statistic -2.224 P-value 0.198 Lags 0 ------------------------------------- Trend: Constant Critical Values: -3.79 (1%), -3.01 (5%), -2.65 (10%) Null Hypothesis: The process contains a unit root. Alternative Hypothesis: The process is weakly stationary. The null is not rejected. Differencing one m…

http://stackoverflow.com/comment/89492780
has text: Where am I actually looking for the "copy.py" file? Coz i can't find it in the xml or xml/etree folders
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51256948

http://stackoverflow.com/comment/89547257
comment on: http://stackoverflow.com/q/51284268
score: 0
type: Comment
type: QuestionComment
has text: Thank you. At the end of the question is the Minimal Complete and Verifiable example.

http://stackoverflow.com/comment/89570182
has text: @Gonzalo Adrover, you need to create an list of object first. Like David=Players("David","Bechham",40,190,70) Tom=Players("Tom","Hanks",49,180,80) And list_teams=[David,Tom]
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51296172
type: AnswerComment

http://stackoverflow.com/q/51317473
score: 1
upvote count: 1
type: Question
tagged with: pyspark
linked to: http://stackoverflow.com/q/35844330
has body: This is the structure of my dataframe using df.columns. ['LastName', 'FirstName', 'Stud. ID', '10 Relations', 'Related to Politics', '3NF', 'Documentation &amp; Scripts', 'SQL', 'Data (CSV, etc.)', '20 Relations', 'Google News', 'Cheated', 'Sum', 'Delay Factor', 'Grade (out of 2)'] I have transformed this dataframe in pyspark using assembler = VectorAssembler(inputCols=['10 Relations', 'Related to Politics', '3NF'],outputCol='features') and output = assembler.transform(df). Now it contains some Row objects. These objects have this architecture (This is what I get when I run output.printSchema()) root |-- LastName: string (nullable = true) |-- FirstName: string (nullable = true) |-- Stud. ID: integer (nullable = true) |-- 10 Relations: integer (nullable = true) |-- Related to Politics: integer (nullable = true) |-- 3NF: integer (nullable = true) |-- Documentation &amp; Scripts: integer (nullable = true) |-- SQL: integer (nullable = true) |-- Data (CSV, etc.): integer (nullable = true) |-- 20 Relations: integer (nullable = true) |-- Google News: integer (nullable = true) |-- Cheated: integer (nullable = true) |-- Sum: integer (nullable = true) |-- Delay Factor: double (nullable = true) |-- Grade (out of 2): double (nullable = true) |-- features: vector (nullable = true) For each row, the assembler chooses to make the features vector Sparse or Dense (For memory reasons). But this is a big problem. Because I want to use this transformed data for making a linear regression model. So, I'm searching for a way to make VectorAssembler always choose Dense Vector. Any idea? Note: I have read this post. But the problem is that since the Row class is a subclass of tuple, I cannot change a Row object after it is made.
accepted answer: http://stackoverflow.com/a/51319484
has title: Make VectorAssembler always choose DenseVector
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51319484

http://stackoverflow.com/comment/89540469
type: Comment
type: QuestionComment
has text: @guma44 You already do it 10,000 times using timeit. Do you plan to read such a file millions of times?
comment on: http://stackoverflow.com/q/51280942
score: 0

http://stackoverflow.com/a/52194625
downvote count: 0
type: Answer
score: 2
upvote count: 2
has body: dx.get_classes() will return all the classes. You can then check the ones marked as "EXTERNAL" for API calls. See the link: Using the analysis object
answers question: http://stackoverflow.com/q/51253619

http://stackoverflow.com/q/51216549
favorite count: 0
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
score: -3
tagged with: python
linked to: http://stackoverflow.com/q/37715222
has answer: http://stackoverflow.com/a/51216739
has comment: http://stackoverflow.com/comment/89414644
downvote count: 3
type: Question
has title: Can you help me reverse geocode a csv file using python?
tagged with: geocode
upvote count: 0
answer count: 1
has body: I found a python code on stack overflow here Reverse geocode, reading .CSV file and TypeError: a float is required I am trying to reverse geocode my own CSV file. I decided to use (Python 2.7.10 (default, May 23 2015, 09:40:32) [MSC v.1500 32 bit (Intel)] on win32) because I believe that is what the code I'm using was written in. This is the code from pygeocoder import Geocoder import csv gmaps = Geocoder(api_key='api-key') input = open('C:/Users/DavidDouglas/pythongeocode/BikeEvent_view.csv','r') output = open('C:/Users/Steffen/pythongeocode/addresses.csv','w') try: reader = csv.reader(input) writer = csv.writer(output) for row in reader: print(row) coordinates1 = row[1] coordinates2 = row[2] my_location = gmaps.reverse_geocode(float(coordinates1), float(coordinates2)) writer.writerow(my_location) finally: input.close() output.close() I'm getting the error File "c:/Users/DavidDouglas/code/python/reversegeocode.py", line 13 for row in reader: ^ SyntaxError: invalid syntax This is probably a very silly question that python pros will laugh at, but I'm pretty new to the language and am trying to help out a friend. Thanks for any assitance

http://stackoverflow.com/comment/89596146
type: QuestionComment
has text: I think you need `OrdinalEncoder` described https://github.com/scikit-learn-contrib/categorical-encoding and http://contrib.scikit-learn.org/categorical-encoding/ordinal.html
score: 0
comment on: http://stackoverflow.com/q/51308994
type: Comment

http://stackoverflow.com/comment/89624114
type: AnswerComment
score: 0
has text: Do you know where I can find any related document?
type: Comment
comment on: http://stackoverflow.com/a/51318514

http://stackoverflow.com/comment/89439496
comment on: http://stackoverflow.com/q/51228959
has text: `(ds['time'] - np.datetime64('2000-01-01 00:00:00)).astype(int) / (30 * 60 * 1e9)` is what you want?
score: 3
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89562885
score: 0
type: AnswerComment
has text: I'm not sure if this is the correct way to be going about it but I'm currently putting it in as `CLIENT_URI = os.environ.get("CLIENT_URI")`
type: Comment
comment on: http://stackoverflow.com/a/51255876

http://stackoverflow.com/a/51307109
score: 0
type: Answer
has body: process.poll() returns something other than None as soon as the subprocess finishes executing. That says absolutely nothing about whether or not you've read all of the subprocess's output! You need to keep calling process.stdout.readline() in a loop until it returns an empty string - in fact that's the only loop you need in this case, since process.poll() isn't giving you any information that you're actually using.
answers question: http://stackoverflow.com/q/51294742

http://stackoverflow.com/comment/89606618
comment on: http://stackoverflow.com/a/51312673
type: Comment
score: 0
type: AnswerComment
has text: Hmmm, yes there is. OP never mentioned globals. You're the one that brought it up and suggest he use it. In your honest opinion, is fixing a problem using bad pratices really fixing a problem ?

http://stackoverflow.com/q/51272027
score: 0
has answer: http://stackoverflow.com/a/51863758
answer count: 1
has title: trimming the output of difflib.Differ
type: UnansweredQuestion
tagged with: compare
tagged with: python
has body: I want to have more informative message for assertEqual mismatches and I am using difflib.Differ for that. However, when the file is big, it returns way too much info. How do I achieve something like diffs windowing that only shows a few context lines? @@ -155,6 +155,8 @@ except (ImportError,) as e: raise +tst + class KeepTextFilter(object): def __init__(self, regexes = [], f_notify=None): This is my test code: def get_data(): left, right = [],[] for num in range(0,10): lmark = rmark = " " if not (num % 5): lmark, rmark = "L", "R" left.append("%02d%s" % (num, lmark)) right.append("%02d%s" % (num,rmark)) return left, right from difflib import Differ differ = Differ() left, right = get_data() print(left) print(right) output = "\n".join(differ.compare(left, right)) print(output) and this is what the output looks like (given bigger lists, it will put out everything) ['00L', '01 ', '02 ', '03 ', '04 ', '05L', '06 ', '07 ', '08 ', '09 '] ['00R', '01 ', '02 ', '03 ', '04 ', '05R', '06 ', '07 ', '08 ', '09 '] - 00L + 00R 01 02 03 04 - 05L + 05R 06 07 08 09 How could I achieve have a window of say 1. i.e. - 00L + 00R 01 04 - 05L + 05R 06 I am thinking hacking something together with a deque(maxlen=1) but thought I would ask - this seems like an obvious requirement. I looked at the constructor for Differ() and compare's signature, but neither have this option.
tagged with: unit-testing
type: Question

docker-api
tag name: docker-api
type: Tag
tags question: http://stackoverflow.com/q/51202031

http://stackoverflow.com/q/51231735
has answer: http://stackoverflow.com/a/51232020
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51232020
tagged with: post
type: Question
has body: Using request lib, I want to post more than 1 parameter to a URL/endpoint. data1="lol" data2="lol2" payload = {'data1param': data1} r = requests.get('https://example.com/endpoint.php', params=payload) How do I post more than 1 parameter? Do I modify payload like payload = {'data1param': data1, 'data2param': data2) Just need to confirm my syntax because I am getting null when POST-ing more than 1 parameter?
has title: POSTing multiple parameters to endpoint in python
score: 0
answer count: 1
tagged with: python
tagged with: request

http://stackoverflow.com/a/51325203
downvote count: 0
has body: SMOTE does not perform filling up your missing or NaN values. You need to fill them up and then feed for SMOTE analysis. Dealing with missing values is a different task altogether, you can take a look at Imputer from sklearn to begin with. Here is another write-up on sklearn regarding missing values : Imputing missing values Once you have finished dealing with NaN values, then feed your modified data to SMOTE. References Predicting missing values with Scikit-learn Imputer module Handling missing data with Python Handling missing values
answers question: http://stackoverflow.com/q/51322554
type: Answer
score: 6
upvote count: 6
has comment: http://stackoverflow.com/comment/89626160

http://stackoverflow.com/a/51268600
type: Answer
score: 2
accepted answer of: http://stackoverflow.com/q/51213408
upvote count: 2
has body: I was able to figure out the solution to my problem. zip_file = open(os.path.join(root, file), 'rb') headers = {'content-type': 'application/zip'} return_val = requests.put(url=url, data=zip_file, auth=HTTPBasicAuth(username, password),headers=header_type)
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51213408

http://stackoverflow.com/a/51266980
type: Answer
has body: I don't see much flickering, although it looks like you have a more expensive function in the interactive. Could you describe what you want to happen a little more? Maybe widgets.link will help compared to a.observe? import ipywidgets as widgets ncalls =0 caption = widgets.Label(value='N Calls: ' + str(ncalls)) a = widgets.IntSlider(min=-5, max=5, value=1, description='a') b = widgets.IntSlider(min=-5, max=5, value=1, description='b') def handle_slider_change(change): b.value = change["new"] - change["old"] + b.value def f(a, b): global ncalls ncalls +=1 caption.value = 'N Calls: ' + str(ncalls) print(a,b) widgets.link((a, 'value'), (b, 'value')) out = widgets.interactive_output(f, {"a":a, "b":b}) widgets.VBox([caption,a,b,out])
answers question: http://stackoverflow.com/q/51197004
score: 0

http://stackoverflow.com/comment/89350384
has text: I don't think you know what the word "arbitrary" means.
score: 1
comment on: http://stackoverflow.com/q/51184223
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89515864
comment on: http://stackoverflow.com/q/51247566
has text: @PatrickHaugh Does it mean that I have to turn everything into a mutable variable before I modify them in a function?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89523930
score: 0
type: Comment
comment on: http://stackoverflow.com/q/51272754
has text: @JoeHealey: you probably have a UCS4 build in that case (`sys.maxunicode` is then 1114111, rather than 65535 on a UCS2 build).
type: QuestionComment

http://stackoverflow.com/comment/89396232
has text: Have you tried it with Py3.6? There are lots of libraries that haven't been updated yet, In your python shell, type "which python" and see if you are indeed using Py3.7.
comment on: http://stackoverflow.com/q/51207625
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/89378105
comment on: http://stackoverflow.com/a/51181241
has text: @abarnert My example actually has multiple inheritance, so I don't see how what you are saying contradicts to it. Am I missing something? Or did I just not write the answer clearly enough to make the point clear?
score: 0
type: AnswerComment
type: Comment

numerical-methods
tags question: http://stackoverflow.com/q/51220597
tags question: http://stackoverflow.com/q/51301647
tags question: http://stackoverflow.com/q/51291324
type: Tag
tags question: http://stackoverflow.com/q/51286830
tag name: numerical-methods

http://stackoverflow.com/a/51181923
downvote count: 0
has comment: http://stackoverflow.com/comment/89346661
has comment: http://stackoverflow.com/comment/89346510
type: Answer
has comment: http://stackoverflow.com/comment/89346606
answers question: http://stackoverflow.com/q/51181876
score: 2
upvote count: 2
has body: dir is a builtin function. You're trying to join that function to the string 'index.html', hence the error. The reason you're presumably confused is that you tried to hide dir with a string, here: dir = path.abspath(path.dirname(__file__)) But when you put that inside a class definition, that doesn't create a global variable that hides the builtin, it creates a class attribute. To access a class attribute from within a method of that class, you have to do the same thing you do with a normal instance attribute: content_path = path.join(self.dir, 'index.html') The only differences between class attributes and instance attributes are that: All of your instances share the same dir attribute instead of each having their own copy. You can access it as RequestHandler.dir or type(self).dir instead of just as self.dir. To avoid this kind of confusion, it's a good idea to avoid reusing the names of any of the builtin functions. While it's legal to do so, it often leads to mistakes just like this one, and makes it harder to debug those mistakes. Also, given that dir is a constant across the entire program, just like hostName and hostPort are, and isn't all that closely tied to the RequestHandler type, maybe you just wanted a global constant, like hostName, instead of a class attribute.
has comment: http://stackoverflow.com/comment/89346530

http://stackoverflow.com/comment/89381991
score: 0
type: Comment
comment on: http://stackoverflow.com/q/51200093
type: QuestionComment
has text: @abarnert: not really: running `coverage` twice for the sake of a small snippet is no good.

http://stackoverflow.com/a/78493283
has body: @Sana's answer was close. I think I know why I output an error for you though. Here's the corrected code (you want to save the output file "bar" with the extension "dotx" rather than "docx" as it appears in the last line of Sana's code): Prerequisites First we need to make sure we have the correct package (python-docx) installed, by running the following line in your console of choice: Note This can be a bit tricky because the top of the script should include "import docx", BUT the python package docx is actually an older deprecated version of the updated python-docx. So before you run the script you will want to run the following using the latter (python-docx) and NOT the former (docx)!! pip install python-docx Now make sure that the *.docx file that you want to convert to a Word template (i.e., a *.dotx file) is in the same directory as your script. This way you can avoid having to include the full file path to the original document in script itself: The code: import docx # replace "foo.docx" below with file name of document to be converted document = docx.Document('foo.docx') document_part = document.part document_part._content_type = 'application/vnd.openxmlformats-officedocument.wordprocessingml.template.main+xml' document.save('bar.dotx') I can confirm this works in Python 3.12, as I just tested it a moment ago.
answers question: http://stackoverflow.com/q/51252040
score: 0
type: Answer

http://stackoverflow.com/a/51216777
answers question: http://stackoverflow.com/q/51216767
type: Answer
upvote count: 6
accepted answer of: http://stackoverflow.com/q/51216767
downvote count: 1
has comment: http://stackoverflow.com/comment/89414859
score: 5
type: AcceptedAnswer
has body: You need to call self from within a class method. self.addx() Also the addx parameter on this line shouldn't be there: def addy(self, addx): I think this is what you are going for: class test: def __init__(self, x): self.x = x def addx(self): y = self.x + 10 return y def addy(self): z = self.addx() + 10 return z one = test(1) print(one.addy())

http://stackoverflow.com/q/51321694
has comment: http://stackoverflow.com/comment/89619140
has title: XlsxWriter write_formula() not working always show Zero (0)
has comment: http://stackoverflow.com/comment/89621425
favorite count: 0
has comment: http://stackoverflow.com/comment/89619742
has comment: http://stackoverflow.com/comment/89621300
tagged with: excel-formula
has comment: http://stackoverflow.com/comment/89620956
type: UnansweredQuestion
tagged with: python
upvote count: 4
has body: I have work with xlsxwriter and I try to print simple formula with a print of formula into the sheet import xlsxwriter workbook = xlsxwriter.Workbook('filename1.xlsx') format_val=workbook.add_format() worksheet = workbook.add_worksheet() worksheet.write(0,1,5) worksheet.write(1,1,2) worksheet.write_formula(3,0, '=SUM(B1:B2)') workbook.close() csvf = StringIO(import_file.read().decode()) Here the Image of how to show and when I press = than output is print 7 But output also will be Zero (0). I know that XlsxWriter doesn’t calculate the result of a formula and instead stores the value 0 as the formula result. It then sets a global flag in the XLSX file to say that all formulas and functions should be recalculated when the file is opened. I have tried this. It is working for me but it's not a proper thing when I try with Upper Case is not working: ~ num_formate=format_val.set_num_format('0') worksheet.write_formula(5,1, '=2+1',num_formate,4) But when it's open How to show calculate value?
tagged with: excel
has comment: http://stackoverflow.com/comment/89621833
downvote count: 0
has comment: http://stackoverflow.com/comment/89621038
has comment: http://stackoverflow.com/comment/89621070
has comment: http://stackoverflow.com/comment/89619502
has answer: http://stackoverflow.com/a/66814318
type: Question
has comment: http://stackoverflow.com/comment/89620976
has answer: http://stackoverflow.com/a/77054654
tagged with: python-3.5
score: 4
answer count: 2

http://stackoverflow.com/q/51241952
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/51256504
tagged with: python-3.x
upvote count: 2
has answer: http://stackoverflow.com/a/51242007
tagged with: python
type: AnsweredQuestion
score: 2
possible better answer: http://stackoverflow.com/a/51242007
has answer: http://stackoverflow.com/a/51242103
type: Question
has body: the goal is to read a string from the user and put that string in order of the ASCII code without using lists or the sort() Below is my code answer = input("enter string: ") len_ans = len(answer) new_answer = "" previous = " " leftover ="" while True: for i in range(len_ans): if (ord(previous[0])) &gt;= (ord(answer[i])): new_answer += previous else: leftover += previous print(new_answer) previous = answer[i] new_answer += leftover leftover = "" answer = new_answer if answer == new_answer: print(new_answer) break else: new_answer = ""
has answer: http://stackoverflow.com/a/51256504
has title: print string in the order
answer count: 3

http://stackoverflow.com/q/51172784
has body: I need to present the result of the query from database in csv format using python. from influxdb import InfluxDBClient client = InfluxDBClient(host='192.168.0.110', port=8086) client.get_list_database() client.switch_database('Mlogi_ALL') res= client.query('SELECT * FROM n') print(res) The above line of codes retrieves the query result as: Out[5]: ResultSet({'(u'n', None)': [{u'sid': 3, u'time': u'2018-07-04T04:58:22Z', u'M': u'01081093', u'N': u'01081093', u'iid': u'0', u'V': 4, u'sd': u'0', u'ides': u'0'}, {u'sid': 3, u'time': u'2018-07-04T04:58:22Z', u'M': u'01081093', u'N': u'01081093', u'iid': None, u'V': 4, u'sd': None, u'ides': None} Now I need these results in form of csv, so the next line of code is : res.to_csv("/home/rahul", sep=",", encoding="utf-8") But here I get the following error: Traceback (most recent call last): File "", line 1, in res.to_csv("/home/surya", sep=",", encoding="utf-8") AttributeError: 'ResultSet' object has no attribute 'to_csv' How to rectify this, I have seen few ResultSet errors on stackoverflow but I'm unable to retrieve my results to csv format.
has comment: http://stackoverflow.com/comment/89329419
type: Question
score: 0
has title: 'ResultSet' object has no attribute 'to_csv'
tagged with: influxdb-python
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has comment: http://stackoverflow.com/comment/89342408
answer count: 0
has comment: http://stackoverflow.com/comment/89338979
type: UnansweredQuestion

http://stackoverflow.com/comment/89391815
score: 1
comment on: http://stackoverflow.com/q/51205382
has text: I guess `project` is not the root path in Pycharm, right?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89585654
type: QuestionComment
comment on: http://stackoverflow.com/q/51303762
has text: How does the `LPREngine_Create` signature (*C*) look like? In *Python* you don't specify argument types. Seriously, you should get yourself used to *Python* before diving into *ctypes* (as it's a bit unusual for *Python* programmers).
score: 1
type: Comment

http://stackoverflow.com/comment/89510239
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51265889
has text: What exactly are you trying to do? That library that you are trying to load is already loaded, the python TF framework depends on it.
score: 0

http://stackoverflow.com/a/51211042
has comment: http://stackoverflow.com/comment/89402870
upvote count: 2
answers question: http://stackoverflow.com/q/51210853
has body: import re from collections import Counter mails = [] with open("mails.txt", "r") as f: texte = f.read().split() for i in texte: mails.append(re.search("@[\w.]+", i).group()) mails_value = Counter(mails).most_common() print mails_value
downvote count: 1
type: Answer
score: 1

http://stackoverflow.com/a/51263804
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51263661
answers question: http://stackoverflow.com/q/51263661
type: Answer
score: 0
has body: Simple string If title (which the name suggests), is just a simple string, you do not need to loop (since looping over a string means you iterate over the characters of that string). You can thus write it as a variable somewhere. For example: &lt;div class="container"&gt; {% for images in arrImages %} &lt;hr&gt; &lt;p class="text-justify"&gt{{ title }}&lt;/p&gt; &lt;img class = "col-12 ml-auto col-12 mr-auto" src={{ images }}&gt; {% endfor %} List of strings In case it is a list of strings, and every string corresponds to one image, then you should zip the two lists together to an iterable of tuples that contain the title and the image source. Although there are extensions to do this in the template, in standard Django, you typically do this with a zip(..) in the view: return render(request, 'main.html', {'imageTitles': zip(arrImages, arrTitle)}) In the template, we then need to unpack these 2-tuples: &lt;div class="container"&gt; {% for image, title in imageTitles %} &lt;hr&gt; &lt;p class="text-justify"&gt{{ title }}&lt;/p&gt; &lt;img class = "col-12 ml-auto col-12 mr-auto" src={{ image}}&gt; {% endfor %}

http://stackoverflow.com/a/51234395
has body: To generate a protobuf you need two things: The metagraph, the .meta that you mention, The checkpoint, .ckpt that is generated alongside. Essentially, the .meta file contains the graph definition while the .ckpt contains the weights of the trained model. The protobuf format merges the two in one file. You have to load the meta graph and then the checkpoint as follow: sess = tf.Session() saver = tf.train.import_meta_graph(meta_file) saver.restore(save_path=ckpt_file, sess=sess) Finally, you have to define the output nodes of your graph before exporting it to the protobuf format. The output nodes consist in a list of names of the output layers you would like to be able to retrieve. For instance it could be ['myModel/fc12/BiasAdd']. from tensorflow.python.framework import graph_util output_graph = graph_util.convert_variables_to_constants( sess, sess.graph.as_graph_def(), output_node_names) with tf.gfile.GFile('output.pb', 'wb') as f: f.write(output_graph.SerializeToString())
answers question: http://stackoverflow.com/q/51233023
score: 3
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51233023
type: Answer
upvote count: 3
has comment: http://stackoverflow.com/comment/89450977

http://stackoverflow.com/a/51304759
score: 0
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/89594386
type: Answer
answers question: http://stackoverflow.com/q/51304378
has body: You are launching tasks and getting their results from within another task. This is known to cause deadloack - once your workers pool is exhausted, your first taks is waiting for other tasks that cannot execute for the lack of available workers. The solution is to use callbacks or more complex workflows instead. In your case, you should indeed use a chord, that's the proper solution, so give it another try and if you still have problems with it post about that problem.

http://stackoverflow.com/a/51407643
upvote count: 2
has body: Since I have at most thousands of images, my solution to this problem was to have a separate tfrecord file per image. That way individual images could be shuffled without having to load them into memory first. This drastically reduced the buffering that needed to occur.
score: 2
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51215569
has comment: http://stackoverflow.com/comment/97858781
type: Answer
answers question: http://stackoverflow.com/q/51215569

http://stackoverflow.com/comment/89470508
score: 0
comment on: http://stackoverflow.com/q/51245547
type: Comment
type: QuestionComment
has text: @JohnColeman Also, that "2-line function" would be really helpful in an answer.

http://stackoverflow.com/comment/89788040
type: Comment
has text: I think your update returned another description keyerror or something, but when you switch the Meta class and the __init__ function it works! Thank you for your help!
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51293751

http://stackoverflow.com/comment/89546185
type: AnswerComment
comment on: http://stackoverflow.com/a/51273292
type: Comment
has text: @mkheifetz I just made some changes to my response to address the validation bug that you caught last night! It should return `True` now.
score: 0

http://stackoverflow.com/q/51275653
score: 2
upvote count: 2
type: UnansweredQuestion
has title: Is there a way for a celery task to determine whether the worker is waiting for it to finish so it can shut down?
tagged with: celery
has answer: http://stackoverflow.com/a/78195012
type: Question
answer count: 1
downvote count: 0
has body: We have a few celery tasks that are really long running (and no, we can't segment it out in to subtasks, unfortunately) but are totally safe to kill mid task. This sucks when we need to deploy new code because when we need to bounce all the workers if one of those is in play then it can take half an hour instead of 30 seconds. Is there any way from within a task to find out if it's worker is waiting on it so that it can terminate/restart/whatever so that these tasks that are safe to kill can periodically check that and self terminate?
tagged with: python
favorite count: 0

http://stackoverflow.com/comment/126004828
score: 0
type: AnswerComment
has text: +1. This answer addresses the title (Google led me here). See also https://stackoverflow.com/questions/29672375/histogram-in-matplotlib-time-on-x-axis
comment on: http://stackoverflow.com/a/51321707
type: Comment

http://stackoverflow.com/comment/89378264
type: Comment
score: 3
comment on: http://stackoverflow.com/a/51198155
type: AnswerComment
has text: One possible reason for downvotes is that it’s bare code with no explanation or discussion.

http://stackoverflow.com/a/59710025
upvote count: 5
answers question: http://stackoverflow.com/q/51182226
downvote count: 0
has body: Please makesure not your typo /Application/test.app/Contents/Resources/app.asar/remderer.js:226 Error: python: can't open file 'visitor.py': [Error 2] No such file or directory is remderer.js, but other place is renderer.js, so please makesure is NOT your typo. If is, correct it. Reason Actually electron-builder IS bundled your python file, but due to asar, your python-shell can NOT find your python file, so cause the error. How to fix Solution 1: Easiest but not recommend by official: disable asar How to disable asar change you package.json to: { ... "build": { "appId": "com.example.app", ... "asar": false, then in your renderer.js, which contain python-shell code, maybe like this: import {PythonShell} from 'python-shell'; PythonShell.run('visitor.py', null, function (err) { if (err) throw err; console.log('finished'); }); should working now. internal logic after disable asar, the all related file path is not contain asar, become this: /Application/test.app/Contents/Resources/app/visitor.py /Application/test.app/Contents/Resources/app/renderer.js that is, .app file structure is: |_ test.app |_ Contents |_ Resources |_ app |_ styles.css |_ main.js |_ package.json |_ dist/ |_ node_modules/ |_ renderer.js |_ visitor.py |_ download.py ... Solution 2: keep enable asar, put extra files into unpack: how to asar unpack change you package.json to: { ... "build": { "appId": "com.example.app", ... "asar": true, "asarUnpack": [ "visitor.py", "download.py" "renderer.js" ], the packaged .app file structure is: |_ test.app |_ Contents |_ Resources |_ app.asar # a single compressed binary file |_ app.asar.unpacked # a folder/directory, contain unpacked origin files |_ visitor.py |_ download.py |_ renderer.js your renderer.js, maybe NOT need change, and should working. more details about asarUnpack please refer official doc: Overridable per Platform Options PS: some other asar and related trying, can refer my Chinese post: 【已解决】mac中PyInstaller打包后的二进制文件在electron-builder打包后app中有些无法通过…
type: Answer
has comment: http://stackoverflow.com/comment/117642609
score: 5

http://stackoverflow.com/q/51193654
downvote count: 0
accepted answer: http://stackoverflow.com/a/51193711
type: Question
has answer: http://stackoverflow.com/a/51193711
upvote count: 2
tagged with: pandas
has title: How can I concat and fill at the same time?
answer count: 1
has body: Let's say I have three data frames: from pandas import DataFrame df1 = DataFrame([ [1], [3], [4] ], index=[1, 3, 4], columns=['value1'] ) df2 = DataFrame([ [5], [6], [7], ], index=[5, 6, 7], columns=['value2'] ) df3 = DataFrame([ [5, 9], [6, 10], [7, 11], [8, 12] ], index=[5, 6, 7, 8], columns=['value1', 'value2'] ) Using concat([df1, df2, df3], sort=True, axis=1) will now give me value1 value2 value1 value2 1 1.0 NaN NaN NaN 3 3.0 NaN NaN NaN 4 4.0 NaN NaN NaN 5 NaN 5.0 5.0 9.0 6 NaN 6.0 6.0 10.0 7 NaN 7.0 7.0 11.0 8 NaN NaN 8.0 12.0 Now, how can I get to the result value1 value2 1 1.0 NaN 3 3.0 NaN 4 4.0 NaN 5 5.0 5.0 6 5.0 6.0 7 7.0 7.0 8 8.0 12.0 In other words, for columns of the same name, how can I merge them "to the left"? I'm looking for a generic solution, which can accept any number of multiple columns with the same name (as well as also having column names that only occur once).
favorite count: 0
tagged with: python
type: AnsweredQuestion
score: 2

http://stackoverflow.com/comment/89485188
type: QuestionComment
comment on: http://stackoverflow.com/q/51253056
has text: can you share a [mcve] ?
score: 0
type: Comment

http://stackoverflow.com/comment/89466301
has text: so before you kill your program get stdout and stderr.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51243775

http://stackoverflow.com/a/51228711
has comment: http://stackoverflow.com/comment/89437330
score: 2
has comment: http://stackoverflow.com/comment/89437334
has comment: http://stackoverflow.com/comment/89437373
downvote count: 0
upvote count: 2
has body: As far as I know pickling is when converting some object in memory to a byte stream and I don't think I am doing anything like that over here. Well, you are doing that. You can't pass Python values directly between processes. Even the simplest variable holds a pointer to a structure somewhere in the process's memory space, and just copying that pointer to a different process would give you a segfault or garbage, depending on whether the same memory space in the other process is unmapped or mapped to something completely different. Something as complex as a generator—which is basically a live stack frame—would be even more impossible. The way multiprocessing solves that is to transparently pickle everything you give it to pass. Functions, and their arguments, and their return values, all need to be pickled. If you want to know how it work under the covers: a Pool essentially works by having a Queue that the parent puts tasks on—where the tasks are basically (func, args) pairs—and the children get tasks off. And a Queue essentially works by calling pickle.dumps(value) and then writing the result to a pipe or other inter-process-communication mechanism.
type: Answer
has comment: http://stackoverflow.com/comment/89437246
has comment: http://stackoverflow.com/comment/89437335
has comment: http://stackoverflow.com/comment/89437343
answers question: http://stackoverflow.com/q/51228679
has comment: http://stackoverflow.com/comment/89437274
has comment: http://stackoverflow.com/comment/89437303

http://stackoverflow.com/a/51319254
accepted answer of: http://stackoverflow.com/q/51312285
has comment: http://stackoverflow.com/comment/89630182
answers question: http://stackoverflow.com/q/51312285
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89630561
has comment: http://stackoverflow.com/comment/89641228
has body: We can use .find to get the code word, if it exists, and then use the dictionary to map the code word to its code number. We can use the dictionary .get method to return the null code for missing or unknown code words. This version returns None if it encounters bad data: a name that doesn't contain '-', or a name that doesn't have either 8 or 5 letters before the '-'. env_code = { 'ICS': '1', 'IGW': '2', 'RTL': '3', 'TDZ': '4', } null_code = '9' def get_env_code(name): idx = name.find('-') if idx == 8: # code may be valid code = name[idx-3:idx] elif idx == 5: # code is missing code = '' else: # Bad name return None return env_code.get(code, null_code) # test data = [ 'AABBBICS-CCCDDD001', 'AABBBIGW-CCCDDD001', 'AABBBRTL-CCCDDD001', 'AABBBTDZ-CCCDDD001', 'USNYCRTL-LANDCE001', 'AABBBXYZ-CCCDDD001', 'AABBB-CCCDDD001', 'BADDATA', ] for s in data: print(s, get_env_code(s)) output AABBBICS-CCCDDD001 1 AABBBIGW-CCCDDD001 2 AABBBRTL-CCCDDD001 3 AABBBTDZ-CCCDDD001 4 USNYCRTL-LANDCE001 3 AABBBXYZ-CCCDDD001 9 AABBB-CCCDDD001 9 BADDATA None Here's a simpler version that returns the null code instead of None for bad data. def get_env_code(name): idx = name.find('-') code = name[idx-3:idx] if idx == 8 else '' return env_code.get(code, null_code)
has comment: http://stackoverflow.com/comment/89699145
type: Answer
has comment: http://stackoverflow.com/comment/89856597
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/89637137
has comment: http://stackoverflow.com/comment/89863271
has comment: http://stackoverflow.com/comment/89862256
has comment: http://stackoverflow.com/comment/89634612

http://stackoverflow.com/comment/89615466
has text: You should ask a question with your needs then. No one will be able to guess your future needs
comment on: http://stackoverflow.com/q/51319581
type: Comment
type: QuestionComment
score: 2

http://stackoverflow.com/q/51270794
tagged with: facebook-marketing-api
tagged with: facebook
tagged with: python
has comment: http://stackoverflow.com/comment/89524630
tagged with: curl
score: 0
linked to: http://stackoverflow.com/q/51194773
has comment: http://stackoverflow.com/comment/89526798
duplicate of: http://stackoverflow.com/q/51194773
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89535527
has body: i want to know how to get the size of audience in facebook graph api. for example: how many people live in us, age between 20 and 30, and are interested in baseball. i am having problems using the graph api, and python's request class. i have this code for example import requests data2 = [ ('type', 'adinterest'), ('q', 'baseball'), ('access_token', 'access code'),('limit','1000') ] response = requests.get('https://graph.facebook.com/v2.11/search', params=data2) r=response.json()
answer count: 0
tagged with: facebook-graph-api
has title: how the get the audience size in facebook using graph api
type: Question

http://stackoverflow.com/comment/89366599
has text: Shouldn't it be `mymodule.transfer`? I mean, `mocker.patch('mymodule.transfer.Popen')` etc.
comment on: http://stackoverflow.com/q/51190025
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/comment/89453859
type: Comment
comment on: http://stackoverflow.com/a/51237420
has text: this is easy and can u post the full code
score: 0
type: AnswerComment

http://stackoverflow.com/comment/89362122
has text: @NielsHoogeveen - Can you add data sample? Missing values are `NaN`s?
comment on: http://stackoverflow.com/a/51190119
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/89614958
score: 0
type: AnswerComment
has text: Great answer, however do not oppose `class` and `instance` because classes are instance of Type
type: Comment
comment on: http://stackoverflow.com/a/51319372

http://stackoverflow.com/comment/89453294
comment on: http://stackoverflow.com/a/51229026
type: AnswerComment
score: 0
has text: The error doesn't have to do if the array exists, it has to do with checking the truth value of a NumPy array. `a = np.array([1, 2, 3])` followed by `if a: print('hi')` throws the same error.
type: Comment

http://stackoverflow.com/q/51239072
favorite count: 0
has comment: http://stackoverflow.com/comment/89461997
has comment: http://stackoverflow.com/comment/89460728
tagged with: python
has answer: http://stackoverflow.com/a/51241744
type: AnsweredQuestion
score: 3
downvote count: 0
tagged with: http://stackoverflow.com/tag/json
tagged with: jsonschema
type: Question
has title: Is my implementation of exclusiveMinimum property correct?
has comment: http://stackoverflow.com/comment/89461846
upvote count: 3
has comment: http://stackoverflow.com/comment/89460787
answer count: 1
accepted answer: http://stackoverflow.com/a/51241744
has body: I am using JsonSchema 2.6.0 for the validation of form data for my python program. I am trying to implement exclusiveMinimum but when I post to the form it accepts 0 as a valid value, but it shouldn't. from jsonschema import Draft3Validator orderValidationSchema = { "$schema": "http://json-schema.org/draft-04/schema#", "type": "object", "properties": { "total_amount": { "$ref": "#/definitions/floatRef", "required": "true", "exclusiveMinimum": 0 }, "payable_amount": { "$ref": "#/definitions/floatRef", "required": "true", "exclusiveMinimum": 0 }, }, "definitions": { "floatRef": { "type": "number", }, } } After going through few git issues and other links I tried it in the way shown below but still it didn't work. from jsonschema import Draft3Validator orderValidationSchema = { "$schema": "http://json-schema.org/draft-04/schema#", "type": "object", "properties": { "total_amount": { "$ref": "#/definitions/floatRef", "required": "true", "minimum": 0, "exclusiveMinimum": "true" }, "payable_amount": { "$ref": "#/definitions/floatRef", "required": "true", "minimum": 0, "exclusiveMinimum": "true" }, }, "definitions": { "floatRef": { "type": "number", }, } } Please do let me know if I am making any mistakes. I am using Draft3Validator just in case there is any issue active related to it. Below is the json that is passed to this schema. { "total_amount" : 100000, "payable_amount" : 10000 }

http://stackoverflow.com/comment/89374114
score: 0
type: Comment
type: QuestionComment
has text: In this particular case, that may not work. Due to the nature of their business models, financial metrics should differ by industry. Removing the industry classification would create a lower tier bucket that comingles different industries where the flag was were deemed less sensitive (flags would be 0 on average), resulting in less predictive power.
comment on: http://stackoverflow.com/q/51195939

http://stackoverflow.com/comment/89610984
type: AnswerComment
has text: Did you use try and except for nom2 check whether the value is present or not, like you did for pbm....... And i don't understand the logic here, you need to remove the vol variable if nom2 is None?
type: Comment
score: 0
comment on: http://stackoverflow.com/a/51302419

http://stackoverflow.com/q/51270756
type: Question
has answer: http://stackoverflow.com/a/51270881
answer count: 6
tagged with: pandas
has answer: http://stackoverflow.com/a/51271088
has answer: http://stackoverflow.com/a/51270781
favorite count: 0
has answer: http://stackoverflow.com/a/51270945
upvote count: 8
tagged with: python
has body: I'm sure there must e an easy way to do this: I want to create a list which will eventually become column names for a DataFrame. There will be 13 columns, each representing a period in time, called "Period n", where n is the period number. I think there's probably a way to build this list via loop, but I will show what I tried to do: col_no = list(range(1,14)) col_name = ['Period' for n in range (1,14)] col_list = col_name + col_no print(col_list) ['Period', 'Period', 'Period', 'Period', 'Period', 'Period', 'Period', 'Period', 'Period', 'Period', 'Period', 'Period', 'Period', 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] Then I tried: col_list = list(zip(col_name + col_no)) print(col_list) [('Period',), ('Period',), ('Period',), ('Period',), ('Period',), ('Period',), ('Period',), ('Period',), ('Period',), ('Period',), ('Period',), ('Period',), ('Period',), (1,), (2,), (3,), (4,), (5,), (6,), (7,), (8,), (9,), (10,), (11,), (12,), (13,)] Basically, I just wanted an easily generated list that reads "Period 1", "Period 2", etc. I'm pretty new to Python, and pretty stumped.Thanks in advance
has answer: http://stackoverflow.com/a/51270816
has answer: http://stackoverflow.com/a/51270994
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51270781
score: 7
has title: Create a list of strings with consecutive numbers appended
possible better answer: http://stackoverflow.com/a/51270994
downvote count: 1

string
tags question: http://stackoverflow.com/q/51283194
tags question: http://stackoverflow.com/q/51175606
tags question: http://stackoverflow.com/q/51245946
tags question: http://stackoverflow.com/q/51178251
tags question: http://stackoverflow.com/q/51289175
tags question: http://stackoverflow.com/q/51216402
tags question: http://stackoverflow.com/q/51295864
tags question: http://stackoverflow.com/q/51225282
tags question: http://stackoverflow.com/q/51301150
tags question: http://stackoverflow.com/q/51214231
tags question: http://stackoverflow.com/q/51241575
tags question: http://stackoverflow.com/q/51193842
tags question: http://stackoverflow.com/q/51220010
tags question: http://stackoverflow.com/q/51274096
tags question: http://stackoverflow.com/q/51296199
tags question: http://stackoverflow.com/q/51187311
tags question: http://stackoverflow.com/q/51290134
tags question: http://stackoverflow.com/q/51223511
tags question: http://stackoverflow.com/q/51214358
tags question: http://stackoverflow.com/q/51321769
tags question: http://stackoverflow.com/q/51259521
tags question: http://stackoverflow.com/q/51206232
tags question: http://stackoverflow.com/q/51269960
tags question: http://stackoverflow.com/q/51178494
tags question: http://stackoverflow.com/q/51320667
tags question: http://stackoverflow.com/q/51229187
tags question: http://stackoverflow.com/q/51312000
tags question: http://stackoverflow.com/q/51313055
tags question: http://stackoverflow.com/q/51170763
tags question: http://stackoverflow.com/q/51234496
tags question: http://stackoverflow.com/q/51167575
tags question: http://stackoverflow.com/q/51319210
tags question: http://stackoverflow.com/q/51253012
tags question: http://stackoverflow.com/q/51214404
tags question: http://stackoverflow.com/q/51314424
tags question: http://stackoverflow.com/q/51256032
tags question: http://stackoverflow.com/q/51174983
tags question: http://stackoverflow.com/q/51306393
tags question: http://stackoverflow.com/q/51292163
tag name: string
tags question: http://stackoverflow.com/q/51315809
tags question: http://stackoverflow.com/q/51233622
tags question: http://stackoverflow.com/q/51221526
tags question: http://stackoverflow.com/q/51292296
tags question: http://stackoverflow.com/q/51254282
tags question: http://stackoverflow.com/q/51243702
tags question: http://stackoverflow.com/q/51213110
tags question: http://stackoverflow.com/q/51317680
tags question: http://stackoverflow.com/q/51230093
tags question: http://stackoverflow.com/q/51243464
tags question: http://stackoverflow.com/q/51172657
tags question: http://stackoverflow.com/q/51178925
tags question: http://stackoverflow.com/q/51297805
type: Tag
tags question: http://stackoverflow.com/q/51303110
tags question: http://stackoverflow.com/q/51176980
tags question: http://stackoverflow.com/q/51302922
tags question: http://stackoverflow.com/q/51252002
tags question: http://stackoverflow.com/q/51236069
tags question: http://stackoverflow.com/q/51193920
tags question: http://stackoverflow.com/q/51195001
tags question: http://stackoverflow.com/q/51168744
tags question: http://stackoverflow.com/q/51291797
tags question: http://stackoverflow.com/q/51219088
tags question: http://stackoverflow.com/q/51219752
tags question: http://stackoverflow.com/q/51259374
tags question: http://stackoverflow.com/q/51230252
tags question: http://stackoverflow.com/q/51209186
tags question: http://stackoverflow.com/q/51220389
tags question: http://stackoverflow.com/q/51197175
tags question: http://stackoverflow.com/q/51172881
tags question: http://stackoverflow.com/q/51310072
tags question: http://stackoverflow.com/q/51179822
tags question: http://stackoverflow.com/q/51321062
tags question: http://stackoverflow.com/q/51213300
tags question: http://stackoverflow.com/q/51199256
tags question: http://stackoverflow.com/q/51272814
tags question: http://stackoverflow.com/q/51287972
tags question: http://stackoverflow.com/q/51241829
tags question: http://stackoverflow.com/q/51263420

http://stackoverflow.com/q/51170561
downvote count: 0
has body: I am using numpy. Now I have a 3D array: ary = array([[[1, 2, 3], [4, 5, 6], [7, 8, 9], [1, 2, 3], [4, 5, 6], [7, 8, 9]]]) I want to find the 2D coordinates of [4, 5, 6] in it. The expected result is: [0,1], [0,4]. But if I use where, the result is: np.where(s==[4,5,6]) (array([0, 0, 0, 0, 0, 0]), array([1, 1, 1, 4, 4, 4]), array([0, 1, 2, 0, 1, 2])) So, What can I do to get the results I want like [0,1], [0,4]?
accepted answer: http://stackoverflow.com/a/51171365
has title: Numpy how find the index of the third dimension from a three-dimensional array (eg x, y)
favorite count: 0
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/89323779
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/51171365
type: Question
tagged with: numpy
tagged with: arrays
answer count: 1

http://stackoverflow.com/comment/89340454
has text: Do you want to treat 'yes', 'yeah', etc. as 'y'? If so, you should look only at the first letter of the input (which is `qr[0]`).
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51178925

http://stackoverflow.com/comment/89501191
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51254736
has text: Making a detour to built-in Python objects such as `dict` and then returning back to `ast` via `ast.parse` feels a bit awkward as opposed to just staying within `ast`. What about returning `return ast.Dict(node.args[0].elts[0].elts[:1], node.args[0].elts[0].elts[1:])` after a node has been identified as `OrderedDict` node? That way everything stays within `ast`. Also you could replace the bunch of `assert`ions within `try / except` with a few `if` conditions, i.m.o. that'd make the code a lot cleaner.

http://stackoverflow.com/q/51292333
has body: My current setup.py writes the git commit hash in a file which the module can access after it has been installed. However, I would like to disable that when I am developing the module since the setup.py file will not be triggered twice and the hash would be inaccurate. This brings us to the question: Is there a way to tell from setup.py whether the module is being installed in editable mode? i.e., pip install -e . I found a similar question here, but even the "hack" will not work in my case since the module will be installed directly with git, and the .git directory will exist even for normal installs during installation.
upvote count: 6
has answer: http://stackoverflow.com/a/51294311
tagged with: setup.py
score: 6
tagged with: python
has title: How to tell from setup.py if the module is being installed in editable mode
tagged with: git
type: AnsweredQuestion
tagged with: setuptools
accepted answer: http://stackoverflow.com/a/51294311
type: Question
linked to: http://stackoverflow.com/q/43348746
downvote count: 0
answer count: 1
favorite count: 0

http://stackoverflow.com/q/51245909
has body: Array_temp = array_1 tarray_1 print(Array_temp) [list([1.0, 3.0, 7.0, 1.0, 3.0, 7.0]) list( [2.0, 4.0, 6.0, 8.0, 2.0, 4.0, 6.0, 8.0])] Array_sub = array_1 array_1 print(Array_mul) TypeError Traceback (most recent call last) &lt;i python-input-11-c5dc21502aaf&gt; in &lt;module() --&gt; 1 Array_sub = array_1-array_1 2 print (Array_mul) TypeError: unsupported operand type(s) for -: 'list' and 'list' array_di = array_1 *array_1 print (array_di) TypeError Traceback (most recent call last) &lt;i python-input-13-09997f8001 f6&gt; in &lt;module () --&gt;1 array_di = array_1*array_1 2 print (array_di) TypeError: can't multiply sequence by non-int of type 'list' Adding arrays together succeeded, but failed to subtract or multiply arrays Tell me what's wrong with my code
has answer: http://stackoverflow.com/a/51249715
has comment: http://stackoverflow.com/comment/89470813
type: Question
tagged with: numpy
answer count: 1
tagged with: arrays
has comment: http://stackoverflow.com/comment/89474235
has title: numpy python code array
has comment: http://stackoverflow.com/comment/89470377
favorite count: 0
downvote count: 3
tagged with: python
upvote count: 0
type: UnansweredQuestion
score: -3

http://stackoverflow.com/comment/89399115
comment on: http://stackoverflow.com/q/51209233
has text: Add a `\b` after the lookbehind.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/95510002
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51232871
has text: I had the same problem, could never solve it. I ended up just using the subprocess lib, as described here http://machakux.appspot.com/blog/44003/making_speech_with_python

http://stackoverflow.com/q/51268204
has comment: http://stackoverflow.com/comment/89534641
type: Question
has comment: http://stackoverflow.com/comment/89514685
has comment: http://stackoverflow.com/comment/89514705
tagged with: resize
has comment: http://stackoverflow.com/comment/89515390
has title: What can cause unexpected tkinter widget resizing after frame resize?
has body: One thing that can do it is assigning weights to non existent columns and rows. Maybe users know of others? I recently had to track down this problem, and place it here in the hope it will be useful to others. After resizing your window frame, tkinter will not resize widgets if you have assigned a non zero weight to non existent columns. I ran into this situation where I had a dynamic UI which hid a panel, and replaced it with some buttons. For these buttons to resize properly, I did a columnconfigure and assigned weights of 1 to these extra columns. When the UI was restored, these buttons were removed, and we went back to one column. However the weights for these non existent columns still influenced the resizing as seen in the attached figure. To solve the problem I reset the weights of these extra columns that I had set to 1 back to zero (even though these columns did not exist in the UI any more). Minimal code to illustrate the problem is shown below: The problem line is labelled # @@@@@@@ this is a problem import tkinter as tk class frame_resize: def setupGUI(self): self._root = tk.Tk() self._font = 'helvetica 16' self._mainFrame = tk.Frame(self._root, bg='pink') self._label = tk.Label(self._mainFrame, font=self._font, bg='sky blue', text='this is some text') self._mainButton = tk.Button(self._mainFrame, text='Press here', font=self._font) # give weights so that widgets expand when outer frame expands tk.Grid.rowconfigure(self._root, 0, weight=1) tk.Grid.columnconfigure(self._root, 0, weight=1) tk.Grid.rowconfigure(self._mainFrame, 0, weight=1) tk.Grid.columnconfigure(self._mainFrame, 0, weight=1) # @@@@@@@ this is a problem, if we have no column 1 tk.Grid.columnconfigure(self._mainFrame, 1, weight=1) #pop elemnts into grid self._mainFrame.grid(column=0, row=0, sticky='nsew') self._label.grid(column=0, row=0, sticky='nsew') self._mainButton.grid(column=0, row=1, sticky='nsew') self._root.mainloop() fr = frame_resize() fr.setupGUI()
tagged with: tkinter
answer count: 0
type: UnansweredQuestion
tagged with: python
tagged with: grid
has comment: http://stackoverflow.com/comment/89516106
score: 0

http://stackoverflow.com/a/51250113
upvote count: 1
has body: Can you provide more details on the layers that you defined ? Anyway, for the concatenate layer, you must have at least one dimension matching between your both tensors on the same axis. To be simple, you can easily see that 'None' doesn't match with 1 and 16 doesn't match with 64. In addition to that, trying to reshape as you are doing is wrong. Initially h_t is of shape (1, 64) and with : h_t = tf.reshape(h_t, shape=tf.TensorShape([None, h_t.get_shape()[-1].value])) you are trying to reshape it into a (None, 64) tensor which is conceptually wrong as None means that it can be any integer and usually represents your batch size. Same problem while trying to do : x_t = tf.reshape(x_t, shape=tf.TensorShape([1, x_t.get_shape()[-1].value])) where your initial shape is (None, 16) while you are trying to reshape it into a fixed shape : (1, 16). I think that you should try to make your h_t layer returning a tensor with shape (None, 1, 16) or (None, 16) so that you can either flatten and then concatenate for the first case and just use concatenate for the second.
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51248889
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51248889
type: Answer
score: 1

http://stackoverflow.com/q/51253563
type: Question
has answer: http://stackoverflow.com/a/51253603
has title: Python Exact Match- Absolute exact match
tagged with: python
score: 0
answer count: 1
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89486503
has comment: http://stackoverflow.com/comment/89486138
has body: Based on the code I have I am trying to find an exact match to any of the job positions listed in the input. INPUT this is str contains specific MATCH dfp1[dfp1.index.str.match('Teacher|Dentist|General Manager|District Manager|Bus Driver|Team Lead|Dancer')] Output is: Teacher Teacher, Middle Teacher, High Dentist, Sanford Dentist General Manager General Manager, Dollar Tree Team Lead Dancer, 10th Dancer Dancer, Previous I do not want anything extra other than the exact job position I put in the input. I want to specifically see only Teacher or Dentist or General Manager or District Manager or Bus Driver or Team Lead or Dancer. I am not sure what my code is missing for it to display the job titles and no others.

http://stackoverflow.com/a/51219002
downvote count: 0
score: 1
has body: If you want to filter data you must use QSortFilterProxyModel and overwrite the filterAcceptsRow() method, on the other hand, creating the model every time is not elegant, you could only hide the column with setColumnHidden() methos of QTableView. import sys import os sys.path.append(os.environ.get('PS_SITEPACKAGES')) from Qt import QtGui, QtWidgets, QtCore from functools import partial class FilterProxy(QtCore.QSortFilterProxyModel): def __init__(self, *args, **kwargs): super(FilterProxy, self).__init__(*args, **kwargs) self.filters_colums = set() self.mText = "" def setText(self, text): self.mText = text self.invalidateFilter() def appendColumn(self, name): self.filters_colums.add(name.lower()) self.invalidateFilter() def removeColumn(self, name): self.filters_colums.discard(name.lower()) self.invalidateFilter() def filterAcceptsRow(self, source_row, source_parent): if self.mText: for i in range(self.sourceModel().columnCount()): header = self.sourceModel().headerData(i, QtCore.Qt.Horizontal) text = self.sourceModel().index(source_row, i).data() if header in self.filters_colums and self.mText in text.lower(): return True return False return True class QDictTableView(QtWidgets.QWidget): def __init__(self, *args, **kwargs): super(QDictTableView, self).__init__(*args, **kwargs) self.resize(400,300) # controls self.ui_search_input = QtWidgets.QLineEdit() self.ui_search_input.setPlaceholderText('Search...') self.ui_item_table = QtWidgets.QTableView() self.ui_item_table.setEditTriggers(QtWidgets.QAbstractItemView.NoEditTriggers) self.ui_item_table.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows) self.ui_item_table.verticalHeader().hide() lay_filters = QtWidgets.QHBoxLayout() lay_main = QtWidgets.QVBoxLayout(self) lay_main.setAlignment(QtCore.Qt.AlignTop) lay_main.addWidget(self.ui_search_input) lay_main.addLayout(lay_filters) lay_main.addWidget(self.ui_item_table) model = self.populate_table() self.proxy = FilterProxy() self.proxy.setSourceModel(model) self.…
upvote count: 1
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/51212916
accepted answer of: http://stackoverflow.com/q/51212916

http://stackoverflow.com/comment/89507918
type: AnswerComment
has text: Checkout my updated answer and let me know the status
type: Comment
comment on: http://stackoverflow.com/a/51263866
score: 0

http://stackoverflow.com/q/51220853
downvote count: 0
favorite count: 0
has title: Can I get Django model objects as singletons?
has comment: http://stackoverflow.com/comment/89422642
has body: When I call Models.get() for the same id it returns different Python objects: print(Book.objects.get(id=1) is Book.objects.get(id=1)) &gt;&gt;&gt; False I wonder if it is possible to change this behavior, maybe with some custom Model Manager. It could internally store some registry for all retrieved objects and override get_queryset() to make it use objects from this registry if they have already been retrieved. Why do it can be helpful I have a model ServerCredentials which stores login and password. I have multiple consumers that connect using the same credentials. Since only one connection to server is allowed, it would be convenient to store transient connection information (e.g. auth token) as a field of ServerCredentials object, but not in database. If model objects could be singletons, consumers could easily share auth tokens just by using a field of ServerCredentials. Without it, I have to make some registry manually, but I fell that it should be done on ModelManager's side. Is it a possible to cache objects in a registry on ModelManager's side? Is it a good idea? Are there implementations for that? Many thanks in advance!
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51221023
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/51221040
score: 1
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/89422459
tagged with: django-models
answer count: 2

http://stackoverflow.com/comment/133232334
type: AnswerComment
score: 0
type: Comment
has text: I finally found why tensorflow-gpu doesn't work in my case: it is related with the drivers. -If anyone is looking for system requirements for tensorflow-gpu that can be found in the following link: https://www.tensorflow.org/install/pip "....The following NVIDIA® software is required for GPU support only: NVIDIA® GPU Drivers version 450.80.02 or later... ." -Also using the following link: https://www.nvidia.com/download/index.aspx?lang=en-us we see the latest driver for geforce gtx 500 series is 391
comment on: http://stackoverflow.com/a/75513076

http://stackoverflow.com/comment/89607797
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51315320
has text: It wasn't meant to be a CSV as you have mentioned, it was a plain .txt file. its a long story as to why I had to convert it into a CSV.
type: Comment

http://stackoverflow.com/q/51253048
type: AnsweredQuestion
has body: I'm trying to send a call to sed but it seems like it is not processing the variables it looks correct when I print it but it not correct in the call #!/usr/bin/python -tt import json from pprint import pprint from subprocess import call with open('admin_list.json') as data_file: admins = json.load(data_file) #pprint(data[0]["key"]) for admin in admins: #print(admin["name"]) #print (" sudo sed, 1 a ${"+admin['key']+"} /home/"+admin['name']+"/.ssh/authorized_keys") call(["sudo sed", "1 a ${"+admin['key']+"} /home/"+admin['name']+"/.ssh/authorized_keys"]) OSError: [Errno 2] No such file or directory" I've updated my code I do not get errors but the file still is not updated #!/usr/bin/python -tt import json import os from pprint import pprint from subprocess import call with open('admin_list.json') as data_file: admins = json.load(data_file) #pprint(data[0]["key"]) for admin in admins: call(["sudo","sed", "1 a "+admin['key']+"","/home/"+admin['name']+"/.ssh/authorized_keys"]) call(['cat','/home/'+admin["name"]+'/.ssh/authorized_keys'])
has comment: http://stackoverflow.com/comment/89488731
type: Question
has comment: http://stackoverflow.com/comment/89485903
has title: How do I pass python variables to subprocess call to sed?
score: 0
tagged with: bash
tagged with: sed
answer count: 1
has comment: http://stackoverflow.com/comment/89485306
has answer: http://stackoverflow.com/a/51253193
accepted answer: http://stackoverflow.com/a/51253193
tagged with: python

http://stackoverflow.com/q/51169129
has answer: http://stackoverflow.com/a/51169318
tagged with: python
tagged with: django
has body: I have a listview like this: class IncidentListView(generic.ListView): model = Incident paginate_by = 3 def get_queryset(self,request): order_by = request.GET.get('order_by', 'defaultOrderField') return model.objects.all().order_by(order_by) When I go to the url, I get this error: get_queryset() missing 1 required positional argument: 'request' What am I doing wrong? I want to make it so you can click a sorting link that creates a new listview, but unsure how to approach. For reference, I followed the recommendation here
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/51169318
type: Question
answer count: 2
has title: Get_queryset() missing 1 required positional argument: 'request'
linked to: http://stackoverflow.com/q/47509515
has answer: http://stackoverflow.com/a/51169171
accepted answer: http://stackoverflow.com/a/51169171
score: 0

http://stackoverflow.com/q/51179328
type: Question
downvote count: 2
has answer: http://stackoverflow.com/a/51179371
upvote count: 1
accepted answer: http://stackoverflow.com/a/51179371
duplicate of: http://stackoverflow.com/q/7427101
answer count: 1
tagged with: python
has body: I'm really new to python (literally started today, 2 hours ago)... I know php and i want to know if theres a method to introduce variables in to a .py file... For example in php you have $_GET variable... I want something like this... python myprogram.py --num 1234567890 To be executed inside... search_box = driver.find_element_by_name('txtPhone') search_box.send_keys('$num') search_box = driver.find_element_by_name('txtPhoneC') search_box.send_keys('$num') link = driver.find_element_by_xpath("//select[@name='ddlProducts']/option[text()='10']").click() How can i do that? (not english native speaker) NOTE: I dont know if it matters, but im using selenium with chromedriver to make a "bot"
favorite count: 0
has comment: http://stackoverflow.com/comment/89341133
linked to: http://stackoverflow.com/q/17544307
linked to: http://stackoverflow.com/q/7427101
type: AnsweredQuestion
score: -1
has title: something like $_GET in python...?

http://stackoverflow.com/comment/89513756
type: Comment
has text: That's a different question/problem, so it should go in a new different SO post.
comment on: http://stackoverflow.com/a/51250459
score: 0
type: AnswerComment

http://stackoverflow.com/q/51256302
tagged with: amazon-web-services
favorite count: 0
has comment: http://stackoverflow.com/comment/96562331
has answer: http://stackoverflow.com/a/51585917
upvote count: 6
has comment: http://stackoverflow.com/comment/139950111
has comment: http://stackoverflow.com/comment/93530330
type: UnansweredQuestion
score: 6
tagged with: python
linked to: http://stackoverflow.com/q/46751551
has answer: http://stackoverflow.com/a/70610799
has body: During the user migration I want to return "Incorrect username or password." as error message instead of "User does not exist" Have been searching on google for a while, cannot find out how to replicate the following JS example in this documentation https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-migrate-user.html exports.handler = (event, context, callback) =&gt; { var user; if ( event.triggerSource == "UserMigration_Authentication" ) { // authenticate the user with your existing user directory service user = authenticateUser(event.userName, event.request.password); if ( user ) { event.response.userAttributes = { "email": user.emailAddress, "email_verified": "true" }; event.response.finalUserStatus = "CONFIRMED"; event.response.messageAction = "SUPPRESS"; context.succeed(event); } else { // Return error to Amazon Cognito callback("Bad password"); } } else if ( event.triggerSource == "UserMigration_ForgotPassword" ) { // Lookup the user in your existing user directory service user = lookupUser(event.userName); if ( user ) { event.response.userAttributes = { "email": user.emailAddress, // required to enable password-reset code to be sent to user "email_verified": "true" }; event.response.messageAction = "SUPPRESS"; context.succeed(event); } else { // Return error to Amazon Cognito callback("Bad password"); } } else { // Return error to Amazon Cognito callback("Bad triggerSource " + event.triggerSource); } }; It uses callback('message') in nodejs but I cannot find out how to do that in Python. Stumbled on to this question I can&#39;t find callback parameter in python lambda handler Tried returning message string, but get "Exception during user migration"
has comment: http://stackoverflow.com/comment/110989414
has comment: http://stackoverflow.com/comment/96538042
type: Question
has comment: http://stackoverflow.com/comment/110992786
answer count: 2
downvote count: 0
has title: AWS Cognito user migration lambda in python, how to return custom error message

http://stackoverflow.com/q/51255352
upvote count: 3
type: Question
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/67102903
has title: Why does os.path.exists() stop windows named pipes from connecting?
has comment: http://stackoverflow.com/comment/89491386
has comment: http://stackoverflow.com/comment/89490037
has comment: http://stackoverflow.com/comment/89494214
has comment: http://stackoverflow.com/comment/89489721
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/67102903
favorite count: 0
tagged with: named-pipes
tagged with: python-3.7
tagged with: windows
tagged with: pywin32
tagged with: python
has body: It seems that a successful test of the existence of a windows named pipe by using os.path.exists() prevents the pipe from working. Why would this be? Here is successfully working windows named-pipe code: import time import multiprocessing as mp import win32pipe, win32file PIPENAME = r'\\.\pipe\Foo' def producer(pipe_name: str): print('producer') # if not os.path.exists(pipe_name): # print(f'No pipe {pipe_name}') # return pipe = win32file.CreateFile(pipe_name, win32file.GENERIC_READ | win32file.GENERIC_WRITE, # dwDesiredAccess 0, # dwShareMode None, # lpSecurityAttributes win32file.OPEN_EXISTING, # dwCreationDisposition 0, # dwFlagsAndAttributes None ) win32pipe.SetNamedPipeHandleState(pipe, win32pipe.PIPE_READMODE_MESSAGE, None, None) win32file.WriteFile(pipe, b'foobar') def receiver(pipe_name: str): print('receiver') pipe = win32pipe.CreateNamedPipe(pipe_name, win32pipe.PIPE_ACCESS_DUPLEX, win32pipe.PIPE_TYPE_MESSAGE | win32pipe.PIPE_READMODE_MESSAGE | win32pipe.PIPE_WAIT, 1, # nMaxInstances 65536, # nOutBufferSize 65536, # nInBufferSize 0, # 50ms timeout (the default) None) # securityAttributes win32pipe.ConnectNamedPipe(pipe) msg = win32file.ReadFile(pipe, 65536) print(f'msg: {msg}') if __name__ == '__main__': recv_p = mp.Process(target=receiver, args=(PIPENAME,)) prod_p = mp.Process(target=producer, args=(PIPENAME,)) recv_p.start() time.sleep(0.1) prod_p.start() prod_p.join() recv_p.join() This works as expected, with the receiver printing the received message. But if the three commented-out lines in the producer are uncommented, the os.path.exists(pipe_name) call somehow breaks the pipe so the output becomes: receiver producer Process Process-2: Process Process-1: Traceback (most recent call last): File "C:\Users\redacted\AppData\Local\Programs\Python\Python37\lib\multiprocessing\process.py", line 297, in _bootstrap self.run() File "C:\Users\redacted\AppData\Local\Programs\Python\Python37\lib\multiprocessing\process.py", line 99, in run self._target(*self._args…
has comment: http://stackoverflow.com/comment/89493359
has comment: http://stackoverflow.com/comment/89493331

http://stackoverflow.com/q/51298758
answer count: 3
has comment: http://stackoverflow.com/comment/89604915
downvote count: 0
favorite count: 0
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/51299593
tagged with: python
has body: Imagine the following simple example: def doNothing(): sleep(0.5) barVar.set(10) sleep(0.5) barVar.set(20) sleep(0.5) barVar.set(30) mainWindow = Tk() barVar = DoubleVar() barVar.set(0) bar = Progressbar(mainWindow, length=200, style='black.Horizontal.TProgressbar', variable=barVar, mode='determinate') bar.grid(row=1, column=0) button= Button(mainWindow, text='Click', command=doNothing) button.grid(row=0, column=0) mainWindow.mainloop() What I get when I run this, the progressbar is already at 30% when clicking the button, no progress in front of me. Like attached: What I need: I can see the progress in front of me (not hanging then suddenly 30%) Update: I upadted the code according to @Bernhard answer, but still I can not see the progress in front of me. Just a sudden jump of 30% after waiting 1.5 sec Seocnd Update: I'm only using sleep here as a simulation for a process that takes time, like connecting over ssh and grabing some info.
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/51314379
tagged with: tkinter
has title: Tkinter: Updating progressbar when a function is called
has answer: http://stackoverflow.com/a/51314379
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/51298799
type: Question
has answer: http://stackoverflow.com/a/51299593
tagged with: python-3.6

http://stackoverflow.com/comment/89365785
score: 0
type: Comment
type: QuestionComment
has text: How random are the numbers supposed to be? E.g., with your appraoch, for large `n` each count should end up pretty much exactly at the probability for that position, whereas "true" random numbers should allow wider variation, as long as the sum remains the same.
comment on: http://stackoverflow.com/q/51191735

http://stackoverflow.com/q/51256285
accepted answer: http://stackoverflow.com/a/51256425
type: Question
tagged with: discord.py
has comment: http://stackoverflow.com/comment/89491499
has body: I'm trying to make my bot tell a user if there is a error by spitting out You do not have the permissions {} But when I try to use this code: @client.command(pass_context = True) async def ban(ctx, member : discord.Member, *, content: str): if ctx.message.author == client.user: return if ctx.message.author.server_permissions.administrator: msg = (str(member) + "has been banned for" + str(content)).format(ctx.message) await client.send_message(member, content) await client.ban(member) await client.send_message(ctx.message.channel, msg) @ban.error async def ban_error(error, ctx): if isinstance(error, CheckFailure): msg = "Sorry but you do not have the permissions {}".format(ctx.message.author.mention) await client.send_message(ctx.message.channel, msg) The discord bot dms the user and there is no errors in the python console and if I remove the @ban.error piece I get a too low of a permission error.
upvote count: 1
answer count: 1
has title: Cannot get discord to show error in chat
tagged with: python
tagged with: discord
favorite count: 0
tagged with: python-3.x
type: AnsweredQuestion
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/51256425

http://stackoverflow.com/comment/89557661
type: QuestionComment
type: Comment
score: 1
has text: The error message you quote is a Numpy error, while neither your code nor your question mentions Numpy anywhere. You don't seem to be telling the whole truth here. :)
comment on: http://stackoverflow.com/q/51289877

http://stackoverflow.com/comment/89549302
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51281994
has text: thanks, but have error (index):1 Failed to load resource: the server responded with a status of 403 (Forbidden)

http://stackoverflow.com/comment/89483970
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51252361
has text: Does it give further information when telling you that it failed to run myappsource? Perhaps a line that looks like "Could not find theIcon.ico"?

http://stackoverflow.com/comment/89505196
type: Comment
type: QuestionComment
has text: It should go into the column next to the name generated. So if michael gets pulled and generated, the cell to the right of michael (on the csv) should increment by 1 becoming 6. I am only using y as it contains an index which i thought may be useful. I also thought the value (in this case y) between the square brackets [ ] was the location of the cell to be written to
comment on: http://stackoverflow.com/q/51262969
score: 0

http://stackoverflow.com/a/56575669
downvote count: 0
answers question: http://stackoverflow.com/q/51322535
type: Answer
upvote count: 1
score: 1
has body: For the data you have provided, I have made the assumptions that the lists are available as list of lists. You can use the following code: import pandas as pd from pymongo import MongoClient scraped_data = [['Type', 'Audited', 'Audited', 'Audited', 'Audited'], ['Period Ending', '31-Mar-18', '31-Mar-17', '31-Mar-16', '31-Mar-15'], ['No, of Months', '12', '12', '12', '12'], ['Net Sales', '466,34', '1,479,10', '5,551,24', '10,724,32'], ['Other Income', '26,68', '185,81', '132,56', '121,20'], ['Interest', '0,00', '0,00', '-286,76', '-361,95'], ['Profit before Tax', '-2,482,68', '-1,513,02', '-805,38', '213,97'], ['Tax', '75,04', '-0,95', '-9,07', '-73,37']] conn = MongoClient(host="url/of/mongodb", port=27017) db = conn["db_name"] coll = db['collection_name'] columns = [elem[0] for elem in data] frame_data = [elem[1:] for elem in data] source = pd.DataFrame(data=frame_data) transposed = source.T mapper_dict={} for i,elem in enumerate(columns): mapper_dict.update({i:elem}) final_result = transposed.rename(mapper=mapper_dict,axis=1).to_dict(orient="records") coll.insert_many(final_result) This would store the data as per your requirement
has comment: http://stackoverflow.com/comment/99730724

http://stackoverflow.com/a/51259815
type: Answer
has body: Additional information could be passed to each child by adding another optional argument to your child, e.g. extra. This could be in the form of a dictionary, and if present is added to the child's dictionary. For example: import csv import json class Node(object): def __init__(self, name, size=None, extra=None): self.name = name self.children = [] self.size = size self.extra = extra def child(self, cname, size=None, extra=None): child_found = [c for c in self.children if c.name == cname] if not child_found: _child = Node(cname, size, extra) self.children.append(_child) else: _child = child_found[0] return _child def as_dict(self): res = {'name': self.name} if self.size is None: res['children'] = [c.as_dict() for c in self.children] else: res['size'] = self.size if self.extra: res.update(self.extra) return res root = Node('Flare') with open('test.csv', 'r') as f: reader = csv.reader(f) header = next(reader) for row in reader: team, task, country, id, id2 = row root.child(team, extra={'test' : 'TEAM'}) \ .child(task, extra={'test' : 'Task'}) \ .child(country, extra={'test' : {'ID': id, 'ID2': id2}}) \ .child(id, size=id2) print json.dumps(root.as_dict(), indent=4) This would give you: { "name": "Flare", "children": [ { "test": "TEAM", "name": "Team C", "children": [ { "test": "Task", "name": "Processing", "children": [ { "test": { "ID2": "34", "ID": "67" }, "name": "US", "children": [ { "name": "67", "size": "34" } ] } ] }, { "test": "Task", "name": "Review", "children": [ { "test": { "ID2": "56", "ID": "734" }, "name": "US", "children": [ { "name": "734", "size": "56" } ] } ] }, { "test": "Task", "name": "Support", "children": [ { "test": { "ID2": "43", "ID": "34" }, "name": "US", "children": [ { "name": "34", "size": "43" } ] } ] } ] } ] } You should be able to adjust the call to include the information you want and the layout you want. These are examples.
score: 0
answers question: http://stackoverflow.com/q/51245686

http://stackoverflow.com/comment/89524160
type: Comment
type: QuestionComment
has text: You can use `verbose=1` instead of `2` to see if there is any progress at all...
score: 1
comment on: http://stackoverflow.com/q/51271817

http://stackoverflow.com/q/51266728
type: AnsweredQuestion
upvote count: 0
has comment: http://stackoverflow.com/comment/89511757
has body: At the moment I have been using lists to plot data and wish to find out a pattern for forecasting. Trying to use data frames have not helped me and have caused great discomfort. Is it possible to use python lists and machine learning or pattern recognition algorithm to forecast data? I am new to python :)
has title: Is it possible to use lists in order to forecast data in python?
favorite count: 0
has comment: http://stackoverflow.com/comment/89511608
type: Question
has answer: http://stackoverflow.com/a/51361559
tagged with: machine-learning
tagged with: python
answer count: 1
accepted answer: http://stackoverflow.com/a/51361559
tagged with: forecasting
score: -4
downvote count: 4

http://stackoverflow.com/comment/89521909
comment on: http://stackoverflow.com/q/51271726
has text: Did you try downloading and installing the latest C++ SDK?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89541824
type: QuestionComment
has text: your `Content-type` is not json, isn't it? maybe should be something like `multipart/form-data; boundary=`
type: Comment
comment on: http://stackoverflow.com/q/51282011
score: 0

tkinter
tags question: http://stackoverflow.com/q/51214057
tags question: http://stackoverflow.com/q/51241759
tags question: http://stackoverflow.com/q/51312412
tags question: http://stackoverflow.com/q/51298758
tags question: http://stackoverflow.com/q/51270180
tags question: http://stackoverflow.com/q/51218010
tags question: http://stackoverflow.com/q/51191603
tags question: http://stackoverflow.com/q/51203784
tags question: http://stackoverflow.com/q/51217019
tags question: http://stackoverflow.com/q/51180388
tags question: http://stackoverflow.com/q/51202159
tags question: http://stackoverflow.com/q/51235094
tags question: http://stackoverflow.com/q/51251594
tags question: http://stackoverflow.com/q/51254118
tag name: tkinter
tags question: http://stackoverflow.com/q/51243498
tags question: http://stackoverflow.com/q/51228548
tags question: http://stackoverflow.com/q/51248099
tags question: http://stackoverflow.com/q/51253078
tags question: http://stackoverflow.com/q/51227992
tags question: http://stackoverflow.com/q/51292672
tags question: http://stackoverflow.com/q/51276618
tags question: http://stackoverflow.com/q/51194601
tags question: http://stackoverflow.com/q/51304080
tags question: http://stackoverflow.com/q/51320783
tags question: http://stackoverflow.com/q/51227060
tags question: http://stackoverflow.com/q/51183324
tags question: http://stackoverflow.com/q/51178942
tags question: http://stackoverflow.com/q/51280915
tags question: http://stackoverflow.com/q/51181368
tags question: http://stackoverflow.com/q/51242646
tags question: http://stackoverflow.com/q/51273988
tags question: http://stackoverflow.com/q/51286820
tags question: http://stackoverflow.com/q/51263837
tags question: http://stackoverflow.com/q/51305250
tags question: http://stackoverflow.com/q/51169603
tags question: http://stackoverflow.com/q/51311798
tags question: http://stackoverflow.com/q/51316684
tags question: http://stackoverflow.com/q/51222060
tags question: http://stackoverflow.com/q/51200282
tags question: http://stackoverflow.com/q/51323224
tags question: http://stackoverflow.com/q/51263512
tags question: http://stackoverflow.com/q/51181605
tags question: http://stackoverflow.com/q/51203301
tags question: http://stackoverflow.com/q/51243796
tags question: http://stackoverflow.com/q/51268204
tags question: http://stackoverflow.com/q/51266291
tags question: http://stackoverflow.com/q/51220232
tags question: http://stackoverflow.com/q/51270345
tags question: http://stackoverflow.com/q/51230326
tags question: http://stackoverflow.com/q/51242815
tags question: http://stackoverflow.com/q/51183596
tags question: http://stackoverflow.com/q/51274493
tags question: http://stackoverflow.com/q/51221755
tags question: http://stackoverflow.com/q/51200744
tags question: http://stackoverflow.com/q/51226466
tags question: http://stackoverflow.com/q/51296866
tags question: http://stackoverflow.com/q/51178266
tags question: http://stackoverflow.com/q/51262561
tags question: http://stackoverflow.com/q/51191313
tags question: http://stackoverflow.com/q/51299070
tags question: http://stackoverflow.com/q/51235075
tags question: http://stackoverflow.com/q/51240265
tags question: http://stackoverflow.com/q/51197181
tags question: http://stackoverflow.com/q/51225555
tags question: http://stackoverflow.com/q/51217104
tags question: http://stackoverflow.com/q/51205716
tags question: http://stackoverflow.com/q/51230403
tags question: http://stackoverflow.com/q/51296650
tags question: http://stackoverflow.com/q/51205949
tags question: http://stackoverflow.com/q/51306179
tags question: http://stackoverflow.com/q/51298489
tags question: http://stackoverflow.com/q/51215097
tags question: http://stackoverflow.com/q/51292880
tags question: http://stackoverflow.com/q/51168620
tags question: http://stackoverflow.com/q/51211452
tags question: http://stackoverflow.com/q/51228874
tags question: http://stackoverflow.com/q/51214626
tags question: http://stackoverflow.com/q/51252361
tags question: http://stackoverflow.com/q/51224905

http://stackoverflow.com/a/74577656
type: Answer
answers question: http://stackoverflow.com/q/51233491
score: 0
has body: From Python Interpreter download the version of opencv-python 4.5.4.60 and opencv-contrib-python 4.5.5.64.

http://stackoverflow.com/comment/89471914
comment on: http://stackoverflow.com/q/51246242
has text: Yes it is hdfs only.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51260906
has body: Isolated count You are close. But your syntax attempts to treat a series as if it were a list. Instead, you can use the count method after conversion to list: from operator import methodcaller df['22_Count'] = df['Value'].str.split(',').apply(methodcaller('count', '22')) print(df) Index Value 22_Count 0 0 22,88,22,24 2 1 1 24,24 0 2 2 22,24 1 3 3 11,22,24,12,24,24,22,24 2 4 4 22 1 Multiple counts Use the methods shown by @jezrael.
answers question: http://stackoverflow.com/q/51258419
score: 0
type: Answer

http://stackoverflow.com/a/51230435
upvote count: 3
has comment: http://stackoverflow.com/comment/89443444
downvote count: 0
type: Answer
has body: Minimal changes to make it work: lol = [['a', 'v', '1', 'r'], ['d', 'x', 'b'], ['s', '0', 'u', 'x']] def cut_lol(lol, n): count = 0 result = [] for l in lol: if count + len(l) &gt; (n): new_len_l = n - count if new_len_l: result.append(l[:new_len_l]) return result result.append(l) count += len(l) return result Simplified version: lol = [['a', 'v', '1', 'r'], ['d', 'x', 'b'], ['s', '0', 'u', 'x']] def cut_lol(lol, n): count = 0 result = [] for l in lol: to_read = n - count if to_read &lt;= 0: break result.append(l[:to_read]) count += len(l) return result
score: 3
answers question: http://stackoverflow.com/q/51230377

http://stackoverflow.com/q/51231901
type: Question
score: 2
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python
has body: For fun, I am trying to run a caesar cipher on a string where each character is shifted by the previous character in the string. The initial character is obviously not shifted and used to shift the second, the second character is used as the seed for the third character, etc Encoding appears to be working as intended; decoding on the other hand... key = "a" word = key + "shop" print(word) coded = "" for i, val in enumerate(word[1:]): coded += (chr(((ord(word[i]) + ord(val) - 97) % 26) + 97)) print(key + coded) encoded = key + coded decoded = "" for i, val in enumerate(encoded[1:]): decoded += chr(((ord(encoded[i]) - ord(val) - 97) % 26) + 97) print(key + decoded) My Maths appears (to the naive eye) correct. Does the encoding have some property that I am not aware of that does not allow for reversing of this? Example output using the inputs above: ashop alsow amqbp Obviously I would like the amqbp to be ashop. Moving the -97 around does not help (not even sure why it would if it did). What am I missing here?
upvote count: 2
type: UnansweredQuestion
tagged with: caesar-cipher
has title: Caesar cipher seeded from previous (shifted) character
has answer: http://stackoverflow.com/a/51231980

http://stackoverflow.com/a/51311494
upvote count: 1
accepted answer of: http://stackoverflow.com/q/51288632
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51288632
type: Answer
has body: You should call cube.Update() before you call cube.GetOutput() from vtk import * # Generate polygon data for a cube cube = vtk.vtkCubeSource() cube.Update() # Create a mapper for the cube data cube_mapper = vtk.vtkPolyDataMapper() cube_mapper.SetInputData(cube.GetOutput()) # Connect the mapper to an actor cube_actor = vtk.vtkActor() cube_actor.SetMapper(cube_mapper) cube_actor.GetProperty().SetColor(1.0, 0.0, 0.0) # Create a renderer and add the cube actor to it renderer = vtk.vtkRenderer() renderer.SetBackground(0.0, 0.0, 0.0) renderer.AddActor(cube_actor) # Create a render window render_window = vtk.vtkRenderWindow() render_window.SetWindowName("Simple VTK scene") render_window.SetSize(400, 400) render_window.AddRenderer(renderer) # Create an interactor interactor = vtk.vtkRenderWindowInteractor() interactor.SetRenderWindow(render_window) # Initialize the interactor and start the # rendering loop interactor.Initialize() render_window.Render() interactor.Start()
score: 1

http://stackoverflow.com/q/51207005
has body: I want to add a new entry to an array and remove the last entry. I want to do this without using pop or append etc. Attempt def main(): array = [1,2,3,4,5] array_len = len(array) new_val = 9 print(array) for i in range(0,array_len-1): temp = array[i] array[i] = array[i+1] array[i+1]= temp array[0] = new_val print(array) main() The output gives [9,3,4,5,1] when the answer I want is [9,1,2,3,4]. Any tips on how I can correct the logic used would be great! Edit I should have been more clear. I want to do this using only logic and loops, without using built in python functions or array operations like array[:-1] etc..
favorite count: 0
has title: Add new entry to an array in Python and remove the last entry
has comment: http://stackoverflow.com/comment/89395003
answer count: 3
possible better answer: http://stackoverflow.com/a/51207101
tagged with: python
accepted answer: http://stackoverflow.com/a/51207148
has comment: http://stackoverflow.com/comment/89394988
has comment: http://stackoverflow.com/comment/89398238
has comment: http://stackoverflow.com/comment/89394899
has comment: http://stackoverflow.com/comment/89395466
has answer: http://stackoverflow.com/a/51207116
downvote count: 1
type: AnsweredQuestion
score: -1
has comment: http://stackoverflow.com/comment/89395030
has answer: http://stackoverflow.com/a/51207148
type: Question
upvote count: 0
tagged with: arrays
has answer: http://stackoverflow.com/a/51207101
has comment: http://stackoverflow.com/comment/89395004

http://stackoverflow.com/comment/89368379
type: Comment
type: QuestionComment
has text: I guess the biggest question here is what you define as the center?
comment on: http://stackoverflow.com/q/51193320
score: 0

http://stackoverflow.com/comment/89342522
type: Comment
type: QuestionComment
score: 0
has text: I want to keep it anonymous, so I've left out the ability to register users.Also, I'm using mongoDB and planning on doing the same once I start testing it on Heroku. I've only used mongoDB and sqlite3 so far, but I'd be happy to try something else since this is my first large web project.
comment on: http://stackoverflow.com/q/51179920

http://stackoverflow.com/a/51325523
upvote count: 1
accepted answer of: http://stackoverflow.com/q/51318909
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: You are not done yet, you need to do this : conda install keras
answers question: http://stackoverflow.com/q/51318909
score: 1

http://stackoverflow.com/a/51322237
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51321791
has body: This function uses a dictionary of the secondary colours and their component colours, and checks if the set of component colours is a subset of the set of colours passed to it: secondary_colours = {"green": ("yellow", "blue"), "purple": ("blue", "red"), "orange": ("red", "yellow"), "grey": ("white", "black"), "beige": ("white", "yellow"), "brown": ("black", "yellow")} def obtainable_colours(primary_colours): """Returns a list of secondary colours obtainable from combinations of the primary colours provided. Assumes additive pigment mixing as defined above.""" global secondary_colours response = [] for s_col,components in secondary_colours.items(): if set(components) &lt; set(primary_colours): response.append(s_col) return response Test: p1 = ['white','black','yellow'] p2 = ['yellow','white','black','red'] p3 = ['blue','yellow','red'] p4 = ['white','red','blue'] for p in [p1,p2,p3,p4]: print(p) print(obtainable_colours(p)) print("\n") &gt;&gt;&gt; ['white', 'black', 'yellow'] ['grey', 'beige', 'brown'] ['yellow', 'white', 'black', 'red'] ['orange', 'grey', 'beige', 'brown'] ['blue', 'yellow', 'red'] ['green', 'purple', 'orange'] ['white', 'red', 'blue'] ['purple']
answers question: http://stackoverflow.com/q/51321791
type: Answer
score: 0
has comment: http://stackoverflow.com/comment/89620194

http://stackoverflow.com/q/51324402
has comment: http://stackoverflow.com/comment/89624003
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89623789
score: 1
has answer: http://stackoverflow.com/a/51324781
upvote count: 1
has comment: http://stackoverflow.com/comment/89629353
type: Question
has title: Boolean indexing in Pandas
has comment: http://stackoverflow.com/comment/89624681
tagged with: pandas
has body: I have the following DataFrame books = pd.Series(data = ['Great Expectations', 'Of Mice and Men', 'Romeo and Juliet', 'The Time Machine', 'Alice in Wonderland' ]) authors = pd.Series(data = ['Charles Dickens', 'John Steinbeck', 'William Shakespeare', ' H. G. Wells', 'Lewis Carroll' ]) user_1 = pd.Series(data = [3.2, np.nan ,2.5]) user_2 = pd.Series(data = [5., 1.3, 4.0, 3.8]) user_3 = pd.Series(data = [2.0, 2.3, np.nan, 4]) user_4 = pd.Series(data = [4, 3.5, 4, 5, 4.2]) dict_temp = {'Book Title':books, 'Author': authors, 'User 1': user_1, 'User 2':user_2, 'User 3': user_3, 'User 4': user_4} pd.set_option('precision', 1) temp_df = pd.DataFrame(dict_temp) My aim is to select all the columns which have user rating = 5.0. When i do the following it works fine. temp_df[temp_df == 5.0] However, if i want to select columns which have user rating > 4.0, the result is different. Why is this? temp_df[temp_df &gt; 4.0] Here is the screenshot of what happens when I run temp_df == 5.0 v/s temp_df > 4.0. My question is why do i see Book Title and Author columns ? P.S. i am able to acheive my desired results by this line temp_df[temp_df'User 1','User 2','User 3','User 4' &gt; 4.0]
answer count: 1
downvote count: 0
favorite count: 0

http://stackoverflow.com/comment/89524825
type: AnswerComment
type: Comment
has text: I'm not sure it can on a complexity level. It can improve in small cases here and there, but I think from a complexity standpoint it is required that something to the factor of `n` where `n` is the number of connected color sets is required
score: 1
comment on: http://stackoverflow.com/a/51273162

http://stackoverflow.com/a/78717313
downvote count: 0
answers question: http://stackoverflow.com/q/51285835
type: Answer
upvote count: 3
score: 3
has body: As of November 2023 all answers here are outdated - you can now configure the log level of lambdas in a much more fine grained way than before, specifically you can adjust the System log level to not generate these Start/Stop messages. The only downside is that you have to log in JSON format unfortunately. More details are available here: https://aws.amazon.com/blogs/compute/introducing-advanced-logging-controls-for-aws-lambda-functions/

http://stackoverflow.com/a/51240804
has body: You're question is fairly unclear. Especially when it comes to what input you're going to have. Thus the answer below works for the input you provided, but you will probably need to adapt the conditons, splits, and others aspects to your needs. Your input: from collections import OrderedDict D = OrderedDict([('Id', '0061J00000QPnGoQAL'), ('Name', 'Acme X-Author RenewalSep tx'), ('Account', OrderedDict([('Region__c', 'Americas'), ('Name', 'Accenture')])), ('CreatedBy', OrderedDict([('Name', 'Jerret Moz')]))]) How to get the second desired output: D2 = OrderedDict() for key, value in D.items(): if key.lower() == "id": D2[key] = value elif key.lower() == "name": D2[key] = value.split(" RenewalSep tx")[0] elif type(value) == OrderedDict: for key2, value2 in value.items(): D2[key + "." + key2] = value2 Output: OrderedDict([('Id', '0061J00000QPnGoQAL'), ('Name', 'Acme X-Author'), ('Account.Region__c', 'Americas'), ('Account.Name', 'Accenture'), ('CreatedBy.Name', 'Jerret Moz')])
has comment: http://stackoverflow.com/comment/89477422
type: AcceptedAnswer
score: 0
accepted answer of: http://stackoverflow.com/q/51240613
type: Answer
answers question: http://stackoverflow.com/q/51240613

http://stackoverflow.com/comment/89475330
type: Comment
has text: I forgot I used Anaconda, maybe the reason is this :/
comment on: http://stackoverflow.com/q/51245502
score: 0
type: QuestionComment

http://stackoverflow.com/q/51240796
has body: I am using OULAD dataset It has 7 csv file which are linked together in the way shown in the image in the OULAD website. one of the csv files named student_registration has 32593 rows and 5 columns and another one named student_Vle has 10655280 rows and 6 columns. I want to add columns date &amp; sum_click from student_vle to student_registration table such that only existing 32593 students information is added. I tried left join but the result is very weird. It has [13009427 rows x 11 columns] instead of 32593 rows and 8 columns. Its like Union. U can get the dataset from UCI repository. here is my code- import pandas as pd import numpy as np student_reg = pd.read_csv('/home/user/Documents/MOOC dataset cleaned/studentRegistration.csv') student_vle = pd.read_csv('/home/user/Documents/MOOC dataset cleaned/studentVle.csv') student_reg_vle = pd.merge(student_reg, student_vle, on='id_student', how='left') student_reg_vle.set_index('id_student', inplace=True) print(student_reg_vle)
tagged with: python
has title: To use OULAD datasets how do I join or merge them?
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51240835
type: Question
score: 0
tagged with: pandas
has answer: http://stackoverflow.com/a/51240835
answer count: 1
tagged with: data-analysis

http://stackoverflow.com/a/51178970
downvote count: 0
has body: (1) Referring to this line: if qr == '' or not qr[0].lower() in ['y','n']: The [0] on qr refers to the first character of the input qr only. (2) The differences between this two pieces of code is on the same one, the first is if qr == '' or not qr[0].lower() in ['y','n']: if qr == '' or not qr.lower() in ['y','n']: The second one affects the entire string of qr and keeps all the characters, and makes a difference if you input a string longer than one character.
score: 1
answers question: http://stackoverflow.com/q/51178925
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51178925
type: Answer

http://stackoverflow.com/comment/89491221
type: Comment
has text: Thanks. It works as owner, but I don't like having to give that much privilege. The code is almost working. I use AssetOperation.create_or_update to create the media asset and then switch over to the storage api and put the files into the associated storage container. However, the uploaded files don't show up through the media asset even though I can see them in the asset's storage container. Is there an additional call to "join" them? It would be really nice to have an example. The docs aren't very helpful if you don't know the "flow" of the actions required.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/51218330

http://stackoverflow.com/q/51233767
upvote count: 1
has body: during my python learning I've got an error in this code: class User: def __init__(self, first_name, last_name, location, payment_method): self.first_name = first_name self.last_name = last_name self.location = location self.payment_method = payment_method self.login_attempts = 0 def increment_login_attempts(self): self.login_attempts += 1 def reset_login_attempts(self): self.login_attempts = 0 def printing_login_attempts(self): print('Quantity of login attempts: ' + str(self.login_attempts)) def describe_user(self): print('Current user first name: ' + self.first_name.title()) print('Current user last name: ' + self.last_name.title()) print('Location is ' + self.location.title() + '. Payment method is ' + self.payment_method) def greet_user(self): print('Hello ' + self.first_name.title() + ' ' + self.last_name.title() + '!!!') class Admin(User): def __init__(self, first_name, last_name, location, payment_method): super().__init__(first_name, last_name, location, payment_method) self.privilegis = Privilegis() class Privilegis: def __init__(self, privilegis_type): self.privilegis_type = ['Allow to delete users', 'Allow to rename users', 'Allow to ban users'] def show_privilegis(self): print('Special admins privilegis are: ' + ', '.join(self.privilegis)) new_user = Admin('John', 'Edwards', 'LA', 'visa') new_user.privilegis.show_privilegis() error description self.privilegis = Privilegis() TypeError: __init__() missing 1 required positional argument: 'privilegis_type' I cant get what the problem is. How should I use one class(Privilegis) as attribute of another(Admin) ?
tagged with: python
favorite count: 0
has title: __init__() missing 1 required positional argument (Python3)
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89446583
has comment: http://stackoverflow.com/comment/89446584
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89446572
downvote count: 1
duplicate of: http://stackoverflow.com/q/19929626
has answer: http://stackoverflow.com/a/51233788
type: Question
answer count: 2
linked to: http://stackoverflow.com/q/19929626
score: 0
has answer: http://stackoverflow.com/a/51233825

http://stackoverflow.com/comment/89515536
type: Comment
comment on: http://stackoverflow.com/a/51221814
has text: Thanks. Is there anyway to get a value out of those hooks into my tests though? I updated OP slightly; thing_that_takes_a_few_mins() returns a value that I want accessible in my tests.
score: 0
type: AnswerComment

http://stackoverflow.com/q/51287361
has comment: http://stackoverflow.com/comment/89553544
has comment: http://stackoverflow.com/comment/89553043
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89554251
answer count: 0
linked to: http://stackoverflow.com/q/15872788
has comment: http://stackoverflow.com/comment/89553089
type: Question
tagged with: api
has comment: http://stackoverflow.com/comment/89554012
tagged with: websocket
has comment: http://stackoverflow.com/comment/89553732
score: 0
has body: I am using Bitfinex WebSockets V2 with Python library https://github.com/Crypto-toolbox/btfxwss. I have a problem with receiving updates when subscribed to many websocket channels. The issue is that I need to subscribe to 3 order book updates, 3 ticker updates, and 3 trades updates (total - 9 channels) at Bitfinex Websocket API. And I just stop receiving updates after like several minutes of normal work with no errors (or keep receiving them, but with huge delay). So can you help me to find out what's wrong ? Are there any limitations for Websocket connections? Because when I subscribe to 1 order book updates using the same code, everything is OK.
has comment: http://stackoverflow.com/comment/89553821
has title: Don't receive updates when subscribed to 9 Websocket channels

http://stackoverflow.com/comment/89575504
comment on: http://stackoverflow.com/q/51299228
has text: @Emmanuel that seems to be correct, now it gives me error saying that function takes only one argument. I simply removed second argument and it does print text, but does not remove punctuation
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/89590384
type: AnswerComment
has text: Sorry for being late on this - you need to change the regex then a bit: if there is no space between the dash and the number then this would work: match = re.search(r'(?<=-) [0-9]+', line) (?<=-) goes back and searches for "-" then it starts looking for the number
type: Comment
score: 1
comment on: http://stackoverflow.com/a/51197884

http://stackoverflow.com/comment/89488066
has text: To find out if the number of classes is a problem, you could remove half the classes from the models file and try to see if you still get the error.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51254536
score: 1

http://stackoverflow.com/comment/89493718
comment on: http://stackoverflow.com/a/51253559
has text: That worked great. The only problem is that pyqtgraph has added 460mb to the 50mb exe! It's too big lol. A nice feature but too massive!
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/89570822
has text: Please don't post images of code. Put code in code blocks in your post. Also, you should include the Python script.
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/51296699

http://stackoverflow.com/comment/89495879
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51256922
has text: @jubibanna Check your browser requests you'll see all the `XHR` requests. Besides of this if this answer fills your needs, accept it.

http://stackoverflow.com/comment/89383156
type: Comment
comment on: http://stackoverflow.com/q/51200743
type: QuestionComment
has text: You've described your problem pretty clearly: your data file is *not* in CSV format, so `read_csv` isn't the right tool for you. You need to research how to read lists in sequence.
score: 1

http://stackoverflow.com/comment/89403175
has text: Hey @RobL ! I need that intermediate model because i have to store individual player info like time and medal, which i cannot do in "Swimming" model alone, because its a ManyToManyField in Player field of "Swimming".
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51210970

http://stackoverflow.com/a/51242322
answers question: http://stackoverflow.com/q/51242220
score: 19
type: AcceptedAnswer
upvote count: 19
type: Answer
has body: You can use nargs='?' for this: parser.add_argument('-o', '--output', nargs='?', default=None, const='my_default_location') If not present, it will produce the default value, if present but without a value it'll use const, otherwise it'll use the supplied value. Also read through the other examples in the docs, there's a sample for an optional output file which could be useful.
accepted answer of: http://stackoverflow.com/q/51242220
downvote count: 0

http://stackoverflow.com/a/75822027
score: 0
has body: It can easily be solved by using pandas. import pandas as pd to_match = pd.Series(["c", "a", "b", "b", "c", "a"]) unique_vals = pd.Series(["c", "b", "a"]) indices = pd.Index(unique_vals).get_indexer(to_match) Out[1]: array([0, 2, 1, 1, 0, 2])
answers question: http://stackoverflow.com/q/51171314
type: Answer

http://stackoverflow.com/q/51273988
has answer: http://stackoverflow.com/a/51300248
accepted answer: http://stackoverflow.com/a/51300248
answer count: 1
has body: I want to auto scroll a text box on the right on a specific click on a word on the left (similar to Navigation pane in MS Word). I added hyperlink to link every word in the section, and now I want that when I click the word, it can extract that word, and that word is sent to any function which will return tkinter.see(index/line(word)) and enable auto scroll. But I am unable to extract the word on the click. See the output that I have: I want that when I click on Basic Transaction it scrolls to the basic transactions and when I click on Payment it scrolls to the payment section. My Question to the Specific part: I want to extract the section name when I click on it. Then I can pass that string to the function click1() which will auto scroll to find that specific word on the right text box using the .see method in tkinter. I change the framing of the question: In the above image, on the left text widget, under the Section, if I click on the "Basic Transaction", then how can I print that on the Ipython console(Spyder console)? And if I click "Payment", how can I print "Payment" on my python console? Is there any possible way to extract the text of the Mouse-1 click? Something like: tag_bind(&lt;Mouse-1&gt;) if Mouse-1 clicks: print(wordstart, wordend) OR print(text_widget.cget(text))
has comment: http://stackoverflow.com/comment/89550496
score: 0
upvote count: 1
downvote count: 1
favorite count: 0
tagged with: python-3.x
tagged with: tkinter
has comment: http://stackoverflow.com/comment/89552923
tagged with: python
has comment: http://stackoverflow.com/comment/89526576
type: AnsweredQuestion
has title: Tkinter: Auto scroll Text box on a specific click on the text box on its left in Tkinter. Similar to Navigation Pane in MS Word
has comment: http://stackoverflow.com/comment/89563830
type: Question
has comment: http://stackoverflow.com/comment/89558334

http://stackoverflow.com/a/51217990
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/51217775
accepted answer of: http://stackoverflow.com/q/51217775
score: 1
has body: You aren't taking the current character into account if you find the next character isn't in alphabetical order, and that's why you're missing one character in the end. Instead, you should always process the current character first before resetting temp if the next character isn't in order. s = 'azcbobobegghakl' i = 0 temp = '' #temporary variable I use to change longest longest = '' for i in range(len(s)-1): temp += s[i] if len(longest) &lt; len(temp): longest = temp if s[i] &gt; s[i+1]: #checks if it's in alphabetical order temp = '' #reset temp after every substring if len(longest) &lt; len(temp): longest += temp #update longest if the new substring is longer i +=1 print('Longest substring in alphabetical order is:', longest) This outputs: Longest substring in alphabetical order is: beggh
upvote count: 1
type: AcceptedAnswer

http://stackoverflow.com/a/52615865
upvote count: 1
has body: Another way from scrapy.utils.log import configure_logging configure_logging(install_root_handler=True) logging.disable(50) # CRITICAL = 50 for logging levels = Python Logging Levels more information => Scrapy Logging Another way in spider: custom_settings = { 'LOG_ENABLED': False, # ... other settings... }
score: 1
answers question: http://stackoverflow.com/q/51284987
downvote count: 0
type: Answer

http://stackoverflow.com/a/51204415
has body: There are various ways to split a dict. Here's one. from itertools import islice spam = {'a': '1', 'b': '2', 'c': '3', 'd': '4', 'e': '5'} spam1, spam2 = [dict(islice(spam.items(), i, None, 2)) for i in (None, 1)] print(spam1, spam2) # {'a': '1', 'c': '3', 'e': '5'} {'b': '2', 'd': '4'} We could have converted the items to a tuple and used a regular slice, but since your dict is "very large", it's probably better to use islice. import json then you can use json.dump() to save a dict into a file, and json.load() to get a dict back from the file. To merge the two dicts, use dict.update() spam1.update(spam2) print(spam1) # {'a': '1', 'c': '3', 'e': '5', 'b': '2', 'd': '4'}
accepted answer of: http://stackoverflow.com/q/51203760
score: 4
upvote count: 4
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51203760
type: Answer

http://stackoverflow.com/comment/89375283
score: 3
has text: At the start, a time delay is fine but as you get more users you are going to need to find a different way so that users aren't waiting a few seconds for other users to get their requests sent back. As you scale, you could potentially talk to the owner of the API to discuss setting up more reasonable limits.
comment on: http://stackoverflow.com/q/51196447
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89329023
comment on: http://stackoverflow.com/a/51172695
type: AnswerComment
score: 0
type: Comment
has text: It works thanks, i understand better, i'll explore your advice on sparse matrix !

http://stackoverflow.com/q/51307587
has comment: http://stackoverflow.com/comment/89592685
has comment: http://stackoverflow.com/comment/89592699
tagged with: django
type: Question
type: AnsweredQuestion
has title: Django messages/notification if connected model doesn't exist / has changed
has answer: http://stackoverflow.com/a/51311890
has comment: http://stackoverflow.com/comment/89592249
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/89601540
has comment: http://stackoverflow.com/comment/89594069
has body: I have a Profile model, which is a OnetoOne relation to the User model. I would like to tell the users that their profile is not complete, and ask them to fill in certain details dynamically. For example, I have a Location model which is a OneToOne to the Profile. class Profile(models.Model): # some fields e.g. name class Location(models.Model): profile = models.OneToOneField(Profile, on_delete=models.CASCADE, null=True) # longitude = ... # latitude = ... After user signup, we do not yet have the location instance connected to profile. What I would like to display, is a django-message/error bar at the top, instructing the user to complete the profile if the profile doesn't have the location attribute. I'm not sure how I should proceed: One way, I thought is to add the completed_setup boolean field to the Profile class. If user now decides to delete location, we will also update this field and set it to False. {% if profile.completed_setup %}{% else %} Finish Building Your Profile {% endif %} Another way would be to have the following in the template: {% if profile.location %}{% else %} Finish Building Your Profile {% endif %} I'm looking for the most efficient and proper way to do this, since I have more connected models (not just location).
has comment: http://stackoverflow.com/comment/89592862
accepted answer: http://stackoverflow.com/a/51311890
tagged with: python

http://stackoverflow.com/comment/89593786
type: AnswerComment
has text: I am using simple MAPI. I tried to create the key myself but I think the admin restricted my access to the policies section. Ive been able to add keys in other areas but not under policies (or any sub keys of policies). Do you have any resources on the outlook object model? I will try that instead.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51307974

3d-model
type: Tag
tags question: http://stackoverflow.com/q/51190480
tag name: 3d-model

http://stackoverflow.com/comment/89411727
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51210193
has text: @eaglesear (0,10,1) and (9,-1,-1) is the same sequence [0,1,2...7,8,9] backward and forward, isn't it?
score: 0

http://stackoverflow.com/comment/89474526
type: QuestionComment
comment on: http://stackoverflow.com/q/51247832
score: 1
has text: How have you arrived at the conclusion that the sort is incorrect? Did you print `df` or `dataframe`?
type: Comment

http://stackoverflow.com/a/51291787
type: Answer
score: 1
answers question: http://stackoverflow.com/q/51289109
upvote count: 1
has body: I believe what you want to do is split your 2D arrays into chunks. This old answer might help with your query: Slice 2d array into smaller 2d arrays
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/89561175
accepted answer of: http://stackoverflow.com/q/51289109

http://stackoverflow.com/comment/89434296
type: Comment
type: QuestionComment
has text: You gave three options. What do you expect from us? Make a choicr for you? On what basis?
score: 0
comment on: http://stackoverflow.com/q/51227137

http://stackoverflow.com/q/51276563
has comment: http://stackoverflow.com/comment/89530911
has body: I have a dataframe like this: id year Q 1 2017 1 2 2017 2 3 2018 1 4 2018 2 5 2018 3 And would like to get this create another column called D: id year Q Desc 1 2017 1 '2017 first Quarter' 2 2017 2 '2017 second Quarter' 3 2018 1 '2018 first Quarter' 4 2018 2 '2018 second Quarter' 5 2018 3 '2017 third Quarter' Yet np.where seems to only accept 2 parameter (if true and if false). So the idea is to have a np.where sentence that can deal with multiple possibilities
has answer: http://stackoverflow.com/a/51276600
has answer: http://stackoverflow.com/a/51276711
score: 2
upvote count: 2
type: Question
tagged with: numpy
has title: Python - Pandas create column with np.where for multiple different values
answer count: 3
tagged with: pandas
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/51276601
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/89435211
comment on: http://stackoverflow.com/q/51227582
has text: Also, in your first example, you are only checking for key `'c'` in each element of list `name`. So if `'Completed'` is paired with a different key, you will not get `True`.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89479138
score: 0
comment on: http://stackoverflow.com/q/51250137
has text: Start by reading on [`getattr()`](https://docs.python.org/3/library/functions.html#getattr)...
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89589362
has text: So... "how do I iterate over multiple values?"? Use a list and a for loop.
type: Comment
score: 2
comment on: http://stackoverflow.com/q/51306340
type: QuestionComment

spyder
tag name: spyder
tags question: http://stackoverflow.com/q/51220934
tags question: http://stackoverflow.com/q/51305199
tags question: http://stackoverflow.com/q/51268592
tags question: http://stackoverflow.com/q/51306393
tags question: http://stackoverflow.com/q/51274647
type: Tag
tags question: http://stackoverflow.com/q/51294499
tags question: http://stackoverflow.com/q/51319318
tags question: http://stackoverflow.com/q/51183802
tags question: http://stackoverflow.com/q/51317382
tags question: http://stackoverflow.com/q/51304635
tags question: http://stackoverflow.com/q/51178391
tags question: http://stackoverflow.com/q/51263934
tags question: http://stackoverflow.com/q/51236128

http://stackoverflow.com/comment/89491910
type: Comment
score: 0
has text: im now getting these error throughout my code `Traceback (most recent call last): File "/usr/lib/python3.6/asyncio/selector_events.py", line 723, in _read_ready data = self._sock.recv(self.max_size) ConnectionResetError: [Errno 104] Connection reset by peer`
comment on: http://stackoverflow.com/a/51256425
type: AnswerComment

http://stackoverflow.com/q/51245121
favorite count: 0
tagged with: python-3.x
tagged with: python
has title: MySQLdb - ModuleNotFoundError
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51245987
score: 1
has comment: http://stackoverflow.com/comment/89470315
upvote count: 1
linked to: http://stackoverflow.com/q/454854
has comment: http://stackoverflow.com/comment/89469799
type: Question
downvote count: 0
has body: I'm failing at importing MySQLdb: import MySQLdb results in: ModuleNotFoundError: No module named 'MySQLdb' I installed the following: pip install mysql-python pip install mysqlclient apt-get install python3-dev python-pip python-dev libmysqlclient-dev apt-get install python-mysqldb (which according to this should suffice) Here is my pip freeze | grep -i sql: mysqlclient==1.3.13 MySQL-python==1.2.5 I'm using Python 3.6 with PyCharm Community Edition on a virtual machine Ubuntu 18.04 What is missing here in order to use this? (also, is there another recommended module for Python API into mysql?) Although this states there is no MySQLdb for Python3.X, this (and this) show it is alive and kicking, I think...
has comment: http://stackoverflow.com/comment/89470487
answer count: 1
has answer: http://stackoverflow.com/a/51245987
tagged with: mysql-python
linked to: http://stackoverflow.com/q/42515854

http://stackoverflow.com/comment/89540121
type: AnswerComment
comment on: http://stackoverflow.com/a/51280597
type: Comment
has text: The files from the folder
score: 0

http://stackoverflow.com/a/51237992
type: Answer
answers question: http://stackoverflow.com/q/51181282
has body: It turns out that as I was following detailed instructions from Django 2 By Example, the issue I had was standard due to the way the authors wanted to teach newbies like me to develop an app. I asked my professor and he confirmed that. It's weird in a sense that the book never mentioned this issue. Thanks for all the help.
score: 0

http://stackoverflow.com/comment/89557361
comment on: http://stackoverflow.com/q/51279031
type: Comment
type: QuestionComment
score: 0
has text: Can you run the code, or are you getting a SyntaxError when trying to run it? This shouldn't raise any errors from the python interpreter.

http://stackoverflow.com/q/51283580
tagged with: machine-learning
tagged with: python
downvote count: 4
has title: NLP, ignoring irrelevant words
accepted answer: http://stackoverflow.com/a/51283886
type: AnsweredQuestion
type: Question
has answer: http://stackoverflow.com/a/51283886
score: -1
has comment: http://stackoverflow.com/comment/89545161
upvote count: 3
tagged with: information-extraction
answer count: 1
tagged with: nlp
favorite count: 0
has body: I developed a simple extractor of passport number from words (for example, input - 'one hundred thirty five thirty five zero zero gets output - 1353500) but how can I filter out unrelevant words like 'ok', 'mhm' and so on? for example human can say 'ok it is 1353500' and bot will extract some meaningless numbers from 'ok', 'it', 'is' and it is bad. The question is how to ignore those non-number words?
tagged with: extract

http://stackoverflow.com/comment/89462258
score: 0
has text: To solve your problem, I would use the .format() method available since python2.x https://docs.python.org/2/library/stdtypes.html#str.format
comment on: http://stackoverflow.com/q/51241722
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51249811
tagged with: python
has answer: http://stackoverflow.com/a/51252244
has answer: http://stackoverflow.com/a/59347737
has answer: http://stackoverflow.com/a/76351600
tagged with: random-seed
has answer: http://stackoverflow.com/a/63085995
tagged with: tensorflow
has answer: http://stackoverflow.com/a/51253945
tagged with: reproducible-research
answer count: 9
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/57094699
has answer: http://stackoverflow.com/a/75251670
score: 25
has body: I am trying to generate N sets of independent random numbers. I have a simple code that shows the problem for 3 sets of 10 random numbers. I notice that even though I use the tf.set_random_seed to set the seed, the results of different runs do not look alike. Any help or comments are greatly appreciated. (py3p6) bash-3.2$ cat test.py import tensorflow as tf for i in range(3): tf.set_random_seed(1234) generate = tf.random_uniform((10,), 0, 10) with tf.Session() as sess: b = sess.run(generate) print(b) This is the output of the code: # output : [9.604688 5.811516 6.4159 9.621765 0.5434954 4.1893444 5.8865128 7.9785547 8.296125 8.388672 ] [8.559105 3.2390785 6.447526 8.316823 1.6297233 1.4103293 2.647568 2.954973 6.5975866 7.494894 ] [2.0277488 6.6134906 0.7579422 4.6359386 6.97507 3.3192968 2.866236 2.2205782 6.7940736 7.2391043] I want something like [9.604688 5.811516 6.4159 9.621765 0.5434954 4.1893444 5.8865128 7.9785547 8.296125 8.388672 ] [9.604688 5.811516 6.4159 9.621765 0.5434954 4.1893444 5.8865128 7.9785547 8.296125 8.388672 ] [9.604688 5.811516 6.4159 9.621765 0.5434954 4.1893444 5.8865128 7.9785547 8.296125 8.388672 ] Update 1: Indeed the reason I had put the seed initializer within the for loop, was because I want to set them differently (think of it as for different MCMC runs, for instance). This is my code which does the job but I am not sure if it's efficient. Basically I generate a couple random seeds between 0 and 2^32-1, and change the seed in each run. Any help or comments to make it more memory/RAM efficient are greatly appreciated. import numpy as np import tensorflow as tf global_seed = 42 N_chains = 5 np.random.seed(global_seed) seeds = np.random.randint(0, 4294967295, size=N_chains) for i in range(N_chains): tf.set_random_seed(seeds[i]) .... some stuff .... kernel_initializer = tf.random_normal_initializer(seed=seeds[i]) .... some stuff with tf.Session() as sess: .... some stuff ..... . . .
downvote count: 0
favorite count: 0
upvote count: 25
has answer: http://stackoverflow.com/a/51252197
type: Question
has title: Reproducible results in Tensorflow with tf.set_random_seed
has comment: http://stackoverflow.com/comment/89478679
has answer: http://stackoverflow.com/a/56426278

http://stackoverflow.com/comment/89481603
comment on: http://stackoverflow.com/a/51251242
type: Comment
score: 2
type: AnswerComment
has text: It wasn't working for me until I realized that I had to restart the kernel. Thank you!!

http://stackoverflow.com/comment/89358099
type: Comment
has text: Hi, i tried using your solution it works. Thanks alot !! You're right, maybe there are some invisible characters in my string.
type: AnswerComment
comment on: http://stackoverflow.com/a/51187752
score: 0

http://stackoverflow.com/q/51181637
type: AnsweredQuestion
has title: Getting a specific file from requested iframe
has answer: http://stackoverflow.com/a/51181730
accepted answer: http://stackoverflow.com/a/51181926
tagged with: urllib
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/51181926
tagged with: beautifulsoup
score: 0
possible better answer: http://stackoverflow.com/a/51181730
has body: I want to get the file link from the anime I'm watching from the site. `import requests from bs4 import BeautifulSoup import re page = requests.get("http://naruto-tube.org/shippuuden-sub-219") soup = BeautifulSoup(page.content, "html.parser") inner_content = requests.get(soup.find("iframe")["src"]) print(inner_content.text)` the output is the source code from the filehoster's website (ani-stream). However, my problem now is how to i get the "file: xxxxxxx" line to be printed and not the whole source code?
tagged with: python
tagged with: python-requests

http://stackoverflow.com/comment/89708100
comment on: http://stackoverflow.com/a/51316339
has text: 0 0.303 0.775 TestSet_0000.img sm 0.524 1 0.670 0.670 TestSet_0001.img sm 2.670 This data is in text file. I want to write program to copy only values =>2.5 and previous line (TestSet_0001.img) to new excel sheet. The 2.5 should be in column B and TestSet_0001.img should be in column A.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/89819845
score: 0
type: AnswerComment
has text: I updated my first post. @Bruno Gonçalves you are right. But your linked question doesn't solve my problem. I don't know how to change the post request from the client side.
comment on: http://stackoverflow.com/a/51302340
type: Comment

http://stackoverflow.com/q/51303659
has comment: http://stackoverflow.com/comment/89583928
type: Question
tagged with: sublimetext
answer count: 1
has title: Sublime Text python error
linked to: http://stackoverflow.com/q/3701646
has comment: http://stackoverflow.com/comment/89583898
score: 0
tagged with: sublimetext3
type: UnansweredQuestion
tagged with: path
linked to: http://stackoverflow.com/q/21578149
tagged with: python
has answer: http://stackoverflow.com/a/51303722
has comment: http://stackoverflow.com/comment/89583897
has body: I've recently stared using sublime text for python and have a little problem. Whenever i try to run my program within sublime using CTRL+B. I get the following error: 'python' is not recognized as an internal or external command, operable program or batch file. [Finished in 0.1s with exit code 1] I tried reinstalling python to C:\Python37-64 but the problem still persists. Can anyone help?
duplicate of: http://stackoverflow.com/q/21578149

http://stackoverflow.com/comment/89510248
comment on: http://stackoverflow.com/q/51265427
has text: Yes, correct. Got it.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51182336
downvote count: 2
upvote count: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51182316
has body: It's working for me. Try it: #!/usr/bin/env python import serial from time import sleep import math port = '/dev/ttyAMA0' baud = 9600 timeout = 5 ser = serial.Serial(port=port, baudrate=baud, timeout=timeout) You can also refer to the link https://www.raspberrypi.org/forums/viewtopic.php?t=87465
type: Answer
accepted answer of: http://stackoverflow.com/q/51182316
score: -2

http://stackoverflow.com/q/51200900
has comment: http://stackoverflow.com/comment/89383439
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/89383583
type: Question
has comment: http://stackoverflow.com/comment/89383451
score: 0
has answer: http://stackoverflow.com/a/51203654
answer count: 1
linked to: http://stackoverflow.com/q/36668467
tagged with: gpu
tagged with: python
has title: How can I change which GPU (s) a TensorFlow program may use while the TensorFlow program is running?
has body: One can use the environment variable CUDA_VISIBLE_DEVICES to specify which GPU (s) may TensorFlow use before the TensorFlow program starts, e.g. CUDA_VISIBLE_DEVICES=1 python my_script.py. How can I change which GPU (s) a TensorFlow program may use while it is running? I know that one could change the program to have checkpoints and rerun the TensorFlow program from these checkpoints with CUDA_VISIBLE_DEVICES specifying which GPUs to use, but I wonder if there is some way to avoid relying on the program having checkpoints.
type: UnansweredQuestion

http://stackoverflow.com/q/51297844
accepted answer: http://stackoverflow.com/a/51297987
tagged with: datetime
tagged with: python
has title: How many hours between two time?(unsupported operand type(s) for -: 'datetime.time' and 'datetime.time')
answer count: 4
downvote count: 0
has body: I tried to calculate how many hours between 10:49 and 16:38 by the type of float. import datetime t1 = datetime.time(10,49,00) t2 = datetime.time(16,38,00) t = (t2 - t1).hours
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/51298959
has answer: http://stackoverflow.com/a/51297955
has answer: http://stackoverflow.com/a/51298032
type: Question
upvote count: 3
possible better answer: http://stackoverflow.com/a/51297955
favorite count: 0
has answer: http://stackoverflow.com/a/51297987

http://stackoverflow.com/a/51232323
upvote count: 4
downvote count: 0
type: Answer
has body: This is a bug in Python that was caused in the 2.7 release line by https://bugs.python.org/issue27330 and fixed in https://bugs.python.org/issue29082 . It exists in 2.7.13 and is fixed in 2.7.14. keyboard triggers this bug by using from __future__ import unicode_literals in keyboard._winkeyboard.
answers question: http://stackoverflow.com/q/51232002
has comment: http://stackoverflow.com/comment/89443780
score: 4

http://stackoverflow.com/comment/89388715
score: 0
comment on: http://stackoverflow.com/q/51203779
type: Comment
type: QuestionComment
has text: I mean the output need to be converted into the matrix form. `X [matrix([[0], [0], [0], [1]]), matrix([[0], [0], [1], [0]]), matrix([[0], [0], [1], [0]])`

http://stackoverflow.com/comment/89560606
type: Comment
has text: You could use a list comprehension too: `l = [number for number in my_randoms if number%3 == 0]`
comment on: http://stackoverflow.com/a/51291447
score: 1
type: AnswerComment

http://stackoverflow.com/comment/89627183
score: 0
type: AnswerComment
type: Comment
has text: This works fine for a smaller data set, but for a dataset with 220625 records, it is very slow. Any better solution which is fast is much appreciated. Any suggestions?
comment on: http://stackoverflow.com/a/51324461

http://stackoverflow.com/comment/89497815
score: 0
type: Comment
has text: Thank you so much, that helped me out completely!
type: AnswerComment
comment on: http://stackoverflow.com/a/51259235

http://stackoverflow.com/comment/89352304
type: Comment
comment on: http://stackoverflow.com/q/51185004
score: 0
has text: What are the **exact** values of `start.FileName` and `start.Arguments` and `start.WorkingDirectory`? _Please debug and check - don't guess._
type: QuestionComment

http://stackoverflow.com/q/51310577
has comment: http://stackoverflow.com/comment/89598085
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/89597869
type: AnsweredQuestion
tagged with: django-templates
has comment: http://stackoverflow.com/comment/89598921
has comment: http://stackoverflow.com/comment/89599075
has comment: http://stackoverflow.com/comment/89599273
has title: Unable to display the image through the result of CRUD operations in django
type: Question
has answer: http://stackoverflow.com/a/51311487
accepted answer: http://stackoverflow.com/a/51311487
score: 0
has body: i am working on hotel booking app , in this i want to display the image of a hotel, based on user entered location . In this if i am displaying all hotels , i am able to display an image , if i am trying to displaying an image through some CRUD operations, i am unable to display it. Here are my code snippets. class Customer_details(models.Model): Name = models.CharField(max_length=128) Age = models.IntegerField() Mobile_number = models.IntegerField() Email = models.EmailField() Address = models.CharField(max_length=50) Special_request = models.CharField(max_length=50, blank=True) user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.Name hotel_rating_choices = ( ('1','1'), ('2','2'), ('3','3'), ('4','4'), ('5','5'), ('6','6'), ('7','7'), ) class Hotel(models.Model): Hotel_Name = models.CharField(max_length=50) location = models.CharField(max_length=20) no_of_rooms = models.IntegerField() rating = models.CharField(max_length=1, choices=hotel_rating_choices, default=3) hotel_img = models.ImageField(upload_to='hotel_images/') uploaded_at = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.Hotel_Name class Hotel_image(models.Model): hotel_img = models.ImageField(upload_to = 'hotel_images/') hotel = models.ForeignKey(Hotel, on_delete=models.CASCADE) def __str__(self): return self.hotel Ignore the remaining models just concentrate on Hotel model . `Below code snippet is my view regarding to query. def get_hotels_by_location(request): location = request.POST.get('location') print(location) location = location.lower() result = Hotel.objects.values('Hotel_Name', 'rating', 'hotel_img').filter(location=location) context = {'hotels': result, 'header': ['Hotel_Name', 'Rating', 'image'] } return render( request, template_name='display_hotel_by_location.html', context=context ) And below is my django html template {% for i in header %} {{ i }} {% endfor %} {% for element…
answer count: 1
has comment: http://stackoverflow.com/comment/89598029
has comment: http://stackoverflow.com/comment/89598558

http://stackoverflow.com/a/51295195
has body: I think you just forget to assign it back df.numbers=df.numbers.replace('XX',np.NaN)
answers question: http://stackoverflow.com/q/51295136
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/89567988
has comment: http://stackoverflow.com/comment/89567916
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/51295136

http://stackoverflow.com/q/51286403
linked to: http://stackoverflow.com/q/17677127
favorite count: 0
has comment: http://stackoverflow.com/comment/89552212
type: UnansweredQuestion
tagged with: python
tagged with: selenium-webdriver
tagged with: internet-explorer
has title: How to use DesiredCapabilities class through IEDriverServer in Selenium and Python
tagged with: selenium
has body: I have been struggling with a simple python script working in IE11 for some reason it was unable to find any elemnt, however by setting some desired capabilities in a java code it worked: System.setProperty("webdriver.ie.driver", "C:\\Python27\\IEDriverServer.exe"); DesiredCapabilities ieCapabilities = DesiredCapabilities.internetExplorer(); ieCapabilities.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS,true); WebDriver driver = new InternetExplorerDriver(ieCapabilities);// driver.navigate().to("http://www.google.com"); WebElement search =driver.findElement(By.name("q")); search.sendKeys("selenium"); search.submit(); However, since I already wrote my tests in python I would like to use the same method in python: caps = DesiredCapabilities.INTERNETEXPLORER caps['executablePath'] = 'C:\\Python27\\IEDriverServer.exe' caps['InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS'] = True browser = webdriver.Ie(capabilities=caps) browser.get('https://google.com') search = WebDriverWait(browser,10).until(EC.presence_of_element_located((By.NAME, 'q'))) search.send_keys("selenium") search.submit() But for some reason, selenium is still unable to find the search bar, so I'm guessing the equivalent I wrote in python isn't right, can someone point me out to the right direction please?
tagged with: selenium-iedriver
type: Question
score: 5
has answer: http://stackoverflow.com/a/51287356
linked to: http://stackoverflow.com/q/51165929
upvote count: 5
downvote count: 0
answer count: 1

http://stackoverflow.com/comment/89546942
type: QuestionComment
has text: @DanielRoseman, is there good way to do this, may be overriding default getter setter ?
type: Comment
comment on: http://stackoverflow.com/q/51284801
score: 0

http://stackoverflow.com/comment/89550379
type: QuestionComment
comment on: http://stackoverflow.com/q/51286423
score: 4
has text: It does not take a parameter, it is simply a function taking no parameters.
type: Comment

http://stackoverflow.com/q/51265668
has comment: http://stackoverflow.com/comment/89510121
linked to: http://stackoverflow.com/q/33725862
has title: Connect to database in Remote machine - python - SQL Server
has answer: http://stackoverflow.com/a/59539902
has answer: http://stackoverflow.com/a/51267770
downvote count: 0
type: UnansweredQuestion
favorite count: 0
has comment: http://stackoverflow.com/comment/89509797
tagged with: sql-server
type: Question
has body: I have a database server which can be accessed by Remote desktop login to the server machine. This is what we do manually: Login with Remote desktop to the machine from local. Open Database client in the connected machine. Then connect to database. Now, I need to connect to this DB using python. What I already tried?.. below works for all DB that I connect without remote. conn = pyodbc.connect("DRIVER={ODBC Driver 17 for SQL Server};SERVER=&lt;server name&gt;;database=&lt;DB name&gt;;UID=&lt;user&gt;;PWD=&lt;pwd&gt;") Error: pyodbc.OperationalError: ('08001', u'[08001] [Microsoft][ODBC Driver 17 for SQL Server]Named Pipes Provider: Could not open a connection to SQL Server [53]. (53) (SQLDriverConnect); [08001] [Microsoft][ODBC Driver 17 for SQL Server]Login timeout expired (0); [08001] [Microsoft][ODBC Driver 17 for SQL Server]A network-related or instance-specific error has occurred while establishing a connection to SQL Server. Server is not found or not accessible. Check if instance name is correct and if SQL Server is configured to allow remote connections. For more information see SQL Server Books Online. (53)')
score: 1
answer count: 2
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/89509984

http://stackoverflow.com/q/51258571
tagged with: apscheduler
accepted answer: http://stackoverflow.com/a/51393702
has comment: http://stackoverflow.com/comment/89613736
score: 0
has answer: http://stackoverflow.com/a/51338008
has title: import a class method from file as static in python
possible better answer: http://stackoverflow.com/a/51338008
has comment: http://stackoverflow.com/comment/89519057
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51393702
has body: Actually, I couldn't find a proper topic. I'm trying to use the Apscheduler library. I created a class method for the library and added some missing features by myself as a whole new scheduler library. When using an SQLAlchemyJobStore the added functions to scheduler must be serializable but as I created a new class the added functions are members of the class itself. For example, suppose this code: from datetime import datetime from time import sleep from apscheduler.schedulers.background import BackgroundScheduler from apscheduler.jobstores.sqlalchemy import SQLAlchemyJobStore class sched: def __init__(self): jobstores = { 'default': SQLAlchemyJobStore(url='sqlite:///test.db') } self.scheduler = BackgroundScheduler(jobstores=jobstores) def add_func(self, some_func, args={}, kwargs={}): self.scheduler.add_job( some_func, 'interval', args=args, kwargs=kwargs, seconds=5, replace_existing=True) def start(self): self.scheduler.start() def tick(self, i, j, **kwargs): print("hello{} {}".format(i, j)) for k in kwargs: print(k, ":", kwargs[k]) if __name__ == '__main__': schedule = sched() schedule.start() schedule.add_func(schedule.tick, args=[1, 2], kwargs=dict(a=1, b=2)) # using the following three lines solve the problem # sched = sched() # sched.start() # sched.add_func(sched.tick, args=[1, 2], kwargs=dict(a=1, b=2)) while True: sleep(.1) Traceback (most recent call last): File "...\Python36\lib\site-packages\apscheduler\executors\base.py", line 125, in run_job retval = job.func(*job.args, **job.kwargs) TypeError: tick() missing 1 required positional argument: 'j' This error means the whole class cannot be serialized but if I name my instance same as class name (here sched) it would be fixed. In the example, the tick function must be a member of schedule class itself because in my original class scheduler.add_job gets a modified function from the class methods and currently, I don't want to edit my new schedule class entirely. My question is when I want to import the c…
type: Question
answer count: 2

http://stackoverflow.com/comment/89516055
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51268694
has text: Maybe the documentation regarding string composition might help; I'm not particularly familiar with this package, unfortunately http://initd.org/psycopg/docs/sql.html

http://stackoverflow.com/q/51282714
has answer: http://stackoverflow.com/a/72465813
tagged with: python
favorite count: 0
tagged with: parquet
has body: Is there a way to divide a huge parquet file into smaller ones (using Python)? Keeping all the columns and dividing rows? Thank you
type: UnansweredQuestion
downvote count: 1
upvote count: 6
type: Question
has title: divide a parquet file into 3 parquet files using python
answer count: 2
score: 5
has answer: http://stackoverflow.com/a/51283979

http://stackoverflow.com/comment/89591564
score: 1
type: Comment
type: QuestionComment
has text: Please include both your code and the errors in the question. Also, please keep the question plain and only what is relevant to your problem.
comment on: http://stackoverflow.com/q/51307435

http://stackoverflow.com/a/51301802
has body: erikbern commented on 27 Aug 2015 at GitHub: Tasks are already singletons (instantiated with the same parameters).
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/51301413
score: 1
answers question: http://stackoverflow.com/q/51301413
upvote count: 1

http://stackoverflow.com/a/51303054
type: Answer
has comment: http://stackoverflow.com/comment/89587192
accepted answer of: http://stackoverflow.com/q/51302820
upvote count: 2
has comment: http://stackoverflow.com/comment/89583787
has comment: http://stackoverflow.com/comment/89584066
score: 2
has body: You should not be using pd.Series.map or manual row iteration for simple Boolean conditions. Instead, you can use numpy.where. For example, replace the following... a = df['man'].map(lambda x: (df['01-18']+df['02-18']+df['03-18']) if x == True \ else (df['01-18']+df['02-18']+df['03-18'])/3 ) ...with vectorised logic: sums_1_2_3 = df[['01-18', '02-18', '03-18']].sum(axis=1) df['new_col'] = np.where(df['man'], sums_1_2_3, sums_1_2_3 / 3) Alternatively: sum_1_2_3 = df[['01-18', '02-18', '03-18']].sum(axis=1) mean_1_2_3 = df[['01-18', '02-18', '03-18']].mean(axis=1) df['new_col'] = np.where(df['man'], sum_1_2_3, mean_1_2_3) As well as making your code cleaner, this will ensure you are utilizing the NumPy arrays underlying your Pandas dataframe. You will see significant performance benefits versus pd.Series.map + lambda, which is just a thinly veiled loop.
has comment: http://stackoverflow.com/comment/89583820
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51302820

http://stackoverflow.com/q/51280179
type: UnansweredQuestion
score: 7
has title: Celery fails to discover tasks in version 4.2.0
upvote count: 7
tagged with: celery
type: Question
downvote count: 0
favorite count: 0
has body: Here is the code which I use to start celery: from celery import Celery from foo.lib.config import app from foo.mods.bar.tract import Tesser from foo.mods.baz.commons import clean_data, quotify celery_app = Celery(app.name, broker=app.config["CELERY_BROKER_URL"]) celery_app.conf.update(app.config) celery_app.autodiscover_tasks() @celery_app.task def tract_task(content): return Tesser.tesseract(content) @celery_app.task def clean_data_task(content): return clean_data(content) @celery_app.task def quotify_task(content): return quotify(content) I start the worker using this command: celery worker -A celery_tasks.celery_app -l=info This used to work flawlessly before but when I upgraded celery to 4.2.0 I get the following error: Traceback (most recent call last): File "/home/minister/.local/bin/celery", line 11, in &lt;module&gt; sys.exit(main()) File "/home/minister/.local/lib/python3.5/site-packages/celery/__main__.py", line 16, in main _main() File "/home/minister/.local/lib/python3.5/site-packages/celery/bin/celery.py", line 322, in main cmd.execute_from_commandline(argv) File "/home/minister/.local/lib/python3.5/site-packages/celery/bin/celery.py", line 496, in execute_from_commandline super(CeleryCommand, self).execute_from_commandline(argv))) File "/home/minister/.local/lib/python3.5/site-packages/celery/bin/base.py", line 275, in execute_from_commandline return self.handle_argv(self.prog_name, argv[1:]) File "/home/minister/.local/lib/python3.5/site-packages/celery/bin/celery.py", line 488, in handle_argv return self.execute(command, argv) File "/home/minister/.local/lib/python3.5/site-packages/celery/bin/celery.py", line 420, in execute ).run_from_argv(self.prog_name, argv[1:], command=argv[0]) File "/home/minister/.local/lib/python3.5/site-packages/celery/bin/worker.py", line 223, in run_from_argv return self(*args, **options) File "/home/minister/.local/lib/python3.5/site-packages/celery/bin/base.py", line 238, in __call__ ret = self.run(*args, **kwargs) File…
tagged with: python
answer count: 0

http://stackoverflow.com/comment/89579324
has text: Possible duplicate of [Parse JSON in Python](https://stackoverflow.com/questions/7771011/parse-json-in-python)
comment on: http://stackoverflow.com/q/51301150
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/comment/89435547
comment on: http://stackoverflow.com/q/51227784
score: 0
type: Comment
has text: @ScottBoston added input and actual vs expected output
type: QuestionComment

http://stackoverflow.com/q/51302477
has comment: http://stackoverflow.com/comment/89583539
accepted answer: http://stackoverflow.com/a/51303224
has comment: http://stackoverflow.com/comment/89583926
has comment: http://stackoverflow.com/comment/89583709
answer count: 1
has comment: http://stackoverflow.com/comment/89583815
score: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/89584190
favorite count: 0
has comment: http://stackoverflow.com/comment/89582234
has title: Pandas: Maintain a column after aggregation
has comment: http://stackoverflow.com/comment/89584100
has body: I have a data look like as below: The code used to build it is as follows: Data = pd.DataFrame({'Customer_ID':[1,2,3,4,5,1,2,3,4,5], 'Product_ID':['A','D','C','A','E','B','D','C','B','E'], 'SalesAmount':[12.34,13.55,34.00, 19.15,13.22,12.34,13.55,34.00, 19.15,13.22], 'ProductCost' : [12.34,13.55,34.00, 19.15,13.22,12.34,13.55,34.00, 19.15,13.22]}) My question is, how would I maintain a column after aggregation of columns needed ? In my case I want to have the column Product_ID in the data after aggregation. The code and the result I used to aggregate are as follows: Data_aggr = Data.groupby('Customer_ID').agg({'SalesAmount':[min,sum], 'ProductCost':['mean',max] },'Product_ID') Data_aggr.columns = ["_".join(x) for x in Data_aggr.columns.ravel()] Data_aggr.index.name='Customer_ID' Data_aggr.reset_index(inplace=True) Data_aggr Result: My desired output is :
has answer: http://stackoverflow.com/a/51303224
has comment: http://stackoverflow.com/comment/89583932
upvote count: 1
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89583466
downvote count: 1
type: Question

http://stackoverflow.com/comment/89431104
comment on: http://stackoverflow.com/q/51225355
score: 2
has text: The `j` is recognized by Python's parser, exactly the same way that quote marks are recognized as the start of a string, or digits are recognized as part of a number. The only way to add another such feature would be to edit Python's source code and recompile it. Defining a function or class (`P(x)`, perhaps) would be a much more reasonable way to accomplish this.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51319801
possible better answer: http://stackoverflow.com/a/51319837
has answer: http://stackoverflow.com/a/51319980
downvote count: 3
has body: I have a query that gives a result as given below. abc=[(1531,), (4325,), (9204,)] How do I convert it into a list as below? def=['1531','4325','9204'] I will always have integer and not string as my result.
upvote count: 1
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51319909
accepted answer: http://stackoverflow.com/a/51319909
has comment: http://stackoverflow.com/comment/89615457
answer count: 5
has title: Convert a query result into a list using python
tagged with: python
has answer: http://stackoverflow.com/a/51319837
has answer: http://stackoverflow.com/a/51319838
type: AnsweredQuestion
tagged with: list
has answer: http://stackoverflow.com/a/51319969
type: Question
has comment: http://stackoverflow.com/comment/89615530
has comment: http://stackoverflow.com/comment/89615283
score: -2

http://stackoverflow.com/comment/89371610
has text: Just as a tip, I **strongly** recommend never using pylab in real code. Pylab is just a namespace clutter for matplotlib's pyplot and numpy smooshed together, see [this answer](https://stackoverflow.com/a/46761217/3100515). If what you want is simply a power spectral density, there are plenty of options in scipy or you can make your own with an fft.
score: 0
comment on: http://stackoverflow.com/q/51194727
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51310246
has body: I am attempting to get Python.net (pythonnet) working on Python 3.7 and when running the setup.py it fails with the following error. I'm assuming that it has to do with a missing entry in the path lines but I coulnd't fine any reference to it. It's basically a pretty plain install of Python 3.7 on Windows 7. the pip install also fails with the same results. Does anyone have a suggestion on what path or file might be missing? PS C:\Users\user\pythonnet-master\pythonnet-master&gt; python setup.py bdist_wheel running bdist_wheel running build running build_ext Checking for updates from https://www.nuget.org/api/v2/. Currently running NuGet.exe 4.6.2. NuGet.exe is up to date. MSBuild auto-detection: using msbuild version '15.5.180.51428' from 'C:\Program Files (x86)\Microsoft Visual Studio\2017 \Professional\MSBuild\15.0\bin'. All packages listed in packages.config are already installed. Traceback (most recent call last): File "tools\geninterop\geninterop.py", line 292, in &lt;module&gt; sys.exit(main()) File "tools\geninterop\geninterop.py", line 272, in main python_h = preprocess_python_headers() File "tools\geninterop\geninterop.py", line 192, in preprocess_python_headers for line in _check_output(cmd).splitlines(): File "tools\geninterop\geninterop.py", line 41, in _check_output output = subprocess.check_output(*args, **kwargs) File "C:\Users\i102604\AppData\Local\Programs\Python\Python37\lib\subprocess.py", line 376, in check_output **kwargs).stdout File "C:\Users\i102604\AppData\Local\Programs\Python\Python37\lib\subprocess.py", line 453, in run with Popen(*popenargs, **kwargs) as process: File "C:\Users\i102604\AppData\Local\Programs\Python\Python37\lib\subprocess.py", line 756, in __init__ restore_signals, start_new_session) File "C:\Users\i102604\AppData\Local\Programs\Python\Python37\lib\subprocess.py", line 1155, in _execute_child startupinfo) FileNotFoundError: [WinError 2] The system cannot find the file specified
has title: Error Installing Python.net on Python 3.7
has comment: http://stackoverflow.com/comment/115189557
tagged with: python
answer count: 0
tagged with: installation
has comment: http://stackoverflow.com/comment/89601199
upvote count: 3
type: UnansweredQuestion
type: Question
score: 3
tagged with: python.net
has comment: http://stackoverflow.com/comment/89604154
tagged with: python-3.7
has comment: http://stackoverflow.com/comment/93080954
downvote count: 0
tagged with: .net
favorite count: 0

http://stackoverflow.com/q/51256449
type: Question
has body: I have these 3 paths in my urls.py: urlpatterns = [ ... path("stuff/&lt;str:name&gt;/", views.stuff), path("stuff/&lt;str:name&gt;/&lt;str:color&gt;/", views.colored_stuff), path("stuff/&lt;str:name&gt;/&lt;str:color&gt;/&lt;str:size&gt;/", views.sized_colored_stuff), ] and these corresponding methods in views.py: def stuff(request, name): ... def colored_stuff(request, name, color): ... def sized_colored_stuff(request, name, color, size): ... If I call https://example.com/stuff/Oak/Red/Big, the third path is called, which makes sense. However, then when I try to hit https://example.com/stuff/Birch then request still goes to the third path instead of the first. Any idea why and how to fix it?
has comment: http://stackoverflow.com/comment/89493231
has comment: http://stackoverflow.com/comment/89494902
has comment: http://stackoverflow.com/comment/89492794
has comment: http://stackoverflow.com/comment/89493270
has comment: http://stackoverflow.com/comment/89494234
tagged with: django
tagged with: python
answer count: 0
type: UnansweredQuestion
has title: Django calls wrong path after calling long path first
score: 0

http://stackoverflow.com/q/51229870
type: UnansweredQuestion
tagged with: python
tagged with: recursion
tagged with: http://stackoverflow.com/tag/json
has answer: http://stackoverflow.com/a/51230009
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/51229930
has title: Why is my python loop not breaking?
score: 0
has body: I wrote a recursive function to walk through a JSON string that is loaded to a python dict. I am trying to stop when I find the final desired key in the JSON structure. I explicitly have a break statement in that spot but it appears not to be breaking. I am stumped as to why this continues. I have included the output below but this is a working python2 example. I put the sample JSON string in a gist. import urllib2 import json # This is loading the JSON url ="https://gist.githubusercontent.com/mroth00/0d5c6eb6fa0a086527ce29346371d8ff/raw/700d28af12184657eabead7542738f27ad235677/test2.json" example = urllib2.urlopen(url).read() d = json.loads(example) # This function navigates the JSON structure def j_walk(json_input,dict_keys): for key, values in json_input.items(): #print(index) if (key != dict_keys[0]): print("passing") print(key) continue elif ((key == dict_keys[0]) and (len(dict_keys)&gt;1) and (values is None)): return 'missingValue' elif ((key == dict_keys[0]) and (len(dict_keys)==1) and (values is None)): return 'missingValue' elif ((key == dict_keys[0]) and (len(dict_keys)==1)): print(key) print(dict_keys[0]) print(len(dict_keys)) print("i made it") print values break elif ((key == dict_keys[0]) and (len(dict_keys)&gt;1)): print(len(dict_keys)) #print(values) j_walk(values,dict_keys[1:]) else: return 'somethingVeryWrong' # Run the function here: j_walk(d,['entities','hashtags']) Output, it should break after "i made it" and printing the value but it keeps going: passing user passing truncated passing text passing created_at 2 passing symbols passing user_mentions hashtags hashtags 1 i made it [{u'indices': [103, 111], u'text': u'Angular'}] passing id_str passing id passing source
tagged with: break

http://stackoverflow.com/comment/89621396
comment on: http://stackoverflow.com/a/51306266
has text: Strange, that would imply there is no `max_duration >= 30`. In my example it worked :)
type: AnswerComment
type: Comment
score: 0

http://stackoverflow.com/comment/89421746
type: Comment
has text: Wow thanks for all the resources! I'll check out curses, it sounds like the best option right now.
comment on: http://stackoverflow.com/a/51220444
score: 0
type: AnswerComment

http://stackoverflow.com/q/51278974
has body: I want to change CKAN registration logic, so I inherited from the CKAN UserController class and registered it as a route, but when I try to view the page, the registration form is empty. It shows only header, footer and the title of the form. I didn't create a ./user/new.html file, so I'm still using the ckan template file. My plugin.py file from ckan.config.routing import SubMapper class AuthPlugin(plugins.SingletonPlugin): plugins.implements(plugins.IConfigurer) plugins.implements(IRoutes, inherit=True) def update_config(self, config_): toolkit.add_template_directory(config_, 'templates') toolkit.add_public_directory(config_, 'public') toolkit.add_resource('fanstatic', 'auth') def before_map(self, map): user_controller = 'ckanext.auth.controllers.user:UserController' with SubMapper(map, controller=user_controller) as m: m.connect('/user/register', action='register') return map User controller class: from ckan.controllers.user import UserController as CoreUserController class UserController(CoreUserController): def register(self, data=None, errors=None, error_summary=None): return super(UserController, self).register(data, errors, error_summary) What should I do to make this work? P.S: As I think the bug is in the ckan ./templates/user.html file, which has a tag. There must be a some kind of context or something that I should set in my controller in order to make it work. P.S.2: Strange thing is when I do the same thing for Organization controller, it works!!! Thanks
answer count: 0
downvote count: 0
type: UnansweredQuestion
tagged with: flask
has title: CKAN: View is empty when inherited from a base controller
upvote count: 4
favorite count: 0
type: Question
tagged with: python
tagged with: ckan
score: 4
tagged with: jinja2

http://stackoverflow.com/q/51256280
tagged with: pandas
has title: Unpacking Nested List in Python to a DataFrame (Unsuccessful)
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89491423
has comment: http://stackoverflow.com/comment/89492992
linked to: http://stackoverflow.com/q/952914
answer count: 0
score: 0
tagged with: dataframe
has body: I have written a function which takes in data from a database, returns this into a list which then has the following format: df_master = [] #x = arbitrary data from DB for i in db_list: df_tmp = df_tmp.append(ReadDBValues(i, interval, start_date, end_date)) df_master.append(df_tmp) However, this also means flattening the data is somewhat troublesome. I have used the following approach: flat = [item for sublist in df_master for item in sublist] Which yields [1,0,0,1] as in, it returns the 4 columns but not the associated values with each column. I was hoping to be able to convert this into a dataframe as such: W | X | Y | Z .... 1 | 2 | 3 | 4 ... | | | .... I have been using this as my reference: Making a flat list out of list of lists in Python But, I can't seem to flatten more than the first two columns. Could I please get any further guidance? Thank you very much. EDIT: I have now managed to create a 'unique' index for the data so I retain the column names. However, the problem is that say there are two columns; 1400 rows in the first column and 1400 in the second. The code will do the following: Date | Val X | Val Y .... 1398 NaN .... 1399 NaN 1400 NaN NaN 1 NaN 2 When instead it should be: Date | Val X | Val Y .... 1398 523 .... 1399 242 1400 112 Any ideas? EDIT: Using a GroupBy Index has not proven successful either and results in just NaN values appearing. (df_master.groupby(df_master.index).sum()) Can anyone please point me in the right direction?
has comment: http://stackoverflow.com/comment/89491482
type: Question

http://stackoverflow.com/comment/89547986
type: QuestionComment
comment on: http://stackoverflow.com/q/51273823
has text: Yes it would if there are errors. But try the last row. I think you error lies in a missplaced `-`. **%Y-%m-%d**
score: 0
type: Comment

http://stackoverflow.com/a/51185969
type: Answer
has comment: http://stackoverflow.com/comment/89361306
score: 2
downvote count: 0
has body: Try this piece of code word_vec = {} # col 1 is the word, col 2 is the score, col 3 is the number of times it occurs for i in range(len(data)): sentence = data['SurveyResponse'][i].split(' ') for word in sentence: word_vec['word'] = word if word in word_vec: word_vec[word]['Score'] += data['SCORE'][i] # Keep accumulating the total score for each word, would be easier to find the average score later on word_vec[word]['NumberOfTimes'] += 1 else: word_vec[word] = {'Score':data['SCORE'][i], 'NumberOfTimes':1} To increment the value of 'NumberOfTimes', you can directly increment like this word_vec[word]['NumberOfTimes'] += 1
upvote count: 2
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89356829
answers question: http://stackoverflow.com/q/51185830
accepted answer of: http://stackoverflow.com/q/51185830

http://stackoverflow.com/comment/89410428
score: 0
comment on: http://stackoverflow.com/q/51214638
type: QuestionComment
type: Comment
has text: You don't need privileges in order to install software with `pip`. Read up on the `--user` option, or possibly learn about Python virtual environments.

http://stackoverflow.com/comment/89350428
score: 4
type: Comment
type: QuestionComment
has text: No no no no no. You ***really*** don't want to do this with regex.
comment on: http://stackoverflow.com/q/51184305

http://stackoverflow.com/comment/89539175
score: 2
comment on: http://stackoverflow.com/q/51280942
type: QuestionComment
type: Comment
has text: The difference of 2.3 µs is not relevant.

http://stackoverflow.com/comment/89590556
type: AnswerComment
has text: {/home/scott/anaconda3/lib/python3.6/site-packages/pandas/core/indexing.py:1472: FutureWarning: Passing list-likes to .loc or [] with any missing label will raise KeyError in the future, you can use .reindex() as an alternative.} in pandas 0.23.0
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51306894

http://stackoverflow.com/comment/89553294
score: 0
comment on: http://stackoverflow.com/a/51287475
has text: I think there is something wrong with my version of tkinter, because it shows a very basic dialog window and it does not go to the default directory for some reason.
type: AnswerComment
type: Comment

http://stackoverflow.com/a/55225350
score: 2
downvote count: 0
type: Answer
has body: You can apply: YOUR_TARGET.to_pydatetime() EXP: In [1]: type(pd.date_range('2018-01', '2020-05', freq='M')[0]) Out[1]: pandas._libs.tslibs.timestamps.Timestamp In [62]: type(pd.date_range('2018-01', '2020-05', freq='M')[0].to_pydatetime()) Out[62]: datetime.datetime I think that is what you need right?
upvote count: 2
answers question: http://stackoverflow.com/q/51268799

http://stackoverflow.com/comment/89497436
has text: Ah ok - I interpreted OP's request as needing two ranges, not three, in your example. Thanks for clarifying!
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51257099

http://stackoverflow.com/comment/89354045
score: 1
comment on: http://stackoverflow.com/q/51186004
type: Comment
type: QuestionComment
has text: That looks like a simple regex replace issue... Just place new line feed before the IP Address for each except the first one..

http://stackoverflow.com/comment/89358903
comment on: http://stackoverflow.com/q/51181129
type: Comment
type: QuestionComment
has text: @WarrenWeckesser-yes there is inf data in gpoa. and we use gpoa.replace(np.inf,(gpoa.mean()). But this cannot kill all inf data, there are still inf data there, we checked.
score: 0

http://stackoverflow.com/q/51314944
has comment: http://stackoverflow.com/comment/89606756
downvote count: 0
has comment: http://stackoverflow.com/comment/89610969
favorite count: 0
has comment: http://stackoverflow.com/comment/89606775
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51315668
answer count: 3
tagged with: while-loop
has title: Python homework with while loops to print output
has answer: http://stackoverflow.com/a/51315002
tagged with: python
type: UnansweredQuestion
upvote count: 3
has answer: http://stackoverflow.com/a/51317022
has comment: http://stackoverflow.com/comment/89606591
has comment: http://stackoverflow.com/comment/89606508
score: 3
has body: I am trying to learn 'while' loops and counters. I understand how to use them on a basic level but I feel like I'm over using them in this case and there may be a better beginner answer that still uses while loops and if/elif/else statements. Basically the program should print each sentence in a verse based on the counter starting at 0 and printing sentence1, then after the 4th sentence it prints the chorus... Then it moves on to print the next 4 sentences and then the chorus twice at the end. This is where I'm at now, but like I mentioned I feel like I'm over using the while loops making it simpler and it kind of feels like cheating. ver1 = ['sentence1', 'sentence2', 'sentence3', 'sentence4'] ver2 = ['sentence5', 'sentence6', 'sentence7', 'sentence8'] chor1= ['chorus1', 'chorus2'] counter = 0 while counter == 0: print(ver1[0]) counter += 1 while counter == 1: print(ver1[1]) counter += 1 while counter == 2: print(ver1[2]) counter += 1 while counter == 3: print(ver1[3]) counter += 1 #this if statement was my decision just to see if I could use it properly, but I'd like to do the entire thing with while loops if possible....but using if/elif/else statements isn't forbidden. if counter &gt;= 5: print(ver1[3]) else: print(chor1[0]) I created it with if statements to start with but the teacher asked if I'd try making it with while loops as a homework assignment... Here is the original if/elif/else statement that I wrote. verse1 = "I came home and my dog was gone" verse2 = "She took my dog and my truck" verse3 = "oh no she didn't" chorus = "ohh how times have changed" truck = 'gone' dog = 'gone' if dog == "gone": print (verse1) print (chorus) else: print(verse3) if truck == 'gone': print (verse2) print (chorus) else: print (verse3) This is just the first part of the program because I didn't want to continue with it and waste my time if there was a better answer than just copy/pasting while loops with a couple small edits to determine what gets printed.
type: Question

http://stackoverflow.com/a/51182057
accepted answer of: http://stackoverflow.com/q/51181949
answers question: http://stackoverflow.com/q/51181949
score: 1
has comment: http://stackoverflow.com/comment/89346433
has body: @Anthony, your second code block with links should work, it just looks like you have a copy/paste bug: for link in links: browser.get(href.get_attribute('href')) should be for link in links: browser.get(link) ...
type: AcceptedAnswer
downvote count: 0
upvote count: 1
type: Answer

http://stackoverflow.com/a/51199284
has comment: http://stackoverflow.com/comment/89381089
answers question: http://stackoverflow.com/q/51199226
has body: Try this: from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.ui import WebDriverWait company_id = WebDriverWait(driver, 10).until( EC.presence_of_element_located((By.XPATH, "//*[@id='SearchTopBar']")) ) it will wait until element will be present in DOM Full code: from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.ui import WebDriverWait company_list = open('Company_List.txt') for line in company_list: company_id = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, "//*[@id='SearchTopBar']"))) company_id.send_keys(line) company_id.send_keys(Keys.ENTER) driver.implicitly_wait(10) driver.find_element_by_xpath('//*[@id="CompanyHeaderInfo_TearSheetReport_ReportImage"]/div/img').click() driver.implicitly_wait(10)
has comment: http://stackoverflow.com/comment/89380450
score: 0
has comment: http://stackoverflow.com/comment/89381170
has comment: http://stackoverflow.com/comment/89386598
type: Answer

http://stackoverflow.com/comment/89491940
score: 1
comment on: http://stackoverflow.com/q/51253378
type: Comment
type: QuestionComment
has text: Or https://metacpan.org/pod/IPC::System::Simple

http://stackoverflow.com/a/51188684
score: 2
downvote count: 0
has body: For mixed types, Pandas is a convenient option. Since your data is sorted, you only need to keep duplicates: import pandas as pd import numpy as np A = np.array([('I05', 'U13', 4), ('I12', 'U13', 5), ('I22', 'U13', 3), ('I03', 'U15', 5), ('I14', 'U23', 5), ('I12', 'U23', 2), ('I15', 'U43', 5)], dtype='object, object, i4') df = pd.DataFrame(A) B = df[df.duplicated(subset=['f1'], keep=False)].values print(B) array([['I05', 'U13', 4], ['I12', 'U13', 5], ['I22', 'U13', 3], ['I14', 'U23', 5], ['I12', 'U23', 2]], dtype=object) Note NumPy adds names automatically. This is a structured array, not an array of tuples: print(A) array([('I05', 'U13', 4), ('I12', 'U13', 5), ('I22', 'U13', 3), ('I03', 'U15', 5), ('I14', 'U23', 5), ('I12', 'U23', 2), ('I15', 'U43', 5)], dtype=[('f0', 'O'), ('f1', 'O'), ('f2', '&lt;i4')])
upvote count: 2
has comment: http://stackoverflow.com/comment/89359186
answers question: http://stackoverflow.com/q/51188406
has comment: http://stackoverflow.com/comment/89359055
has comment: http://stackoverflow.com/comment/89359003
type: Answer

http://stackoverflow.com/comment/89404350
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51201145
has text: Thanks John! Yes this would work, but in my case I have a huge number of instances (more than 15k) so this would be not as efficient. I posted another solution below after doing some research that I think would work very well too, using filters and using the wildcard character '*'.
score: 0

http://stackoverflow.com/a/51219564
score: 1
answers question: http://stackoverflow.com/q/51219365
has comment: http://stackoverflow.com/comment/89491665
has body: Try this, def get_queryset(self): return Blog.objects.filter(...you filter).values('author').annotate(blog_count=Count('id')).order_by('author')&lt;br&gt;&lt;br&gt; Equivalant SQL statement : SELECT COUNT(id) as blog_count, author FROM Blog GROUP BY author order by author;
upvote count: 1
type: Answer
downvote count: 0
has comment: http://stackoverflow.com/comment/89517766
has comment: http://stackoverflow.com/comment/89480882
has comment: http://stackoverflow.com/comment/89507794

http://stackoverflow.com/comment/89376583
has text: How do you know how to order these numbers? Dictionaries are not sorted in all versions of python
comment on: http://stackoverflow.com/q/51197439
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/comment/89586159
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51304581
has text: @Useless Yep, that's a solution. But, aren't there any other direct ways to achieve this?

http://stackoverflow.com/q/51205137
tagged with: django-admin
tagged with: django-models
has answer: http://stackoverflow.com/a/51299659
upvote count: 2
answer count: 1
favorite count: 0
has title: Django model update or create object with unique constraint
tagged with: python
score: 2
downvote count: 0
type: UnansweredQuestion
tagged with: django
tagged with: web-services
type: Question
has body: There is a model: class Proxy(models.Model): host = models.CharField(max_length=100,) port = models.CharField(max_length=10,) login = models.CharField(max_length=100,) password = models.CharField(max_length=100,) class Meta: unique_together = ("host", "port") I added batch of proxies in admin interface, and one of them is 0.0.0.0:0000, login=123, password=123. Then I add another batch of proxy, and one of them is the same 0.0.0.0:0000, but with new login=234 and password=234. Is any possibility to override save method of model to get behaviour like "insert ... on conflict (host, port) do update set login=login, password=password". Django 2, db - Postgres.

http://stackoverflow.com/q/51318547
has answer: http://stackoverflow.com/a/69790794
favorite count: 0
has answer: http://stackoverflow.com/a/79532591
answer count: 3
tagged with: mysql-python
tagged with: python
has title: Mysql - How to set skip_networking to off?
has body: I'm Trying to connect to Mysql server from python. and i'm getting the following error: Traceback (most recent call last): File "./db_connection.py", line 2, in &lt;module&gt; Con = MySQLdb.Connect(host="127.0.0.1",port= 3360, user="username", passwd="password", db="entries") File "/usr/lib64/python2.7/site-packages/MySQLdb/__init__.py", line 85, in Connect return Connection(*args, **kwargs) File "/usr/lib64/python2.7/site-packages/MySQLdb/connections.py", line 204, in __init__ super(Connection, self).__init__(*args, **kwargs2) _mysql_exceptions.OperationalError: (2003, "Can't connect to MySQL server on '127.0.0.1' (111)") I checked and my port is 0 : mysql&gt; show variables like 'port'; +---------------+-------+ | Variable_name | Value | +---------------+-------+ | port | 0 | +---------------+-------+ 1 row in set (0.01 sec) and skip_networking=ON: mysql&gt; SHOW VARIABLES LIKE 'skip_networking'; +-----------------+-------+ | Variable_name | Value | +-----------------+-------+ | skip_networking | ON | +-----------------+-------+ 1 row in set (0.00 sec) file my.cnf looks like that: [mysqld] skip-grant-tables datadir=/var/lib/mysql socket=/var/lib/mysql/mysql.sock log-error=/var/log/mysqld.log pid-file=/var/run/mysqld/mysqld.pid I tried to put skip-networking = Off and port=3360 and then restart mysql service and it didn't work- skip_networking is still on. Any suggestions on how to connect MySQL DB with python? Thanks!
type: UnansweredQuestion
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/54998631
tagged with: network-programming
score: 1
tagged with: database
tagged with: mysql
downvote count: 0

http://stackoverflow.com/comment/89357790
comment on: http://stackoverflow.com/q/51183411
type: Comment
type: QuestionComment
has text: this is the link to the image: https://i.sstatic.net/dVBTT.jpg
score: 0

http://stackoverflow.com/comment/89523623
score: 1
comment on: http://stackoverflow.com/q/51272748
has text: Please explain this `return("\n" ...` and how you expect anything afterwards to be executed.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51282144
answer count: 0
score: 0
tagged with: matplotlib
type: Question
has comment: http://stackoverflow.com/comment/89607882
tagged with: polar-coordinates
has comment: http://stackoverflow.com/comment/89542793
has body: I have a self organizing map which has been plotted in several ways (using u-matrix and component planes charts) but I don't know what to do in order to plot a chart like this (composed by several polar charts): I have a n-dimensional array which represents the trained SOM's neurons which is (56,56,6) where 6 is the input dimension, so each polar chart must have 6 "bars" representing the different attributes.
type: UnansweredQuestion
tagged with: python
tagged with: plot
has title: Plotting several polar charts using matplotlib for a SOM
tagged with: self-organizing-maps

http://stackoverflow.com/comment/89670422
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51308134
has text: revised answer & link to dox.

http://stackoverflow.com/a/51249652
has comment: http://stackoverflow.com/comment/89479081
has comment: http://stackoverflow.com/comment/89480009
downvote count: 0
has comment: http://stackoverflow.com/comment/89480204
score: 1
has comment: http://stackoverflow.com/comment/89480139
accepted answer of: http://stackoverflow.com/q/51249479
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/51249479
has body: Create a function compute_mode with a argument which takes in a list(in this case num_count). The function finds mode and stores them in a temp_list which is then printed out Append all the mode values to a list like this: temp_list.append(num) Then print the list like this: print("Mode: " ,temp_list) Final code: temp_list = [] def compute_mode(my_list): counts = {} maxcount = 0 for number in my_list: if number not in counts: counts[number] = 0 counts[number] += 1 if counts[number] &gt; maxcount: maxcount = counts[number] for number, count in counts.items(): if count == maxcount: temp_list.append(number) num_count = [1,2,3,4,1,2,3,4,4] #any list compute_mode(num_count) print('Mode:', temp_list)
has comment: http://stackoverflow.com/comment/89479919
has comment: http://stackoverflow.com/comment/89480035
type: AcceptedAnswer

http://stackoverflow.com/comment/89377784
score: 0
type: QuestionComment
has text: did you try to update it ? `pip install scikit-image --upgrade` maybe you have an old version
type: Comment
comment on: http://stackoverflow.com/q/51197683

http://stackoverflow.com/comment/89338259
comment on: http://stackoverflow.com/a/51177558
score: 0
type: AnswerComment
has text: isinstance(inspect, class_object) returns false and type(inspect) returns <type 'module'>
type: Comment

http://stackoverflow.com/a/51181845
upvote count: 1
score: 1
has body: The problem is the list need to updated automatically based on the value of the elements. Setting aside the rest of your question, which to me is unclear, you can achieve this goal via a dictionary. First define a dictionary mapping: d = {'11': 6, '01': 28, '00': 30, '10': 32} Then, using map or a list comprehension, apply the mapping to the elements of your list: # map res = list(map(d.get, split)) # list comprehension res = [d[i] for i in split] print(res) [6, 28, 30, 32, 28, 32, 6]
downvote count: 0
answers question: http://stackoverflow.com/q/51181327
has comment: http://stackoverflow.com/comment/89347062
type: Answer

http://stackoverflow.com/q/51284448
tagged with: lookbehind
has title: Convert a look-behind regex from python to javascript
tagged with: javascript
score: 0
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/89546281
has answer: http://stackoverflow.com/a/51284666
accepted answer: http://stackoverflow.com/a/51284666
has comment: http://stackoverflow.com/comment/89546292
duplicate of: http://stackoverflow.com/q/1396084
tagged with: python
tagged with: regex
type: AnsweredQuestion
has body: I have written a regex pattern with positive look-behind in python which matches a comma-separated list of mobile numbers. The pattern is: ^\+?[0-9]+((,?)(?(1)(\+?[0-9]+)))*$ It matches any mobile number regarding following constraints: Each phone number can start with +; any other + characters are forbidden. Each phone number can start with 00. Spaces are not acceptable; not middle spaces nor peripherals. My pattern works fine in python, but I want to convert it to javascript version in order to use it in an angular project. I googled about javascript look-behind regex, but I couldn't figure out how to make use of indexed look-behind in javascript; the ?(1) part. Is there any way to convert this python regex to javascript or any other equivalent regex to match my needs?
upvote count: 1
downvote count: 1
type: Question
linked to: http://stackoverflow.com/q/1396084
linked to: http://stackoverflow.com/q/7376238

http://stackoverflow.com/a/51300490
has body: It's easy with Pandas, use diff(): import pandas as pd pd.Series(numbers).diff() 0 NaN 1 2.530 2 2.119 3 2.888 dtype: float64
has comment: http://stackoverflow.com/comment/89580365
type: Answer
answers question: http://stackoverflow.com/q/51300431
has comment: http://stackoverflow.com/comment/89578305
score: 2
has comment: http://stackoverflow.com/comment/89578592
downvote count: 0
has comment: http://stackoverflow.com/comment/89578197
upvote count: 2

http://stackoverflow.com/a/51172983
accepted answer of: http://stackoverflow.com/q/51172789
has body: This looks very similar to a problem I have seen (and answered already). Looks like you have either a module or a Python program that's names the same as a system module: datetime.py (I see "C:\Users\user\Desktop\datetime.py" in your stack trace). There are many situations when this can lead to problems and should be avoided. See here for another example of the same situation: ModuleNotFoundError: No module named 'tensorflow.contrib'; 'tensorflow' is not a package
type: Answer
answers question: http://stackoverflow.com/q/51172789
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89330356

group-by
tags question: http://stackoverflow.com/q/51258807
tags question: http://stackoverflow.com/q/51216819
tags question: http://stackoverflow.com/q/51296431
tag name: group-by
tags question: http://stackoverflow.com/q/51183277
type: Tag
tags question: http://stackoverflow.com/q/51238000
tags question: http://stackoverflow.com/q/51199565
tags question: http://stackoverflow.com/q/51185748
tags question: http://stackoverflow.com/q/51254763
tags question: http://stackoverflow.com/q/51309258
tags question: http://stackoverflow.com/q/51286294

http://stackoverflow.com/q/51298992
tagged with: python
type: AnsweredQuestion
downvote count: 0
tagged with: tensorflow
has title: Binary classifier Keras callback for sensitivity and specificity?
type: Question
score: 1
tagged with: numpy
accepted answer: http://stackoverflow.com/a/51305919
has body: How do I get sensitivity and specificity, when class_mode='binary'? - My current solution works for class_mode='categorical': from keras.callbacks import Callback import numpy as np from sklearn.metrics import confusion_matrix class SensitivitySpecificityCallback(Callback): def on_epoch_end(self, epoch, logs=None): if epoch: x_test, y_test = self.validation_data[0], self.validation_data[1] predictions = self.model.predict(x_test) output_sensitivity_specificity(epoch, predictions, y_test) def output_sensitivity_specificity(epoch, predictions, y_test): y_test = np.argmax(y_test, axis=-1) predictions = np.argmax(predictions, axis=-1) c = confusion_matrix(y_test, predictions) print('Confusion matrix:\n', c) print('[{:03d}] sensitivity'.format(epoch), c[0, 0] / (c[0, 1] + c[0, 0])) print('[{:03d}] specificity'.format(epoch), c[1, 1] / (c[1, 1] + c[1, 0])) 82 source lines full code example (Python 2 &amp; 3 compatible) All the output is wrong: Confusion matrix: [[40]] Traceback (most recent call last): File "network.py", line 118, in &lt;module&gt; callbacks=[SensitivitySpecificityCallback()], verbose=1) File "lib/python2.7/site-packages/keras/legacy/interfaces.py", line 91, in wrapper return func(*args, **kwargs) File "lib/python2.7/site-packages/keras/engine/training.py", line 1426, in fit_generator initial_epoch=initial_epoch) File "lib/python2.7/site-packages/keras/engine/training_generator.py", line 229, in fit_generator callbacks.on_epoch_end(epoch, epoch_logs) File "lib/python2.7/site-packages/keras/callbacks.py", line 77, in on_epoch_end callback.on_epoch_end(epoch, logs) File "network.py", line 56, in on_epoch_end output_sensitivity_specificity(epoch, predictions, y_test) File "network.py", line 64, in output_sensitivity_specificity print('[{:03d}] sensitivity'.format(epoch), c[0, 0] / (c[0, 1] + c[0, 0])) IndexError: index 1 is out of bounds for axis 1 with size 1
upvote count: 1
answer count: 1
tagged with: scikit-learn
tagged with: keras
favorite count: 0
has answer: http://stackoverflow.com/a/51305919

http://stackoverflow.com/q/51199127
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51199624
upvote count: 1
tagged with: python
type: AnsweredQuestion
tagged with: virtualenvwrapper
type: Question
accepted answer: http://stackoverflow.com/a/51199624
tagged with: virtualenv
has title: How to link virutualenvwrapper with Jupyter notebook
has body: I have a venv/virtualenvwrapper set up in a directory. After I start working on the venv, i then create a Jupyter notebook inside of the directory, which brings me to Jupyter's localhost browser. I then attempt to import a library, e.g. pandas, which raises the ModuleNotFoundError. I would think that if the venv is being worked on, Jupyter would link to it. Also, I can import global libraries from pip3, just not the local ones in a venv. Is there a way to use the virtualenvwrapper library with Jupyter?
downvote count: 0
answer count: 1
score: 1
tagged with: jupyter-notebook
favorite count: 0

http://stackoverflow.com/a/51263467
type: Answer
has body: this could work, as long as the first date you give is always the first of the month from datetime import datetime from datetime import timedelta date_string = '01/01/2017' date = datetime.strptime(date_string, '%d/%m/%Y').date() today = datetime.now().date() months = range(1,13) years = range(date.year, today.year + 1) for y in years: for m in months: new_date = date.replace(month=m, year=y) last_day = new_date - timedelta(days=1) if (date &lt; new_date) &amp; (new_date &lt;= today): print last_day.strftime('%d/%m/%Y') print new_date.strftime('%d/%m/%Y') elif (date &lt;= new_date) &amp; (new_date &lt;= today): print new_date.strftime('%d/%m/%Y')
answers question: http://stackoverflow.com/q/51262737
score: 0

http://stackoverflow.com/comment/89438832
has text: One problem is that I want to extract topics in this video ( https://www.youtube.com/watch?v=dyTtHdKWS2o ). I mean when the presenter mentions a new topic , this topic appears on the screen ( for eg , 00:19 , 06:33,... )and I want to extract them.But the problem is that , the topics are displayed around the same position , not exactly. I opened all the image ,try and pick up one ratio , manually . Then I apply this ratio for the whole images And of course ,this ratio isnt correct t for some images and some texts are lost .Are there way that I can extract the whole text for every images?.
type: AnswerComment
comment on: http://stackoverflow.com/a/51229384
score: 0
type: Comment

http://stackoverflow.com/comment/89465774
has text: Possible duplicate of [What is the naming convention in Python for variable and function names?](https://stackoverflow.com/questions/159720/what-is-the-naming-convention-in-python-for-variable-and-function-names)
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51243482

http://stackoverflow.com/a/51258068
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51234188
answers question: http://stackoverflow.com/q/51234188
upvote count: 2
has body: You can do this by defining an object_hook to pass to json.loads. From the docs: object_hook is an optional function that will be called with the result of any object literal decoded (a dict). The return value of object_hook will be used instead of the dict. Given this dict: &gt;&gt;&gt; pprint(d) {'campaign_id': '9c1c6cd7-fd4d-480b-8c80-07091cdd4103', 'creation_date': 1530804132, 'float': 1.2345, 'objects': [{'full_name': '', 'id': 12345}], 'strs': ['', 'abc', {'a': ''}], 'top_str': ''} This pair of functions will recurse over the result of json.loads and change instance of the empty string to 'N/A'. def transform_dict(mapping=None): if mapping is None: mapping = {} for k, v in mapping.items(): if v == '': mapping[k] = 'N/A' elif isinstance(v, dict): mapping[k] = transform_dict(v) elif isinstance(v, list): mapping[k] = transform_list(v) else: # Make it obvious that we aren't changing other values pass return mapping def transform_list(lst): for i, x in enumerate(lst): if x == '': lst[i] = 'N/A' elif isinstance(x, dict): lst[i] = transform_dict(x) elif isinstance(x, list): lst[i] = transform_list(x) else: # Make it obvious that we aren't changing other values pass return lst &gt;&gt;&gt; res = json.loads( json.dumps(d), parse_float=decimal.Decimal, object_hook=transform_dict, ) &gt;&gt;&gt; pprint(res) {'campaign_id': '9c1c6cd7-fd4d-480b-8c80-07091cdd4103', 'creation_date': 1530804132, 'float': Decimal('1.2345'), 'objects': [{'full_name': 'N/A', 'id': 12345}], 'strs': ['N/A', 'abc', {'a': 'N/A'}], 'top_str': 'N/A'} Note that this approach depends on the input json being a json object ({...}).
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/99733567
downvote count: 0

http://stackoverflow.com/q/51277787
has comment: http://stackoverflow.com/comment/89533817
has title: pymongo MongoClient Takes Forever To Close
has comment: http://stackoverflow.com/comment/89533220
tagged with: pymongo
has comment: http://stackoverflow.com/comment/89533263
type: Question
tagged with: mongodb
score: 0
tagged with: python
has body: I am running an Apache server that can execute python files. To get the data from the python file it has to finish executing. These 3 lines of code take 600 milliseconds! Absolutely unacceptable for webpages The thing is it prints the data I need almost instantly.. And then takes 600 milliseconds to close (That was with more than these 3 lines of code obviously) I ran it with "time python3 file.py" outside of Apache to get the time #!/usr/bin/python3 from pymongo import MongoClient Client = MongoClient() Not sure if theres some code I can use to forcefully close the connection and use whats already been printed so the script can continue. Any tricks / hacky things you can think of are welcome lol
has comment: http://stackoverflow.com/comment/89536492
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/89546261
type: AnswerComment
type: Comment
has text: well, for age we have the minimal value, but for something like ratio of changes in temperature to the previous temperature (doesn't matter what variable really), which can be negative or positive and doesn't have minimal and maximal values, we can't define the first bin (from - infinity to 0, for example). Also df2 has this row with nan value, that represents any age greater then 50, and it shouldn't be ignored. So cut() is not an option, I need something more versatile.
score: 0
comment on: http://stackoverflow.com/a/51284406

http://stackoverflow.com/comment/89575391
score: 0
type: Comment
type: QuestionComment
has text: @abarnert In the sense that it doesn't allocate memory for elements, and thus does not actually "contain" anything. It is completely defined by its three parameters, unlike true containers like `dict`, `list`, `tuple`... Also, I just checked, Python docs doesn't call ranges containers, either.
comment on: http://stackoverflow.com/q/51299087

http://stackoverflow.com/q/51215137
tagged with: python
linked to: http://stackoverflow.com/q/41556439
tagged with: react-redux
tagged with: django
type: Question
has title: How to redirect data automatically from server to Client
tagged with: javascript
score: 0
answer count: 1
tagged with: websocket
has body: I am working on a web application using python3.5 for the backend, javascript +react/redux for the frontend and a Django server. The goal of the application is to display in real time data sent by some raspberry PI running under different protocols (MQTT, XMPP and CoaP). I tell my django server to make get request to differents servers which handles different protocols, then save those data into a database that i can finally retrieve into my redux store and then display those on my client. I would like to be able to remove the saving in database part which means that my Django server has to forward data it receives directly to the client side. I've made some researches and it seems that websocket programming is the best way to do it but i have such a different architecture so i'm not sure that i will be able to use this except if i restart from scratch which would be awful. If you have any other ideas to do what i want or if you have some advice to transform my app it would be great.
has answer: http://stackoverflow.com/a/51215980
type: UnansweredQuestion

http://stackoverflow.com/comment/89576011
has text: you can use `safe` filter in tempalte. but in this situation, I'm not sure it works.. So use `autoescape off`. I will write answer with this
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51298288
score: 0

http://stackoverflow.com/a/51301693
score: 0
answers question: http://stackoverflow.com/q/51301426
type: Answer
has body: The program does only execute the two print statements print(d_district) and print(d_code), where you actually just dump the contents of the zipcode dictionary. Your first print statement is never reached, as the condition never gets fulfilled. You have to compare to the value and not the key of the dictionary. For the reversed case, you can check if the string entered by the user is numeric, and if this is the case, you just search for the zipcode in the same manner. mydistrict=input('Enter your district: ') if mydistrict.strip().isnumeric(): for city in zipcode: for district in zipcode[city]: if zipcode[city][district] == int(mydistrict.strip()): print(city,zipcode[city][district]) else: for city in zipcode: if mydistrict in zipcode[city]: print(city,zipcode[city][mydistrict])
has comment: http://stackoverflow.com/comment/89613380

http://stackoverflow.com/comment/89351200
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51184189
has text: I could imagine the picture being produced with Mayavi.

http://stackoverflow.com/q/51322338
score: 0
tagged with: python
accepted answer: http://stackoverflow.com/a/51322446
tagged with: django
type: Question
has body: I am having issues with having to hardcode the tags into the templates in Django. The reason I have issues is that I need to have the forms generated dynamically based on a framework I am working on. That framework (written in Python) has a webinterface (hence Django) that requires forms for each module in the framework, depending on the data that needs to be submitted to that module. So I am trying to get the form information (which fields, type of fields, labels etc.) from the module, which I currently am trying like so: #framework/module.py def form(): forms = '"upload": {"filename": "file","directory": "text"}' return forms The reason it is constructed like that, at this moment, is because I try to pass this information to the forms.py from Django so it can then be translated into what Django needs to create the output for the template. Now I have tried a couple of ways on how to get it onto the template. The only problem is, that I have to create the form tags hardcoded into the template. I am trying to figure out how to get the form tags also generated dynamically based on the information supplied by the module. Because there could be modules that require multiple forms on the same page. So in short, I am trying to do this: {% for f in forms %} {{f}} {% endfor %} Instead of this: &lt;form name="upload" action="foo" method="POST"&gt; {{form}} &lt;/form&gt; Is this possible in Django?
type: AnsweredQuestion
has title: Django generating the form tags instead of hardcoding them
answer count: 1
has answer: http://stackoverflow.com/a/51322446

http://stackoverflow.com/comment/89374338
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51196294
score: 0
has text: I Updated my question

http://stackoverflow.com/q/51222901
has answer: http://stackoverflow.com/a/51223987
has body: I trained my word2vec model using the gensim package on 6.4 GB text data which is preprocessed using the following code snippet : def read_input(input_file): with open(input_file, "r") as inp: inp_str = inp.read() inp_str = inp_str.strip('\n') inp_str = re.sub(r'\n', ' ', inp_str) lowercase = inp_str.lower() punc = lowercase.translate(str.maketrans('', '', string.punctuation)) return (punc.translate(str.maketrans('','','1234567890'))) def read_(input_file): return( gensim.utils.simple_preprocess(input_file, deacc=True, min_len=3)) doc = read_input('../train1.txt') documents = read_(doc) logging.info ("Done reading data file") But every time I train the model, its size is 147 Kb which doesn't seems right and when I tried generating vectors from the trained model it says : KeyError: "word 'type' not in vocabulary" The following is the code I used for training my word2vec model : old_model = Word2Vec.load('../word2vec_model') old_model.train(documents, total_examples=old_model.corpus_count, epochs=7) old_model.save('../word2vec_model1') logging.info ("Saved the new word2vec model") Please help me resolving this issue.
type: Question
answer count: 1
score: 0
tagged with: gensim
has title: Word2vec Model size is very small and it is not recognizing words
tagged with: python-3.x
type: UnansweredQuestion
tagged with: word-embedding
tagged with: word2vec
tagged with: python

http://stackoverflow.com/comment/89448207
score: 0
type: Comment
type: QuestionComment
has text: I think you need to construct the right html structure for this to work for you. That is a `table` element should be followed with a `tr` and then a nested `td`s. This will be the order in which you would need them. In the above table you just have `table` nesting `td`s.
comment on: http://stackoverflow.com/q/51234560

http://stackoverflow.com/q/51286702
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89551675
upvote count: 1
tagged with: python
has title: How to scrape a google search results page?
has body: I am trying to scrape google search results using the following code. I want to take the title and the url of the first page of the results and then continue by scraping the next pages of the search results too. This is a sample of code that I just started writing: from urllib.request import urlopen as uReq import urllib.request from bs4 import BeautifulSoup as soup paging_url = "https://www.google.gr/search?q=donald+trump&amp;ei=F91FW8XBGYjJsQHQwaWADA&amp;start=110&amp;sa=N&amp;biw=811&amp;bih=662" req = urllib.request.Request("https://www.google.gr/search?q=donald+trump&amp;ei =F91FW8XBGYjJsQHQwaWADA&amp;start=110&amp;sa=N&amp;biw=811&amp;bih=662",headers = {'User-Agent':"Magic Browser"}) UClient = uReq(req) # downloading the url page_html = UClient.read() UClient.close() page_soup = soup(page_html, "html.parser") I noticed that all google results have a common class named "g". So I wrote the following command: results= page_soup.findAll("div",{"class":"g"}) But after testing the results taken are not the same that I see when I visit the initial Url. Moreover some div tags such as: &lt;div data-hveid="38" data-ved="0ahUKEwjGp7XEj5fcAhXMDZoKHRf8DJMQFQgmKAAwAA"&gt; and &lt;div class="rc"&gt; can not be seen in the tree that BeautifulSoup produces. Meaning I can not use findAll function to locate objects inside those tags because BeautifulSoup acts like they do not exist. Why all this happens?
has comment: http://stackoverflow.com/comment/89552676
score: 1
has comment: http://stackoverflow.com/comment/89558757
tagged with: web-scraping
type: Question
downvote count: 0
has comment: http://stackoverflow.com/comment/89551151
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/comment/89555693
comment on: http://stackoverflow.com/a/51288026
type: Comment
score: 0
type: AnswerComment
has text: how do i do that LOL

http://stackoverflow.com/comment/89329267
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51172820
score: 0
has text: Could you please post your override. Also, could you please explain what do you mean by _they start saving_. You see them in the database ? They appear on your form ?

http://stackoverflow.com/q/51204559
tagged with: shading
tagged with: colors
tagged with: python
answer count: 0
type: UnansweredQuestion
has title: Python Matplotlib: Large dataset that is cyclic. How can I make the shade of the color darken with index?
tagged with: line-plot
tagged with: matplotlib
has body: I'm plotting large data sets. The data is cyclical. Without using a color gradient, it is very difficult to understand how the data is evolving because of it's cyclical behavior. Multiple data sets are plotted at once, so asking a data set to change between colors is out of the question. example figure How can I make my line's color darken with index and still use a legend? EDIT: (editing for clarity and fulfilling the request for a minimum working example) I want my dataset's color to change it's shade from lighter to darker as the index increases. What I'm trying to do I still need the legend to work however. Miniumum working example code: import pandas as pd import matplotlib.pyplot as plt x = range(0,1000) y = [] for i in x: y.append(2*x[i]) i+=1 plt.plot(x,y, label = "poop") plt.legend() plt.show()
type: Question
has comment: http://stackoverflow.com/comment/89390248
has comment: http://stackoverflow.com/comment/89400455
score: 0

http://stackoverflow.com/comment/89600889
has text: Exactly. Assign to each string an `int` and then the classifier will work fine. Let me know and consider upvoting and accepting my answer. cheers
type: Comment
comment on: http://stackoverflow.com/a/51310142
score: 0
type: AnswerComment

http://stackoverflow.com/comment/89583685
comment on: http://stackoverflow.com/a/51303235
score: 0
type: AnswerComment
has text: @brunodesthuilliers But if you want to know how it work, you have to dig into the source .
type: Comment

http://stackoverflow.com/comment/89610747
has text: Do you want to just remove the word? Or do you want to remove the list element?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51317357

http://stackoverflow.com/comment/89383291
comment on: http://stackoverflow.com/a/51200391
has text: yeah this is what i'm getting 'The Final Binary Output is: ['0', '1', '1', '1', 0]'
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/89607489
has text: Please help anyone
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51314984

http://stackoverflow.com/comment/89624949
type: Comment
score: 1
comment on: http://stackoverflow.com/a/51317158
type: AnswerComment
has text: If you update your question with **Actual Code** and **relevant relationship**, I could help you more, That is, user model/abstract user model, userserailzer l etc

http://stackoverflow.com/comment/89428522
type: AnswerComment
comment on: http://stackoverflow.com/a/51222442
type: Comment
score: 1
has text: Start using Anaconda and virtual env in it and this problem went away..

http://stackoverflow.com/q/51242447
upvote count: 1
has answer: http://stackoverflow.com/a/51242674
accepted answer: http://stackoverflow.com/a/51242674
answer count: 1
has title: Subscribing to a ROS sensor_msg/Image using python
favorite count: 0
tagged with: python
type: AnsweredQuestion
downvote count: 0
has body: I'm trying to subscribe to a ROS node published by a vrep vision sensor. Here is my code, which works fine when using my built-in webcam: import rospy from sensor_msgs.msg import Image from std_msgs.msg import String from cv_bridge import CvBridge, CvBridgeError import cv2 import numpy as np import tensorflow as tf import classify_image class RosTensorFlow(): def __init__(self): classify_image.maybe_download_and_extract() self._session = tf.Session() classify_image.create_graph() self._cv_bridge = CvBridge() self._sub = rospy.Subscriber('image', Image, self.callback, queue_size=1) self._pub = rospy.Publisher('result', String, queue_size=1) self.score_threshold = rospy.get_param('~score_threshold', 0.1) self.use_top_k = rospy.get_param('~use_top_k', 5) def callback(self, image_msg): try: cv_image = self._cv_bridge.imgmsg_to_cv2(image_msg, desired_encoding="passthrough") except CvBridgeError as e: print(e) # copy from # classify_image.py image_data = cv2.imencode('.jpg', cv_image)[1].tostring() # Creates graph from saved GraphDef. softmax_tensor = self._session.graph.get_tensor_by_name('softmax:0') predictions = self._session.run( softmax_tensor, {'DecodeJpeg/contents:0': image_data}) predictions = np.squeeze(predictions) # Creates node ID --&gt; English string lookup. node_lookup = classify_image.NodeLookup() top_k = predictions.argsort()[-self.use_top_k:][::-1] for node_id in top_k: human_string = node_lookup.id_to_string(node_id) score = predictions[node_id] if score &gt; self.score_threshold: rospy.loginfo('%s (score = %.5f)' % (human_string, score)) self._pub.publish(human_string) def main(self): rospy.spin() if __name__ == '__main__': classify_image.setup_args() rospy.init_node('rostensorflow') tensor = RosTensorFlow() tensor.main() and my non-threaded child-script in vrep, which i basically copied from the rosInterfaceTopicPublisherAndSubscriber.ttt tutorial: function sysCall_init() activeVisionSensor=sim.getObjectHandle('Vision_sensor') pub=simROS.advertise('i…
type: Question
tagged with: opencv
score: 1
has comment: http://stackoverflow.com/comment/89569665
tagged with: subscriber
tagged with: ros

http://stackoverflow.com/q/51303361
answer count: 1
has title: COLOR_RGB2GRAY gives none-grayscale image (might be an issue with jupyter-notebook)
favorite count: 0
tagged with: jupyter-notebook
downvote count: 2
has comment: http://stackoverflow.com/comment/89583416
tagged with: python
has answer: http://stackoverflow.com/a/51303980
tagged with: opencv
type: AnsweredQuestion
upvote count: 3
score: 1
accepted answer: http://stackoverflow.com/a/51303980
type: Question
has comment: http://stackoverflow.com/comment/89584345
has body: I am trying to perform histogram equalization on an image an have 2 issues. First, I need to plot the histogram for the grayscale version of it. When I try to convert the RGB image to grayscale the output is a blue and yellow image. My code goes as follows: img = cv2.imread(r'D:/UNI/Y3/DIA/2K18/lab.jpg') RGB_img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) gray = cv2.cvtColor(RGB_img, cv2.COLOR_RGB2GRAY) plt.imshow(gray) plt.title('My picture (before hist. eq.)') plt.show() This is Jupyter Notebook's output: But I just realized that if I save if it saves it correctly: Since I need to hand in the jupyter doc how could I overcome this issue? Thx! Second, I perform Histogram equalization but when trying to stack the images horizontally I get the following error form this code: equ = cv2.equalizeHist(gray) res = np.hstack((img,equ)) error -&gt; all the input arrays must have same number of dimensions As far as I can see I didn't touch the images' dimensions at all... EDIT: The left image should be RGB

http://stackoverflow.com/q/51275578
has answer: http://stackoverflow.com/a/51275756
tagged with: python-2.7
answer count: 3
has comment: http://stackoverflow.com/comment/89529249
has answer: http://stackoverflow.com/a/51275873
possible better answer: http://stackoverflow.com/a/51275757
downvote count: 0
has answer: http://stackoverflow.com/a/51275757
has comment: http://stackoverflow.com/comment/89529073
has comment: http://stackoverflow.com/comment/89529322
has title: Matching subsequences within two separate lists
has comment: http://stackoverflow.com/comment/89529072
favorite count: 0
upvote count: 2
tagged with: python
accepted answer: http://stackoverflow.com/a/51275756
score: 2
type: AnsweredQuestion
tagged with: list
has comment: http://stackoverflow.com/comment/89529159
type: Question
has body: I'm processing two seperate lists, one the split result of a string and another containing a list-object with the first item in the list-object being a string. For example, list_0: ["Hey", "hello?", "hi"] list_1: [["Hey", 0.13, 0.14, 0, 0.58], ["hello?", 0.15, 0.16, 1, 0.23], ["hi", 0.17, 0.18, 0, 0.32]] list_0 is arranged in the correct order and contains duplicate values, it can't be a set as it's a translation of an audio file. In list_1, the 3rd element is a reference_number for each speaker. I want to sort through the translation and find the speaker for each word/phrase so I can see that reference_number_0 said "Hey", "hi" and reference_number_1 said "hello?". As there can be duplicate values I need to make sure I'm not incorrectly matching with the first pair. How can I find the ref_number for each complete phrase? Expected output 0: "Hey", "hi" 1: "hello?" As as more complicated example, say I have this as list_0 and list_1: list_0: ["Have", "we", "all", "had", "lunch" yes", "yes", "not", "yet"] list_1: [["Have", 0.0, 0.1, 0, 0.12], ["we", 0.2, 0.3, 0, 0.48], ["all", 0.4, 0.5, 0, 0.85], ["had", 0.6, 0.7, 0, 0.82], ["lunch", 0.8, 0.9, 0, 0.35], ["yes", 0.9, 1.0, 0, 0.57], ["yes", 1.1, 1.2, 1, 0.56], ["not", 1.3, 1.4, 2, 0.25], ["yet", 1.5, 1.6, 2, 0.73]] There's three-speakers here - 0, 1, 2. The output should be: 0: "Have", "we", "all", "had", "lunch", "yes" 1: "yes" 2: "not", "yet" Cheers :)
has comment: http://stackoverflow.com/comment/89529113
has comment: http://stackoverflow.com/comment/89529127
has comment: http://stackoverflow.com/comment/89529293
tagged with: sorting

http://stackoverflow.com/comment/89569564
has text: While this will work, I don't think it's what you want to do here. See [my answer](https://stackoverflow.com/a/51295988/908494), or [Intra-package references](https://docs.python.org/3/tutorial/modules.html#intra-package-references) in the docs.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51295863
type: Comment

http://stackoverflow.com/q/51181600
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/51181877
has title: Oraginizing django urlpatterns for APIs
possible better answer: http://stackoverflow.com/a/51181877
has body: I would like to use an api version index for all my API endpoints (api/v1/). Currently I'm achieving it by structuring my urlpatterns like so: urlpatterns = [ path('api/v1/units/', include('units.api.urls')), path('api/v1/accounts/', include('accounts.api.urls')), ] Is there a way to organize this more elegantly? Ideally I would like it to look something like this: apipatterns = [ 'units/', include('units.api.urls'), 'accounts/', include('accounts.api.urls') ] urlpatterns = [ path('api/v1/', include(apipatterns)), ]
score: 0
has answer: http://stackoverflow.com/a/51181878
tagged with: python
tagged with: django
accepted answer: http://stackoverflow.com/a/51181878
type: AnsweredQuestion

python-c-api
tags question: http://stackoverflow.com/q/51172546
tags question: http://stackoverflow.com/q/51273804
tag name: python-c-api
tags question: http://stackoverflow.com/q/51236885
type: Tag

http://stackoverflow.com/comment/89503488
has text: Yep, that's what I'm doing now (typing it in console instead of .bat), but that only kills the 7-8 chromedriver.exe processes. There are 70 more chrome.exe instances. Killing them also closes my own Chrome browser. I guess a follow-up question is how to taskkill only children of a process. Anyway, it's not that big a deal, but I would just like to be able to do it programmatically. It seems like the multiprocessing module/Selenium should have this sort of functionality.
type: Comment
comment on: http://stackoverflow.com/a/51262558
score: 0
type: AnswerComment

http://stackoverflow.com/a/51298887
type: Answer
answers question: http://stackoverflow.com/q/51298119
score: 0
has body: First, I would go over your dictionary, that holds all data and flatten it: my_array = [data for key, data in my_dictionary.items()] Then I would create the dictionary you need, e.g.: growth = {x['date']: x['growth'] for x in my_array} If you need a list of dictionaries: growth = [{"date": x['date'], "growth": x['growth']} for x in my_array]
has comment: http://stackoverflow.com/comment/89602977

http://stackoverflow.com/a/51180341
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/89343107
has body: list comprehensions have the [] square brackets. if you don't have the [] square brackets, you have a generator expression .apply(lambda x: (i for (i,row) in correct.iteritems())) The code above would make a function that returns a generator expression, and pass it to the .apply .apply([lambda x: i for (i,row) in correct.iteritems()]) The code above would create a list of functions, and pass that list to .apply .apply(lambda x: [i for (i,row) in correct.iteritems()]) The code above would make a function that returns a list, and pass it to the .apply.
upvote count: 1
accepted answer of: http://stackoverflow.com/q/51180293
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51180293
has comment: http://stackoverflow.com/comment/89343254
type: Answer
has comment: http://stackoverflow.com/comment/89343129
has comment: http://stackoverflow.com/comment/89343137

http://stackoverflow.com/q/51180771
type: Question
tagged with: null
tagged with: dataframe
score: -1
has comment: http://stackoverflow.com/comment/89344004
has answer: http://stackoverflow.com/a/51180953
linked to: http://stackoverflow.com/q/46091924
has comment: http://stackoverflow.com/comment/89344057
tagged with: pandas
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/89344241
favorite count: 0
has title: How to drop empty rows from a DataFrame when 'pd.notnull' does not work? Python
has comment: http://stackoverflow.com/comment/89344109
has body: I have a DataFrame with two columns 'A' and 'B'. My goal is to delete rows where 'B' is empty. Others have recommended to use df[pd.notnull(df['B'])]. For example here: Python: How to drop a row whose particular column is empty/NaN? However, somehow this does not work in this case. Why not and how to solve this? A B 0 Lorema Ipsuma 1 Corpusa Dominusa 2 Loremb 3 Corpusc Dominusc 4 Loremd 5 Corpuse Dominuse This is the desired result: A B 0 Lorema Ipsuma 1 Corpusa Dominusa 2 Corpusc Dominusc 3 Corpuse Dominuse
tagged with: python
has comment: http://stackoverflow.com/comment/89344166
has comment: http://stackoverflow.com/comment/89344038
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89344002
has comment: http://stackoverflow.com/comment/89344204
has comment: http://stackoverflow.com/comment/89344072
downvote count: 1

http://stackoverflow.com/comment/89333807
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51173140
has text: @VivekKumar I have 17,000 bits of data in my data set.. Is there anyway I can get this to run faster? Thank you by the way!

http://stackoverflow.com/a/51235746
score: 2
has body: My take on problem: from itertools import chain variable = set(chain.from_iterable(["car", "train", "bike", "boat", "airplaine"])) print(variable) Output: {'o', 'a', 'l', 'c', 'i', 't', 'b', 'e', 'r', 'p', 'n', 'k'}
answers question: http://stackoverflow.com/q/51235732
downvote count: 0
type: Answer
upvote count: 2

http://stackoverflow.com/comment/89503215
type: AnswerComment
has text: Awesomely awesome!
type: Comment
comment on: http://stackoverflow.com/a/51262544
score: 0

http://stackoverflow.com/comment/89393440
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51205949
has text: i don't see any scan part of your code.

http://stackoverflow.com/q/51170169
type: AnsweredQuestion
downvote count: 0
score: 24
tagged with: sqlalchemy
type: Question
has answer: http://stackoverflow.com/a/74717632
linked to: http://stackoverflow.com/q/34322471
has body: With Pandas, I can very easily read data from a database into a dataframe: from sqlalchemy import create_engine import pandas query = 'SELECT * FROM Table_Name;' engine = create_engine('...') df = pandas.read_sql_query(query, engine) print(df.head()) I would like to make sure that no connection is kept open after executing .read_sql_query(), no matters if the query succeeded or if it raised an exception. I am currently: Using a function to restrict the engine's scope. I only expect to call this function once each half an hour, so I do not mind re-creating the engine if that helps ensuring everything is cleaned/closed/garbage-collected. Disabling pooling with poolclass=NullPool. Finally calling engine.disponse(). Like so: from sqlalchemy import create_engine from sqlalchemy.pool import NullPool import pandas def get_data(): query = 'SELECT * FROM Table_Name;' try: engine = create_engine('...', poolclass=NullPool) df = pandas.read_sql_query(query, engine) finally: engine.dispose() return df print(get_data().head()) Is there a better way?
answer count: 2
tagged with: pandas
upvote count: 24
favorite count: 0
possible better answer: http://stackoverflow.com/a/74717632
has title: Clean-up database connection with SQLAlchemy in Pandas
tagged with: python
has answer: http://stackoverflow.com/a/51242577
accepted answer: http://stackoverflow.com/a/51242577

http://stackoverflow.com/q/51221958
answer count: 1
downvote count: 0
favorite count: 0
has title: Tensorflow Dimension Error on reshape
upvote count: 1
has body: I am trying to addapt the very simple MNIST example (https://github.com/tensorflow/tensorflow/blob/r1.8/tensorflow/examples/tutorials/layers/cnn_mnist.py) to suit a problem that I have. The problem seems to be somewhere in the dimension of my input ( i believe) Where the original MNIST data has the following properties (inserted at line 125): print(train_data.shape) # (55000, 784) print(type(train_data)) # &lt;class 'numpy.ndarray'&gt; print(train_labels.shape) # (55000, ) print(type(train_labels)) # &lt;class 'numpy.ndarray'&gt; my data has the following shape Train Data: (10681, 9216) Train Data: &lt;class 'numpy.ndarray'&gt; Train Labe: (10681,) Train Labe: &lt;class 'numpy.ndarray'&gt; in particular we have that 784=28*28 and 9216=96*96.Thus, where the original line (31) reads input_layer = tf.reshape(features["x"], [-1, 28, 28, 1]) i replaced it with input_layer = tf.reshape(features["x"], [-1, 96, 96, 1]) However when I run this, the error that I get is: Traceback (most recent call last): File "/home/j-pc/.local/lib/python3.5/site-packages/tensorflow/python/framework/common_shapes.py", line686, in _call_cpp_shape_fn_impl input_tensors_as_shapes, status) File "/home/j-pc/.local/lib/python3.5/site-packages/tensorflow/python/framework/errors_impl.py", line 473, in __exit__ c_api.TF_GetCode(self.status.status)) tensorflow.python.framework.errors_impl.InvalidArgumentError: Dimension size must be evenly divisible by 3136 but is 3686400 for 'Reshape_1' (op: 'Reshape') with input shapes: [100,24,24,64], [2] and with input tensors computed as partial shapes: input[1] = [?,3136]. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "tensorfuck/learn.py", line 252, in &lt;module&gt; tf.app.run() File "/home/j-pc/.local/lib/python3.5/site-packages/tensorflow/python/platform/app.py", line 124, in run _sys.exit(main(argv)) File "tensorfuck/learn.py", line 238, in main hooks=[logging_hook]) File "/home/j-pc/.local/lib/py…
accepted answer: http://stackoverflow.com/a/51223670
tagged with: python
has answer: http://stackoverflow.com/a/51223670
type: AnsweredQuestion
score: 1
tagged with: tensorflow
type: Question

http://stackoverflow.com/comment/89610823
has text: Hi, I'm using anaconda. I'm new to python but the docs and various resources I've read over the past few days have consistently told me to not use pip while I have anaconda. Is this true?
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/51317382
type: Comment

http://stackoverflow.com/a/51204818
upvote count: 2
type: Answer
has body: Predicting data values Studying the dataset We begin by studying the shape of the dataset, it may show some particular distribution: import numpy as np from matplotlib import pyplot as plt data = np.array([(1, 0), (2, 0), (3, 0.74), (4, 3.90), (5, 42.5), (6, 39.40), (7, 12.29), (8, 1.25), (9, 0), (10, 0)]) x = data[:, 0] y = data[:, 1] / 100 # We normalise the percentage points plt.title("Wine ratings percentages") plt.ylabel("Samples") plt.xlabel("Ratings") plt.plot(x, y, '.') plt.plot(x, y) The results are in: Results interpretation The distribution of the data, as could be expected from a 1-10 ratings dataset, is Binomial, a discrete Gaussian. This is called a Sampling distribution. Predicting the values Now we have an idea of the distribution of our dataset. We have now to predict the values of every class, making the assumption that it is truly Binomial. A Binomial distribution hold two parameters: the number of elements n, in this scenario 10, and the probability of a trial, an extraction, usually called p. Since the mean of a Binomial is np, we can easily obtain p = mean/n. mean = np.mean(x) p = mean/10 The two values are n=10 and p=mean/10=0.010008. We can use these as parameters to obtain the distribution these data would hold if they where full sets. from scipy.stats import binom my_binom = binom(10, p) x_b = np.arange(0, 10+1) y_b = my_binom.pmf(x_b) plt.plot(x_b, y_b, '.') plt.plot(x_b, y_b) The predicted values With this approach, the obtained values are the following: predictions = [(0, 0.0003405062891601558), (1, 0.004161743534179685), (2, 0.02288958943798826), (3, 0.07460310631640629), (4, 0.15956775517675784), (5, 0.2340327075925782), (6, 0.2383666466220704), (7, 0.1664782928789064), (8, 0.07630255090283203), (9, 0.020724149627929712), (10, 0.0025329516211914063)] Further notes You can take this approach and explore it further, trying to identify a more specific distribution or, if you have more data related to other aspects of your model, applying …
score: 2
answers question: http://stackoverflow.com/q/51203869
downvote count: 0

http://stackoverflow.com/q/51301761
type: UnansweredQuestion
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/51302710
has comment: http://stackoverflow.com/comment/89582280
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/89581549
has answer: http://stackoverflow.com/a/54726866
linked to: http://stackoverflow.com/q/54059483
tagged with: cassandra
score: 0
has title: TypeError when make migration with django and cassandra
has body: When I execute python manage.py migrate I get the following TypeError: TypeError: Unknown option(s) for sync_cassandra command: app_label, fake, fake_initial, interactive, migration_name, run_syncdb. Valid options are: database, help, no_color, pythonpath, settings, skip_checks, stderr, stdout, traceback, verbosity, version. I'm using Cassandra 3.11.2, Python 3.5.2 and django 2.0.7. All run in Ubuntu Server 16.04 Edit to add settings.py https://pastebin.com/s4fQCNEk I think everything is fine in settings file... I was triying to reinstall cassandra, cassandra_engine and doesn't works. Thanks!

http://stackoverflow.com/q/51256271
tagged with: pandas
answer count: 1
has title: python 2 equivalent to get_dummies with pandas df
tagged with: jupyter-notebook
tagged with: python
type: AnsweredQuestion
has body: I am seeking clarity as to why my code cannot access specific column values using dummie values using the following example data: df shop category subcategory season date 2013-09-04 abc weddings shoes winter 2013-09-04 def jewelry watches summer 2013-09-05 ghi sports sneakers spring 2013-09-05 jkl jewelry necklaces fall Here is my basic code: wedding_df = df"weddings","winter","summer","spring","fall" I'm using Python 2 with my notebook, so it very well may be a version issue and require get_dummies(), but some guidance would be helpful. Idea is to create a dummy dataframe that uses binary to say if a row had a wedding category and what season. Here is an example of what I'm looking to achieve: weddings winter summer spring fall 71654 1.0 0.0 1.0 0.0 0.0 72168 1.0 0.0 1.0 0.0 0.0 72080 1.0 0.0 1.0 0.0 0.0 with corr(): weddings fall spring summer winter weddings NaN NaN NaN NaN NaN fall NaN 1.000000 0.054019 -0.331866 -0.012122 spring NaN 0.054019 1.000000 -0.857205 0.072420 summer NaN -0.331866 -0.857205 1.000000 -0.484578 winter NaN -0.012122 0.072420 -0.484578 1.000000
type: Question
has answer: http://stackoverflow.com/a/51256286
accepted answer: http://stackoverflow.com/a/51256286
score: 0

http://stackoverflow.com/a/51236525
has body: json_normalize(data, record_path='Content', 'Story') That should work.
has comment: http://stackoverflow.com/comment/89452081
type: Answer
has comment: http://stackoverflow.com/comment/89452073
answers question: http://stackoverflow.com/q/51236433
score: 9
has comment: http://stackoverflow.com/comment/89452128
upvote count: 9
accepted answer of: http://stackoverflow.com/q/51236433
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/51280064
has comment: http://stackoverflow.com/comment/89537705
has comment: http://stackoverflow.com/comment/89542487
has comment: http://stackoverflow.com/comment/89541760
has comment: http://stackoverflow.com/comment/89541916
has comment: http://stackoverflow.com/comment/89538188
has comment: http://stackoverflow.com/comment/89575841
has comment: http://stackoverflow.com/comment/89541998
has comment: http://stackoverflow.com/comment/89539725
has comment: http://stackoverflow.com/comment/89542611
has comment: http://stackoverflow.com/comment/89539097
has comment: http://stackoverflow.com/comment/89542902
has comment: http://stackoverflow.com/comment/89543254
has comment: http://stackoverflow.com/comment/89542968
tagged with: gunicorn
has comment: http://stackoverflow.com/comment/89538772
has comment: http://stackoverflow.com/comment/89540023
has comment: http://stackoverflow.com/comment/89538205
tagged with: django
upvote count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/51513960
has comment: http://stackoverflow.com/comment/89541537
has comment: http://stackoverflow.com/comment/89542109
has comment: http://stackoverflow.com/comment/89541224
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89542253
has comment: http://stackoverflow.com/comment/89541053
score: 1
has comment: http://stackoverflow.com/comment/89538043
has comment: http://stackoverflow.com/comment/89996140
tagged with: django-urls
has comment: http://stackoverflow.com/comment/89543118
possible better answer: http://stackoverflow.com/a/51281522
has comment: http://stackoverflow.com/comment/89541152
has comment: http://stackoverflow.com/comment/89542213
has comment: http://stackoverflow.com/comment/89542154
has comment: http://stackoverflow.com/comment/89539305
has answer: http://stackoverflow.com/a/51281522
type: Question
has comment: http://stackoverflow.com/comment/89539465
answer count: 2
has comment: http://stackoverflow.com/comment/89541842
has comment: http://stackoverflow.com/comment/89538598
downvote count: 0
has body: I have changed the URLs in the website file, now, the page doesn't work. This is the error I get. I'm using Django 1.8.7 on Ubuntu 16.04, on a DigitalOcean Droplet and it is hosted on Gunicorn. This is my project url file: from django.conf import settings from django.conf.urls import include, url from django.conf.urls.static import static from django.contrib import admin urlpatterns = [ url(r'^', include('website.urls')), url(r'^admin/', include(admin.site.urls)), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) This is website urls file: from django.conf import settings from django.conf.urls import url from django.conf.urls.static import static from . import views urlpatterns = [ url(r'^en/$', views.index_en, name='index_en'), url(r'^en/results/$', views.results_en, name="results_en"), url(r'^es/$', views.index_es, name='index_es'), url(r'^es/results/$', views.results_es, name="results_es"), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) My settings.py, it is the default settings generated when i created the droplet, i only changed the language code and the static content directory: import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = 'itisasecrethahaha' DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'website' ) MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', ) ROOT_URLCONF = 'django_project.urls'…
has title: Django Import Error at / No module named urls
has comment: http://stackoverflow.com/comment/89537728
has comment: http://stackoverflow.com/comment/89537922
has answer: http://stackoverflow.com/a/51513960
favorite count: 0

http://stackoverflow.com/q/51322445
downvote count: 0
has body: I have a large dataset of which I would like to drop columns that contain null values and return a new dataframe. How can I do that? The following only drops a single column or rows containing null. df.where(col("dt_mvmt").isNull()) #doesnt work because I do not have all the columns names or for 1000's of columns df.filter(df.dt_mvmt.isNotNull()) #same reason as above df.na.drop() #drops rows that contain null, instead of columns that contain null For example a | b | c 1 | | 0 2 | 2 | 3 In the above case it will drop the whole column B because one of its values is empty.
possible better answer: http://stackoverflow.com/a/74121037
favorite count: 0
has comment: http://stackoverflow.com/comment/89620909
tagged with: python
has answer: http://stackoverflow.com/a/51325114
upvote count: 11
score: 11
linked to: http://stackoverflow.com/q/44627386
type: AnsweredQuestion
tagged with: apache-spark-sql
tagged with: pyspark
has title: How to drop all columns with null values in a PySpark DataFrame?
accepted answer: http://stackoverflow.com/a/51325114
has answer: http://stackoverflow.com/a/74121037
type: Question
answer count: 2
tagged with: apache-spark

http://stackoverflow.com/q/51194183
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
score: 2
downvote count: 0
type: Question
tagged with: apache-spark-sql
has answer: http://stackoverflow.com/a/51246800
tagged with: pyspark
has title: PYSPARK:- Exploding the array in dataframe without loosing null values:'DataFrame' object has no attribute '_get_object_id'
has comment: http://stackoverflow.com/comment/89374462
has comment: http://stackoverflow.com/comment/89371056
upvote count: 2
has body: Getting error while calling below code.This is exploding the array in dataframe without loosing null values but while calling columns I am getting error saying object has no attribute '_get_object_id'. Need help in other way of calling column that can work. from pyspark.sql import SparkSession from pyspark.sql import DataFrame from pyspark.sql import Row from pyspark.sql.types import ArrayType from pyspark.sql.functions import * from functools import reduce def explode_outer(df, columns_to_explode): array_fields = dict([(field.name, field.dataType) for field in df.schema.fields if type(field.dataType) == ArrayType]) return reduce(lambda df_with_explode, column: df_with_explode.withColumn(column, explode( when(size(df_with_explode[column]) != 0, df_with_explode[column]) .otherwise(array(lit(None).cast(array_fields[column].elementType))))), columns_to_explode, df) When doing : cols = ['columname'] df_1 = df.select(explode_outer(df,cols)) Error: AttributeError: 'DataFrame' object has no attribute '_get_object_id'
answer count: 1

http://stackoverflow.com/a/51209368
has body: Vectorised, you can use pd.to_datetime with unit='ns'. df['datetime'] = pd.to_datetime(df['time'], unit='ns') print(df) name time datetime 0 acn 1530677359000000000 2018-07-04 04:09:19 1 acn 1530677363000000000 2018-07-04 04:09:23 2 acn 1530681023000000000 2018-07-04 05:10:23 3 acn 1530681053000000000 2018-07-04 05:10:53 4 acn 1530681531000000000 2018-07-04 05:18:51 5 acn 1530681561000000000 2018-07-04 05:19:21
accepted answer of: http://stackoverflow.com/q/51209020
score: 3
type: AcceptedAnswer
upvote count: 3
downvote count: 0
answers question: http://stackoverflow.com/q/51209020
type: Answer

http://stackoverflow.com/q/51177649
has comment: http://stackoverflow.com/comment/89395914
has body: I am using anaconda version 1.6.14, python version 3.6.5, pulp version 1.6.8 and CPLEX version 12.8. When I run pulp.pulpTestAll() coin passes and CPLEX_CMD fails on testing zero constraint (see output below). The same output is given in this question: Pulp.pulpTestAll() test failed, too many values to unpack But the question is asking why GUROBI failed not why CPLEX failed, and therefore the answers provided there do not answer my question. The output of pulp.pulpTestAll() is: pulp.pulpTestAll() Testing zero subtraction Testing inconsistant lp solution Testing continuous LP solution Testing maximize continuous LP solution Testing unbounded continuous LP solution Testing Long Names Testing repeated Names Testing zero constraint Testing zero objective Testing LpVariable (not LpAffineExpression) objective Testing Long lines in LP Testing LpAffineExpression divide Testing MIP solution Testing MIP solution with floats in objective Testing MIP relaxation Testing feasibility problem (no objective) Testing an infeasible problem Testing an integer infeasible problem Testing column based modelling Testing dual variables and slacks reporting Testing fractional constraints Testing elastic constraints (no change) Testing elastic constraints (freebound) Testing elastic constraints (penalty unchanged) Testing elastic constraints (penalty unbounded) * Solver &lt;class 'pulp.solvers.PULP_CBC_CMD'&gt; passed. Solver &lt;class 'pulp.solvers.CPLEX_DLL'&gt; unavailable Testing zero subtraction Testing inconsistant lp solution Testing continuous LP solution Testing maximize continuous LP solution Testing unbounded continuous LP solution Testing Long Names Testing repeated Names Testing zero constraint '_dummy' * Solver &lt;class 'pulp.solvers.CPLEX_CMD'&gt; failed. Testing zero subtraction Testing inconsistant lp solution Testing continuous LP solution Testing maximize continuous LP solution Testing unbounded continuous LP solution Failure: status == -2 not in [-1] Failure: status == Un…
answer count: 0
has title: Pulp.pulpTestAll() test failed on "Testing zero constraint"
linked to: http://stackoverflow.com/q/40838567
type: Question
tagged with: python
score: 0
tagged with: pulp
tagged with: cplex
tagged with: anaconda
has comment: http://stackoverflow.com/comment/89374045
type: UnansweredQuestion

http://stackoverflow.com/q/51247304
has title: Does tflearn.models.dnn.DNN automatically turn off dropout layers and batch normalization when predicting?
downvote count: 0
tagged with: tflearn
tagged with: deep-learning
answer count: 1
favorite count: 0
has body: I'm quite new to Neural Networks, which is why I've decided to use Tflearn because it is quite intuitive. However I couldn't find an answer to my question. The tflearn documentation gives the following example for letting a deep neural network predict something: network = ... model = DNN(network) model.load('model.tflearn') model.predict(X) I've inserted some batch normalization layers inside the network because my model seemed to be overfitting. Will model.predict() automatically "tell" the batch normalization layer not to behave like in a training phase? Or do I have to specify this somehow with tflearn.config.is_training (is_training=False, session=None)? If yes, do you know where I should put this line? And how do I create my session so that it does the same like my code. At the moment it basically looks like the example at tflearn.org: net = tflearn.input_data(shape=[None, 784]) net = tflearn.fully_connected(net, 64) net = tflearn.dropout(net, 0.5) net = tflearn.fully_connected(net, 10, activation='softmax') net = tflearn.regression(net, optimizer='adam', loss='categorical_crossentropy') model = tflearn.DNN(net) model.fit(X, Y) except that I use a batch normalization layer and I use the neural network for function approximation. Unfortunately I cannot post my code right now,since it's on another Computer but it really is basically the same. Could someone help me with this question? Thanks in advance!
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/51270653
score: 1
tagged with: machine-learning
upvote count: 1
tagged with: tensorflow
type: Question

http://stackoverflow.com/comment/89471869
type: QuestionComment
has text: db.session.query(func.count(Incidents.severity),Incidents.severity, Projects.org).filter(Incidents.severity.in_(['SEV2','SEV3','SEV1','SEV0',''])).join(Projects, Projects.jira_key == Incidents.jira_key).group_by(Projects.org, Incidents.severity) Gives me the results I want.
type: Comment
comment on: http://stackoverflow.com/q/51243998
score: 0

http://stackoverflow.com/comment/89547315
comment on: http://stackoverflow.com/q/51284987
type: Comment
type: QuestionComment
score: 0
has text: @GermanoLodi, yes (didn't help), it seems like the flood is generated before the settings are even loaded

http://stackoverflow.com/a/51237266
downvote count: 1
type: Answer
upvote count: 0
score: -1
has body: Just to compile the answers: That is not a string, it is a list (a string is a word like "hey"). You can do some_numbers.reverse(), and now the list is reversed. Or, if you don't want to overwrite the list, call reversed (list). Or you can get some_numbers [::-1]. The numbers in the brackets (called splices) tell Python how to look at the list. The first number, which since we didn't include defaults to the start of the list, tells Python where to start. The second number, which defaults to len (some_numbers), tells Python where to stop. And the third number (-1) tells Python how to move from one number to the next, in our case, backwards by 1. If you wanted the list in reversed sorted order, then you should do some_numbers.sort (reverse = True). Again, if you don't want to change the list and just want a copy, call sorted (some_numbers, reverse = True).
answers question: http://stackoverflow.com/q/51237093

http://stackoverflow.com/a/51215579
type: Answer
has comment: http://stackoverflow.com/comment/89414488
has comment: http://stackoverflow.com/comment/89412249
has comment: http://stackoverflow.com/comment/89414454
has body: You must call the function after you define it. Also as C Haworth pointed out, you have a typo when calling your function. I've corrected that below. str_horas= input('Digite as horas: ') str_taxa=input('Digite a taxa: ') #calcula_pagamento = ( ) def calcular_pagamento (qtd_horas, valor_hora): horas = float(qtd_horas) taxa = float(valor_hora) if horas &lt;= 40: salario = horas*taxa else: h_excd = horas - 40 salario = 40*taxa+(h_excd*(1.5*taxa)) return salario print('O valor de seus rendimentos é R$',total_salario) total_salario = calcular_pagamento(str_horas,str_taxa)
answers question: http://stackoverflow.com/q/51215537
has comment: http://stackoverflow.com/comment/89412310
accepted answer of: http://stackoverflow.com/q/51215537
has comment: http://stackoverflow.com/comment/89415240
type: AcceptedAnswer
score: 0

http://stackoverflow.com/comment/89588585
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51301798
has text: @Piotrek No. `~` means the home folder path. Are you using windows or linux?

http://stackoverflow.com/a/51222624
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/51221489
accepted answer of: http://stackoverflow.com/q/51221489
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89427998
has body: if you use recursion it is relatively easy. for this first example, i tried to keep the same organization as yours: each criteria is a list containing attributes and children but both stored as dicts instead of tuples def get_data(el): if el.tag =='criteria': data = {'criteria': [el.attrib]} for desc in el.iterchildren(): data['criteria'].append(get_data(desc)) return data else: return {'criterion': el.attrib} the problem is that the data returned is not easily usable: each criteria can contain up to three dicts (attributes, criterion or criteria) and you'll have to make some tests to know which is which. in this second example you know in advance what a list contains: if the key is criteria you know you'll have a list of criteria-dicts. def get_data(el): if el.tag =='criteria': data = {} data.update(el.attrib) for desc in el.iterchildren(): key = desc.tag if not key in data: data[key] = [] data[key].append(get_data(desc)) return data else: return el.attrib
type: Answer

http://stackoverflow.com/q/51250413
favorite count: 0
tagged with: python-3.x
tagged with: python
type: AnsweredQuestion
has body: I need help on list append. I have to export it into CSV with the respective list index. lst1 = ['a', 'b', 'c'] lst2 = ['w', 'f', 'g'] lst3 = ['e', 'r', 't'] ap = [] ap.append((lst1, lst2, lst3)) output: [(['a', 'b', 'c'], ['w', 'f', 'g'], ['e', 'r', 't'])] Expected output: [('a', 'w', 'e') ('b', 'f', 'r') ('c', 'g', 't')] I need to export to Excel via Pandas, please help. col1 col2 col3 a w e b f r c g t
upvote count: 1
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/51250454
tagged with: dataframe
has title: Python List append with respective index
accepted answer: http://stackoverflow.com/a/51250454
score: 0
tagged with: pandas
answer count: 1

http://stackoverflow.com/q/51290347
answer count: 1
has comment: http://stackoverflow.com/comment/89560131
favorite count: 0
type: UnansweredQuestion
tagged with: python
has title: Pandas is Trying to convert my path to a float when inputing to csv cell?
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/89561243
has comment: http://stackoverflow.com/comment/89558973
has body: I'm trying to save a path into a cell of a csv file for reference, but it's giving me error: ValueError: could not convert string to float: [path] class Program: def __init__(self, master): self.data = pd.read_csv("SourcingPython\\ProgramData.csv") if pd.isnull(self.data.User[0]): path = os.getcwd() fair = path.split("\\") for i in fair: if i.isdigit(): link = i self.data.to_csv("SourcingPython\\ProgramData.csv", index=False) def inputSelect(self): self.data.Input.at[0]= askopenfilename() print(self.data.Input[0]) self.data.to_csv("SourcingPython\\ProgramData.csv", index=False) self.inLabel = Label(text=self.data.Input[0], relief=SUNKEN,width=50).grid(row=1,column=1) root.update()
has comment: http://stackoverflow.com/comment/89558433
has comment: http://stackoverflow.com/comment/89559089
score: -1
tagged with: pandas
has answer: http://stackoverflow.com/a/51294463
upvote count: 0

recaptcha
tags question: http://stackoverflow.com/q/51205976
tag name: recaptcha
tags question: http://stackoverflow.com/q/51281805
type: Tag

http://stackoverflow.com/comment/89536785
comment on: http://stackoverflow.com/a/51279680
has text: If you are keeping cash as global then you should keep coins as global too.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/89425026
has text: @user382086 could you please find where your `boto` package is installed and just add that path to sys.path: `sys.path.append( BOTO_PATH )` ? you can easily do that by running python, and `import boto` + `boto.__path__`
comment on: http://stackoverflow.com/a/51222162
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/89451625
has text: use sqlalchemy to issue a create table statement first before trying to upload the data frame to that table?
comment on: http://stackoverflow.com/q/51236304
type: QuestionComment
type: Comment
score: 1

http://stackoverflow.com/q/51247928
upvote count: 6
has comment: http://stackoverflow.com/comment/89474715
tagged with: dataframe
has comment: http://stackoverflow.com/comment/89474783
has answer: http://stackoverflow.com/a/51248064
downvote count: 1
has comment: http://stackoverflow.com/comment/89474676
type: Question
tagged with: pandas
type: AnsweredQuestion
has title: how to do math operations on a pandas columns and save it as a new dataframe
accepted answer: http://stackoverflow.com/a/51248064
has comment: http://stackoverflow.com/comment/89474654
possible better answer: http://stackoverflow.com/a/51248353
favorite count: 0
has answer: http://stackoverflow.com/a/51248353
has body: a b c 6/29/2018 0.744189037 0.251833984 0.632784618 6/30/2018 0.476601558 0.694181607 0.7951655 7/1/2018 0.91376258 0.111712256 0.813708374 7/2/2018 0.849505199 0.037035716 0.973137932 So I am trying to use this data frame and create a new one based off of math operations. So far I have df3 = df2'a','b' and df4 = pd.DataFrame(df3'a'*2 - df3'b'). To summarize, I want to use df3 and multiple column a by 2 and subtract that value by column b and put the result into a brand new data frame. The final output that I would want to get too would be 2*a-b 6/29/2018 1.23654409 6/30/2018 0.259021508 7/1/2018 1.715812903 7/2/2018 1.661974683 However this yields all values of NA.
answer count: 2
score: 5
tagged with: python

http://stackoverflow.com/q/51248067
has comment: http://stackoverflow.com/comment/89481106
has title: While loop is not terminating due to socket function
has comment: http://stackoverflow.com/comment/89505441
has comment: http://stackoverflow.com/comment/89475934
favorite count: 0
tagged with: while-loop
tagged with: sockets
tagged with: python
has comment: http://stackoverflow.com/comment/89481450
has comment: http://stackoverflow.com/comment/89482680
answer count: 0
type: UnansweredQuestion
has body: I am trying to run two while loops in this program. The first while loop needs to run up to 50 seconds but this loop does not exit after 50 seconds (Not terminating after 50 Seconds), it just continues. I verified the timer in a separate program, where timer works well,but in my program timer is not working. import array import time import socket import os,sys import concurrent.futures import struct Nmax_Per_hop=100 hello_Broadcast_Period=40 NeighborDiscovery_Time_Interval=50 MyNeighborSet_ip=[] all_ip=[] a=10 b=0 start_time=time.time() My_ip='192.168.1.1' ############################################################################# def broadcast_hello(): # (send 'Hello message') ip1 = "192.168.1.254" print ("[tx]------>hello to:"+ ip1) PORT = 12345 with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s: s.setsockopt(socket.SOL_SOCKET,socket.SO_BROADCAST,1) s.sendto (b'Hello',('192.168.1.254',PORT)) ########################################################################## def received_hello(): PORT = 12345 ip=[] recv_message_hello=[] global a s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM) s.bind(('',PORT)) message=s.recvfrom(4096) print ("before the ip") ip=message[1][0] if (ip not in all_ip): all_ip.append(ip) print (all_ip) recv_message=message[0] if not recv_message in recv_message_hello: recv_message_hello=recv_message if (ip==My_ip): pass elif ip not in MyNeighborSet_ip : MyNeighborSet_ip.append(ip) else: print ("Already in List") print ("[N-Set]------------:",MyNeighborSet_ip) ########################################################################## temp = concurrent.futures.ThreadPoolExecutor (max_workers=2) Here this loop is not working well while(((time.time()-start_time)<NeighborDiscovery_Time_Interval) and (len(MyNeighborSet_ip) <= Nmax_Per_hop)): if (time.time()-start_time<hello_Broadcast_Period): temp.submit(broadcast_hello) try: temp.submit(received_hello) except: print("###################") print ("IP of this node is: ",My_ip) print ("[N-Set…
tagged with: loops
upvote count: 1
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/89494476
score: 0

sidebar
type: Tag
tag name: sidebar
tags question: http://stackoverflow.com/q/51306328

http://stackoverflow.com/q/51267827
has comment: http://stackoverflow.com/comment/89514202
linked to: http://stackoverflow.com/q/132988
has comment: http://stackoverflow.com/comment/89514300
answer count: 0
duplicate of: http://stackoverflow.com/q/132988
type: UnansweredQuestion
has body: My understanding of "is" is that it checks if the two operands point to the same structure. I am unsure why this is true x = 1 y = 1 y is x and why this is false l1 = [1,2,3] l2 = [1,2,3] l1 is l2 Similarly, why is the first not false as well? Is it saying that when I initialize x, it creates the object with int value "1", and from now on, whenever I initialize variables to have "1", it will point to the first object. If so, I am curious why its not the same with the second example.
favorite count: 0
type: Question
has title: What is 'is' in Python?
has comment: http://stackoverflow.com/comment/89514267
tagged with: python
score: 0
upvote count: 1
downvote count: 1

http://stackoverflow.com/q/51280706
has comment: http://stackoverflow.com/comment/89539430
has body: I am writing a program where the user is asked to type in his name. If the name starts with a, b or c, the program should print ("Your name starts with a, b or c"). Unfortunately if the user starts by typing in a space and then typing his name the program thinks the name starts with a space and it automatically prints "Your name doesn't start with a, b or c" even if the name starts with these letters. I want to delete the space in the input now so this problem doesn't occure any longer. So far I've tried if name.startswith((" ")): name.replace(" ", "") Thanks for any help! name = input("Hi, who are you?") if name.startswith((" ")): name.replace(" ", "") if name.startswith(('a', 'b', 'c')): print("Your name starts with a, b or c") print(name) else: print("Your name doesn't start with a, b or c") print(name)
tagged with: space
has answer: http://stackoverflow.com/a/51280971
has comment: http://stackoverflow.com/comment/89539561
favorite count: 0
has comment: http://stackoverflow.com/comment/89539145
upvote count: 2
accepted answer: http://stackoverflow.com/a/51281004
has comment: http://stackoverflow.com/comment/89538879
tagged with: input
tagged with: python
downvote count: 1
answer count: 4
has answer: http://stackoverflow.com/a/59606225
has answer: http://stackoverflow.com/a/51280875
type: AnsweredQuestion
score: 1
possible better answer: http://stackoverflow.com/a/51280875
has title: How to delete space in the input in Python
type: Question
tagged with: startswith
has comment: http://stackoverflow.com/comment/89538766
has comment: http://stackoverflow.com/comment/89538780
has answer: http://stackoverflow.com/a/51281004

http://stackoverflow.com/q/51243515
has comment: http://stackoverflow.com/comment/89479790
tagged with: ubuntu
has answer: http://stackoverflow.com/a/51245893
linked to: http://stackoverflow.com/q/7669508
has comment: http://stackoverflow.com/comment/89468891
has comment: http://stackoverflow.com/comment/89469190
answer count: 4
possible better answer: http://stackoverflow.com/a/56727855
type: AnsweredQuestion
has body: I'm using code examples from the 'Django 2 by Example' book to build my e-commerce shop. The view works as it should, but the task never gets executed. There are no errors. Page is freezing on "Waiting for localhost...". What I'm doing wrong in the code? views.py import ... from .tasks import order_created def order_create(request): cart = Cart(request) if request.method == 'POST': form = OrderCreateForm(request.POST) if form.is_valid(): order = form.save(commit=False) if cart.promo_code: order.promo_code = cart.promo_code order.discount = cart.promo_code.discount order.save() for item in cart: OrderItem.objects.create(order=order, book=item['book'], price=item['price'], quantity=item['quantity']) # clear the cart cart.clear() print("clean cart") # set the order in the session request.session['order_id'] = order.id print("id - check") # launch asynchronous task order_created.delay(order.id) # here I stuck print("clean cart") # redirect for payment return redirect(reverse('payment:process')) else: form = OrderCreateForm() return render(request, 'orders/order/create.html', {'cart': cart, 'form': form}) tasks.py from celery import task from django.core.mail import send_mail from .models import Order @task def order_created(order_id): """ Task to send an e-mail notification when an order is successfully created. """ order = Order.objects.get(id=order_id) subject = 'Order nr. {}'.format(order.id) message = 'Dear {},\n\nYou have successfully placed an order.\ Your order id is {}.'.format(order.first_name, order.id) mail_sent = send_mail(subject, message, 'archeski.dk@gmail.com', [order.email]) return mail_sent I'm using celery==4.2.0 Django==2.0.7 Ubuntu 18.04 UPDATED: Added this two lines of code in celery.py. And freezing has disappear, order page now redirects me for further payment prosedure. But the task order_created still not running. app.conf.broker_url = 'redis://localhost:6379/1' # app.conf.broker_transport_options = {'visibility_timeout': 3600} # 1 hour. app.co…
score: 3
has answer: http://stackoverflow.com/a/77671697
downvote count: 0
has comment: http://stackoverflow.com/comment/89467386
favorite count: 0
tagged with: orders
has comment: http://stackoverflow.com/comment/89467695
has comment: http://stackoverflow.com/comment/89466484
has answer: http://stackoverflow.com/a/63187774
has comment: http://stackoverflow.com/comment/89466342
type: Question
has title: Django: celery task does not execute with .delay()
accepted answer: http://stackoverflow.com/a/51245893
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/89466266
upvote count: 3
tagged with: celery
has answer: http://stackoverflow.com/a/56727855

http://stackoverflow.com/comment/89346825
has text: @ScottHunter This is all that’s needed is kind of the whole point—not only that, it’s just a specific instance of a general problem with recursion that can always be solved this way (e.g., when the OP later needs to write pre-order, in-order, and post-order tree traversals, remembering this answer will tell them how to solve that one too).
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/51181996
type: Comment

http://stackoverflow.com/comment/89550953
comment on: http://stackoverflow.com/a/51286316
type: Comment
score: 0
type: AnswerComment
has text: @Mathieson: not sure what you mean. The *instance* should be imported from the same module, so that it's guaranteed to be the same instance. Whether that instance is initialised in the same file as the class definition, or imports its class definition from another module, doesn't matter

http://stackoverflow.com/q/51211176
has comment: http://stackoverflow.com/comment/89408276
has comment: http://stackoverflow.com/comment/89408643
has comment: http://stackoverflow.com/comment/89407961
has comment: http://stackoverflow.com/comment/89408530
has answer: http://stackoverflow.com/a/51212737
has comment: http://stackoverflow.com/comment/89408957
linked to: http://stackoverflow.com/q/51210686
has answer: http://stackoverflow.com/a/73127108
has comment: http://stackoverflow.com/comment/89408621
has body: EDIT: I've gotten a lot of useful feedback on how not to do this and how to find alternatives, but making that useful depends on idiosyncrasies of my use case that would make this question less useful to others. At this point, I'm not looking for alternatives to using data structured like this. I'm looking for why it seems to be impossible to do this in numpy (or how to do it if it's not impossible) I have a numpy array, which looks like a = array([list([1]), list([4, 5])], dtype=object) I want to append a list like b = [2, 3, 4] To get a result like array([list([1]), list([4, 5]), list([2, 3, 4])], dtype=object) However, every method I've tried has produced: array([list([1]), list([4, 5]), 2, 3, 4], dtype=object) I've tried vstack, concatenate, and append, as well as wrapping things in lists or ndarrays. Why am I doing this? Basically, I have a lot of data in an ndarray that's going to get fed into sklearn. I want to have a 3d ndarray (data sets x data points x features) but incoming data is bad and certain things have different lengths, so the innermost dimension has to be lists. I'm trying to append a derived feature, which keeps failing. I've managed to reorder the operations to avoid needing to do this appending, but I still want to know how to do it. This seems like an odd failure for numpy. edit: In short, the outer array must be an ndarray because it's actually 2d, and complex slicing is frequently used, while the append operation occurs very few times.
answer count: 3
has comment: http://stackoverflow.com/comment/89409066
has comment: http://stackoverflow.com/comment/89407613
has comment: http://stackoverflow.com/comment/89408418
has comment: http://stackoverflow.com/comment/89408484
favorite count: 0
has comment: http://stackoverflow.com/comment/89408432
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/993984
tagged with: python
has answer: http://stackoverflow.com/a/51214008
has comment: http://stackoverflow.com/comment/89409509
has comment: http://stackoverflow.com/comment/89408995
score: 1
upvote count: 3
has comment: http://stackoverflow.com/comment/89403150
downvote count: 2
linked to: http://stackoverflow.com/q/51095427
has title: How to append a list of primitives to a numpy array of objects
has comment: http://stackoverflow.com/comment/89409485
linked to: http://stackoverflow.com/q/50328737
type: Question
tagged with: numpy

http://stackoverflow.com/q/51206457
answer count: 0
tagged with: dataset
tagged with: scikit-learn
favorite count: 0
type: Question
tagged with: python
tagged with: sklearn-pandas
has comment: http://stackoverflow.com/comment/89393927
score: 0
has body: Can we fit a different data set (let`s say Y) to calculate a mean value and transform it to the X data sets? Can we provide a default value when a NULL value occurs in a data set using Imputer object. from sklearn.preprocessing import Imputer imputer = Imputer(missing_values='NaN', strategy='mean',axis=0) #Y data set in fit imputer imputer = imputer.fit(Y[:, 1:3]) #Here I want to set the mean value created from Y data set and transform it #to the X. How can we handle this scenario. X[:, 1:3]=imputer.transform(X[:, 1:3]) Instead of using fit, can we set any predefined default values?
tagged with: machine-learning
upvote count: 1
has comment: http://stackoverflow.com/comment/89394930
downvote count: 1
has title: Set default values in Imputer object using different dataset
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89393959

http://stackoverflow.com/q/51315566
linked to: http://stackoverflow.com/q/50559000
has comment: http://stackoverflow.com/comment/89607951
has title: How to display the images side by side in jupyter notebook
answer count: 4
tagged with: jupyter-notebook
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51315688
tagged with: python
has answer: http://stackoverflow.com/a/60090292
has comment: http://stackoverflow.com/comment/89607788
has answer: http://stackoverflow.com/a/60090402
type: Question
has body: I have used the following code but it is displaying the images vertically. I want them to display side by side in a Jupyter Notebook. display(Image.open(BytesIO(Item[iii][b'imgs']))) display(Image.open(BytesIO(Item[jjj][b'imgs']))) I have tried using this code display(HTML("&lt;table&gt;&lt;tr&gt;&lt;td&gt;display(Image.open(BytesIO(Item[jjj][b'imgs'])))) but it is display the text display(Image.open(BytesIO(Item[jjj][b'imgs']))))
score: 8
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/51316108
has comment: http://stackoverflow.com/comment/89607643
upvote count: 8

http://stackoverflow.com/comment/89449258
comment on: http://stackoverflow.com/q/51235094
score: 0
type: Comment
type: QuestionComment
has text: Actionally: No...

http://stackoverflow.com/comment/89483363
score: 5
comment on: http://stackoverflow.com/q/51252214
type: Comment
type: QuestionComment
has text: I really don't think we can answer this with the information you've given. What's the directory structure? What import statements are you using in each file?

http://stackoverflow.com/comment/89339513
type: QuestionComment
comment on: http://stackoverflow.com/q/51177788
score: 0
has text: Did you profile what your slow part was/is?
type: Comment

http://stackoverflow.com/comment/89345930
type: QuestionComment
has text: OK, but maybe you can humor me and check anyway. Thanks.
score: 0
comment on: http://stackoverflow.com/q/51181129
type: Comment

http://stackoverflow.com/comment/89325506
type: Comment
comment on: http://stackoverflow.com/q/51171367
type: QuestionComment
score: 1
has text: Welcome to SO. Please provide a [mcve]. Here, *show* (not just describe) us your desired output and what you've tried already.

http://stackoverflow.com/comment/89514843
has text: something in your url mappings and/or template links is wrong... care to post your urls.py/template with link?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51268192

http://stackoverflow.com/a/51181300
type: Answer
answers question: http://stackoverflow.com/q/51181082
has body: If you want to encode all days of the week for a prediction, monday should probably be [1,0,0,0,0,0,0]. Or you use regression (0.0 - 6.0) instead of classification. But, since you used X instead of y here, I'm not sure if your provided X=['Monday','January','South'] is meant to be the input rather than the output (y). If it is, you do not need a one-hot encoding and you can just encode as e.g. X=[0,0,2] with Monday 0 Tuesday 1 ... January 0 February 1 North 0 East 1 ... I agree with @morsecodist that more information is needed for a proper answer to your question.
score: 0

http://stackoverflow.com/q/51274687
accepted answer: http://stackoverflow.com/a/51274734
type: AnsweredQuestion
upvote count: 0
has answer: http://stackoverflow.com/a/51274734
score: -1
type: Question
tagged with: numpy
tagged with: pandas
answer count: 1
downvote count: 1
tagged with: python
has body: Here's the code I've been working on. import numpy as np import pandas as pd from sklearn.datasets import load_boston housing = load_boston() housing = pd.DataFrame(housing.data, columns = housing.feature_names) housing['target'] = pd.Series(housing.target) The error description is as follows AttributeError Traceback (most recent call last) &lt;ipython-input-46-db1e02afaf46&gt; in &lt;module&gt;() 12 13 housing = pd.DataFrame(housing.data, columns = housing.feature_names) ---&gt; 14 housing['target'] = pd.Series(housing.target) /anaconda3/lib/python3.6/site-packages/pandas/core/generic.py in __getattr__(self, name) 4370 if self._info_axis._can_hold_identifiers_and_holds_name(name): 4371 return self[name] -&gt; 4372 return object.__getattribute__(self, name) 4373 4374 def __setattr__(self, name, value): AttributeError: 'DataFrame' object has no attribute 'target'
favorite count: 0
has title: Unable to convert sklearn's bunch object into Pandas series object

http://stackoverflow.com/comment/131277783
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/51554106
has text: Note that this works properly only if the entire content of the cell is bold/not bold.
type: Comment

http://stackoverflow.com/comment/89423990
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51221710
score: 1
has text: @LucaCappelletti I think `newspapers` is a module. http://newspaper.readthedocs.io/en/latest/

http://stackoverflow.com/comment/89619460
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51321610
type: Comment
has text: Is too long, I edited the main post

http://stackoverflow.com/comment/89453877
comment on: http://stackoverflow.com/a/51237375
type: Comment
has text: good one.. thank you
type: AnswerComment
score: 0

http://stackoverflow.com/comment/89451451
comment on: http://stackoverflow.com/a/51236118
type: Comment
score: 0
has text: yes, didn't know couldn't copy paste. Sorry. It worked :D Thank you so much
type: AnswerComment

http://stackoverflow.com/comment/89341570
type: QuestionComment
type: Comment
score: 0
has text: please post how your data is structured, ie do you plot from numpy arrays, or a pandas dataframe, ...? So that answers can start from this common base.
comment on: http://stackoverflow.com/q/51173761

http://stackoverflow.com/comment/89483677
type: QuestionComment
has text: Possible duplicate of https://stackoverflow.com/questions/31828240/first-non-null-value-per-row-from-a-list-of-pandas-columns/31828559
comment on: http://stackoverflow.com/q/51252225
score: 0
type: Comment

http://stackoverflow.com/comment/89495932
type: AnswerComment
has text: The primary reason I didn't use @challenge.command() in phase is that phase needs to be a group. I have more subcommands of the format `cli challenge 1 phase 1 subcommands` So I needed phase as a group. Is there a better way to solve this?
score: 0
comment on: http://stackoverflow.com/a/51255662
type: Comment

http://stackoverflow.com/comment/89522073
type: QuestionComment
has text: nvm, i placed it in libs, found now
comment on: http://stackoverflow.com/q/51270719
score: 0
type: Comment

http://stackoverflow.com/q/51279903
score: 1
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/51279994
has comment: http://stackoverflow.com/comment/89539366
tagged with: dataframe
has comment: http://stackoverflow.com/comment/89539815
tagged with: apply
answer count: 2
has comment: http://stackoverflow.com/comment/89537271
tagged with: pandas
has body: I have two functions applied on a dataframe res = df.apply(lambda x:pd.Series(list(x))) res = res.applymap(lambda x: x.strip('"') if isinstance(x, str) else x) {{Update}} Dataframe has got almost 700 000 rows. This is taking much time to run. How to reduce the running time? Sample data : A ---------- 0 [1,4,3,c] 1 [t,g,h,j] 2 [d,g,e,w] 3 [f,i,j,h] 4 [m,z,s,e] 5 [q,f,d,s] output: A B C D E ------------------------- 0 [1,4,3,c] 1 4 3 c 1 [t,g,h,j] t g h j 2 [d,g,e,w] d g e w 3 [f,i,j,h] f i j h 4 [m,z,s,e] m z s e 5 [q,f,d,s] q f d s This line of code res = df.apply(lambda x:pd.Series(list(x))) takes items from a list and fill one by one to each column as shown above. There will be almost 38 columns.
downvote count: 0
accepted answer: http://stackoverflow.com/a/51279994
favorite count: 0
tagged with: series
has answer: http://stackoverflow.com/a/75892481
tagged with: python
has title: pandas apply and applymap functions are taking long time to run on large dataset
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89551128
possible better answer: http://stackoverflow.com/a/75892481

http://stackoverflow.com/a/51766992
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/51306645
has body: Try using criterion='maxclust' instead. This way you specify the number of clusters you want. res = hierarchy.fclusterdata(embeddings, k, criterion='maxclust', method='ward', metric='euclidean')
score: 1
upvote count: 1

http://stackoverflow.com/q/51201995
tagged with: python
has title: Django modelformset_factory UnboundLocalError
has answer: http://stackoverflow.com/a/51202037
type: AnsweredQuestion
tagged with: formset
score: 1
tagged with: django
upvote count: 1
linked to: http://stackoverflow.com/q/4395230
type: Question
accepted answer: http://stackoverflow.com/a/51202037
tagged with: local
answer count: 1
downvote count: 0
tagged with: variables
has body: I am getting error message the UnboundLocalError local variable 'Assumptions' referenced before assignment (after line else:). I wonder how is that even possible given that Assumptions is a model and is imported to the views.py. Any advise how to solve it would be highly appreciated. Also, I am trying to create multiple forms based on Assumptions modelform and save them into the database model Assumptions. Please advise if this code is the correct design pattern. Thank you. views.py from django.shortcuts import render from .forms import modelformset_factory, AssumptionsForm from .models import Assumptions def get_assumptions(request): if request.method == 'POST': if 'name' in request.POST: formset = modelformset_factory(Assumptions, form = AssumptionsForm, extra = 5) if formset.is_valid(): print('valid form') for form in formset: print('Looping forms') Assumptions = form.save(commit='False') Assumptions.Name = 'name' Assumptions.save() else: formset = modelformset_factory(Assumptions, form = AssumptionsForm, extra = 5) return render(request, 'assumptions.html', {'formset': formset}) assumptions.html {% csrf_token %} {{ formset.management_form }} {{ formset.non_form_errors.as_ul }} {% for name in ['A', 'B'] %} var {% for form in formset.forms %} {% if forloop.first %} {% for field in form.visible_fields %} {% endfor %} {% endif %} {% for field in form.visible_fields %} {# Include the hidden fields in the form #} {% if forloop.first %} {% for hidden in form.hidden_fields %} {{ hidden }} {% endfor %} {% endif %} {{ field.errors.as_ul }} {{ field }} {% endfor %} {% endfor %} {% endfor %} forms.py from django import forms from django.forms import modelformset_factory, ModelForm from .models import Assumptions class AssumptionsForm(ModelForm): class Meta: model = Assumptions fields = ['Worst', 'Base', 'Best'] exclude = ['Name'] models.py from django.db import models from django.forms import ModelForm class Assumptions(models.Model): Worst = mode…
favorite count: 0
linked to: http://stackoverflow.com/q/51203547

http://stackoverflow.com/comment/89585074
type: Comment
has text: No I didn't thanks a lot! Please post it as an answer
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51303995

http://stackoverflow.com/q/51179236
has comment: http://stackoverflow.com/comment/89341089
has answer: http://stackoverflow.com/a/51179269
tagged with: python
accepted answer: http://stackoverflow.com/a/51179640
has title: What is the python equivalent of JavaScript's Array.prototype.find?
has answer: http://stackoverflow.com/a/63673543
has comment: http://stackoverflow.com/comment/89350506
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51179640
possible better answer: http://stackoverflow.com/a/51179269
has body: I'm looking for something like: find(pred, iter) in python obj = { "foo_list": [ {"name": "aaaa", "id": 111}, {"name": "bbbb", "id": 222}, {"name": "cccc", "id": 333} ] } How to: find(lambda x: x.get("name") == "bbbb", obj.get("foo_list", []))
type: Question
answer count: 3
tagged with: find
downvote count: 1
upvote count: 29
favorite count: 0
score: 28

http://stackoverflow.com/q/51217782
has comment: http://stackoverflow.com/comment/89443831
type: Question
has body: ModuleNotFoundError Traceback (most recent call last) in () 1 import pyaudio 2 import sys 3 4 #sys.path.append('c:\\users\\neel.nath\\appdata\\local\\programs\\python\\python36\\lib\\site-packages') 5 PyAudio = pyaudio.PyAudio #initialize pyaudio ModuleNotFoundError: No module named 'pyaudio' I have got this error. Pyaudio is installed in the location which I have commented. Append function for sys.path does not work. How do I go about it?
upvote count: 1
tagged with: jupyter-notebook
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89480992
has title: Jupyter ModuleError pyaudio
tagged with: python
downvote count: 0
answer count: 0
score: 1

http://stackoverflow.com/q/51244299
upvote count: 3
has comment: http://stackoverflow.com/comment/89469158
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/89469126
accepted answer: http://stackoverflow.com/a/51245446
tagged with: dataframe
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/51246358
has title: Get the difference between dataframes according to specific columns pandas
downvote count: 0
has comment: http://stackoverflow.com/comment/89469090
favorite count: 0
possible better answer: http://stackoverflow.com/a/51246358
tagged with: pandas
tagged with: python
has answer: http://stackoverflow.com/a/51245446
has comment: http://stackoverflow.com/comment/89468152
has body: I have multiple big dataframes and I need to get the difference between them, according to specific columns, while keeping the data of the other columns. for example, if I have 2 dataframes as below. df1: num Ref Alt DP NL 0 300 C A 50.0 30.0 1 500 C A 45.0 90.0 2 255 A C 69.0 26.0 3 450 B B 55.0 25.0 df2: num Ref Alt DP NL 0 300 C A 71.0 88.0 1 500 A A 45.0 54.0 2 255 A A 55.0 55.0 3 450 B B 70.0 15.0 I'd like to get the difference between those dataframes according to specific columns ['num','Ref','Alt'] while keeping the data form the remaining columns ['DP', 'NL']. In the example, rows 0 and 3 are the same across the 2 dataframes (since ['num','Ref','Alt'] are the same), so the output dataframes should look something like that: df1: num Ref Alt DP NL 0 500 C A 45.0 90.0 2 255 A C 69.0 26.0 df2: num Ref Alt DP NL 1 500 A A 45.0 54.0 2 255 A A 55.0 55.0 or get it in the same dataframe, if possible... I've tried to think of few solutions,one is concatenating them and then remove the duplicates, but beacuse they are bif dataframes, it might cause problems,or looping through the dataframes and use the below script: temp_df = df_list[0] for df in df_list[1:]: df_filtered_for_diff = pd.merge(temp_df, df, on=['num', 'Ref', 'Alt'], how='outer') temp_df = df_filtered_for_diff return (temp_df) but I was wondering if there are better solutions?
tagged with: python-3.x

http://stackoverflow.com/comment/89530987
has text: isn't working for some reason `@client.event async def hirac(): await client.wait_until_ready() while not client.is_closed: for server in client.servers: await client.move_role(server, server.me.roles, 1) `
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51263991
type: AnswerComment

http://stackoverflow.com/q/51197683
type: Question
has comment: http://stackoverflow.com/comment/89377726
answer count: 2
has comment: http://stackoverflow.com/comment/89377854
linked to: http://stackoverflow.com/q/38087558
has comment: http://stackoverflow.com/comment/89377627
has answer: http://stackoverflow.com/a/78333874
has answer: http://stackoverflow.com/a/72915567
has comment: http://stackoverflow.com/comment/89377301
has comment: http://stackoverflow.com/comment/89427199
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89377270
has comment: http://stackoverflow.com/comment/89377784
has comment: http://stackoverflow.com/comment/89377589
has comment: http://stackoverflow.com/comment/89377094
tagged with: python
has body: I have imported the scikit-image library using the following code: from skimage.measure import compare_ssim as ssim And I used the library here in my program: s = ssim(imageA, imageB) However, I keep getting this error: from skimage.measure import compare_ssim as ssim ModuleNotFoundError: No module named 'skimage' I have installed scikit-image on my computer, so I am not sure why it is not recognizing this library.
has comment: http://stackoverflow.com/comment/89377495
has title: Module Not Found Error for Skimage
score: 0
tagged with: scikit-image
has comment: http://stackoverflow.com/comment/89377464

http://stackoverflow.com/comment/89452070
comment on: http://stackoverflow.com/q/51236529
has text: Why did you expect it to print twice?
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/a/51628396
answers question: http://stackoverflow.com/q/51195491
has comment: http://stackoverflow.com/comment/90341458
has comment: http://stackoverflow.com/comment/90282004
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90471398
has comment: http://stackoverflow.com/comment/90341748
has body: I believe that the object is created, but your form_valid doesn't return to the success_url. At the end of your form_valid you should redirect to success_url. I don't understand what you're trying to achieve with your return at the end of form_valid. def form_valid(self, form): ... return HttpResponseRedirect(self.get_success_url()) And you can than also override success_url and add massage if needed. def get_success_url(self): # add message messages.add_message(self.request, messages.SUCCESS, 'Your message.') # reverse back to providers' page with success message return reverse_lazy('engineering:gaas_wafer_design_list') I have written a simple to use package for such functionalities and you can check it out at django-bootstrap-modal-forms.
type: Answer
accepted answer of: http://stackoverflow.com/q/51195491

http://stackoverflow.com/comment/89333286
has text: I've found the problem. If you're interested you can read the update#2 in my question.
comment on: http://stackoverflow.com/a/51169833
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/51237274
accepted answer: http://stackoverflow.com/a/51237503
answer count: 2
has comment: http://stackoverflow.com/comment/89453557
has comment: http://stackoverflow.com/comment/89457975
favorite count: 0
linked to: http://stackoverflow.com/q/2192547
tagged with: python-internals
has body: I have a wrapper class as in the example below, written in Python. class Foo: def __init__(self, bar=None): if bar: self._bar = bar else: self._bar = CreateBarObject("value") I create an instance via the Python C API // c++ pseudo code for convenience auto obj = PyObject_CallObject(Foo) auto bar = CreateBarObject("another_value"); PyObject_SetAttrString(obj, "_bar", bar) As you can see from the code, Foo.__init__ will be called when an instance gets created which creates a new bar object. But I would like to bypass this "heavy" operation. So any safe way to create an instance of Foo so I can set self._bar via the Python C API? Any ideas?
has title: Initialize PyObject without calling __init__
tagged with: python
possible better answer: http://stackoverflow.com/a/51237416
has comment: http://stackoverflow.com/comment/89453514
has comment: http://stackoverflow.com/comment/89453821
has comment: http://stackoverflow.com/comment/89471589
has answer: http://stackoverflow.com/a/51237416
has comment: http://stackoverflow.com/comment/89453668
upvote count: 2
has answer: http://stackoverflow.com/a/51237503
tagged with: cpython
has comment: http://stackoverflow.com/comment/89453658
downvote count: 1
type: AnsweredQuestion
score: 1
tagged with: http://stackoverflow.com/tag/c
type: Question

http://stackoverflow.com/a/51263293
upvote count: 3
type: Answer
score: 3
answers question: http://stackoverflow.com/q/51263226
has body: One approach using lambda and map Demo: makeDict = lambda x: { "id": x.get('_id'), "Temperature": x.get('data_Temperature'), "time_utc": x.get('data_time_utc'), "longitude": x.get('location_0'), "latitude": x.get('location_1'), "altitude": x.get('altitude'), } print( list(map(makeDict, data1)) ) Output: [{'Temperature': 14, 'time_utc': 1403560800, 'altitude': 74, 'longitude': 9.6071829, 'latitude': 55.726223, 'id': '4nPkqDbLZU'}, {'Temperature': 29, 'time_utc': 1403560900, 'altitude': 74, 'longitude': 9.6071829, 'latitude': 55.726223, 'id': '4nPkqDbL855'}]
downvote count: 0

http://stackoverflow.com/a/51184888
upvote count: 1
has comment: http://stackoverflow.com/comment/89353952
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51184617
type: Answer
answers question: http://stackoverflow.com/q/51184617
has comment: http://stackoverflow.com/comment/89353507
score: 1
has comment: http://stackoverflow.com/comment/89352233
has body: Not sure if i understand your question correctly, are you trying to iterate through the items in list in pairs? If so it is pretty straight forward: for i in grouped_shapefiles: pst = gpd.read_file(i[0]) dbound = gpd.read_file(i[1]) if i[0].split("\\")[-3] == i[1].split("\\")[-3]: dbound.reset_index(inplace=True) wdp = gpd.sjoin(pst, dbound, how="inner", op='within') wdp['DEC_ID'] = wdp['index'] else: print ("Folder pairs mismatch") Edited as per my understanding
has comment: http://stackoverflow.com/comment/89351828
downvote count: 0
has comment: http://stackoverflow.com/comment/89353705

http://stackoverflow.com/q/51319234
has comment: http://stackoverflow.com/comment/89614348
downvote count: 1
has title: i am not able to display doc string of instance of a class
type: Question
has answer: http://stackoverflow.com/a/51319948
linked to: http://stackoverflow.com/q/713138
tagged with: class
score: 0
answer count: 3
upvote count: 1
has answer: http://stackoverflow.com/a/51319331
favorite count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51319334
tagged with: python
has body: def display(): """ i am testing to see doc string """ pass display_1=display() print(display.__doc__) output-:i am testing to see doc string print(display_1.__doc__) output-:None

http://stackoverflow.com/comment/89575648
has text: Thanks for the answer, but I tried this method and the outcome was the same.
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51289294
score: 1

http://stackoverflow.com/q/51200552
answer count: 0
upvote count: 3
type: Question
has body: My skorch Neural Net GridsearchCV code is running, it just appears to not be on the GPU so it is slow. Any help appreciated. It takes 13 seconds per epoch. I know that pytorch runs much faster on the GPU. Code: import skorch import torch import torch.nn as nn from skorch.classifier import NeuralNetBinaryClassifier from sklearn import model_selection from torch.nn import functional as F cuda = torch.device('cuda') parameters = {'lr':[1e-4,1e-5]} class Model(nn.Module): def __init__(self): super(Model, self).__init__() self.lin1 = nn.Linear(50, 30) self.lin2 = nn.Linear(30, 1) def forward(self, x): x = F.tanh(self.lin1(x)) return self.lin2(x).squeeze() class NLL(torch.nn.modules.loss._Loss): def forward(self, input, target): loss = F.nll_loss(input.unsqueeze(1),target) return loss model = Model() model.to(cuda) cl1 = NeuralNetBinaryClassifier( module=model, criterion=NLL, optimizer=torch.optim.Adam, max_epochs=100, train_split=None, device='cuda', ) clf = model_selection.GridSearchCV(cl1, parameters, iid=False, scoring='neg_log_loss', cv=ps, verbose=1, n_jobs=1, return_train_score=True, ) clf.fit(X, Y)
has comment: http://stackoverflow.com/comment/89768307
has title: can't get skorch to run on GPU
tagged with: gpu
tagged with: skorch
downvote count: 0
has comment: http://stackoverflow.com/comment/89724598
has comment: http://stackoverflow.com/comment/89926537
favorite count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89634534
score: 3

http://stackoverflow.com/comment/89384212
type: QuestionComment
comment on: http://stackoverflow.com/q/51201390
has text: You need to implement topological sort to get what you are looking for.
score: 0
type: Comment

http://stackoverflow.com/q/51323748
type: UnansweredQuestion
tagged with: python
upvote count: 6
answer count: 0
downvote count: 1
type: Question
has body: For distributing Python libraries on PyPi, I usually specify the package's dependencies in setup.py à la setup( # ... install_requires=["numpy", "scipy"], # ... ) In some cases, however, I already need to import something in the setup.py, for example when using pybind11. The recommended way for finding the pybind11 include directory is via def __str__(self): import pybind11 # ! return pybind11.get_include(self.user) Hence, the user needs pybind11 installed before pip tries to install the library itself. Unfortunately, simply adding the module to install_requires doesn't cut it: One gets ModuleNotFoundError: No module named 'pybind11' when trying to install. Is there a way to enforce installation of requirements before evaluating setup.py?
score: 5
tagged with: pybind11
linked to: http://stackoverflow.com/q/44308548
has comment: http://stackoverflow.com/comment/89625206
has comment: http://stackoverflow.com/comment/89623121
duplicate of: http://stackoverflow.com/q/44308548
tagged with: dependencies
favorite count: 0
has comment: http://stackoverflow.com/comment/89623034
has title: setup.py: add dependencies required for installation
tagged with: setup.py

http://stackoverflow.com/q/51262938
score: 0
has comment: http://stackoverflow.com/comment/89519230
has comment: http://stackoverflow.com/comment/89519270
has answer: http://stackoverflow.com/a/51918968
tagged with: python
accepted answer: http://stackoverflow.com/a/51918968
has comment: http://stackoverflow.com/comment/89505296
has body: I am a newbie in python, and I have to retrieve the data of this page. http://mims.com/india/drug/search?q=dextro but as this website requires user login so I went through the following code. import requests from bs4 import BeautifulSoup as bs POST_LOGIN_URL = "https://sso.mims.com/Account/Signin" REQUEST_URL = "https://mims.com/india/drug/search?q=DEXTRO%20PLUS" payload = { "EmailAddress": "email address here", "Password" : "password here" } with requests.Session() as session: post = session.post(POST_LOGIN_URL, data=payload) r = session.get(REQUEST_URL) with open('abc.html', 'wb')as f: f.write(r.content) Instead of showing the desired result, it is redirecting me to a page and I am getting a "FORM" element which contains method="post" request and a button which autoclicks. So I am unable to figure it out please someone help.
tagged with: http-redirect
tagged with: request
type: Question
type: AnsweredQuestion
tagged with: post
has title: python requests library redirect new page to post request
answer count: 1

mechanicalsoup
tag name: mechanicalsoup
type: Tag
tags question: http://stackoverflow.com/q/51182921

http://stackoverflow.com/comment/89615832
comment on: http://stackoverflow.com/a/51313701
has text: Thx for the answer! What would be your advice if I don't have the original image? I only have the blurred one.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/89585137
type: Comment
comment on: http://stackoverflow.com/q/51303908
type: QuestionComment
score: 0
has text: I don't quite understand your suggestion here, specifically what you mean by splitting. It also appears that the general order of the output does not seem to be relevant, or am I mistaken there? Because then you might be able to get a much better performance by sorting the values and then only comparing so many values instead (maybe).

http://stackoverflow.com/comment/89520834
score: 1
has text: `pred_df = pd.concat(pred_list, axis = 0, ignore_index=True)` will concatenate `pred_list` and generate a new index at the same time. But [jpp's vectorized approach](https://stackoverflow.com/a/51271201/190597) shows a faster, better way to handle the calculation which avoids the need for `ignore_index=True`.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51271142

http://stackoverflow.com/q/51193517
linked to: http://stackoverflow.com/q/452610
tagged with: python
tagged with: shared-resource
type: Question
has comment: http://stackoverflow.com/comment/89368654
linked to: http://stackoverflow.com/q/28268439
tagged with: closures
score: 0
linked to: http://stackoverflow.com/q/2295290
duplicate of: http://stackoverflow.com/q/2295290
has comment: http://stackoverflow.com/comment/89368859
answer count: 0
has title: Shared and localized variables in Python closures
type: UnansweredQuestion
has body: Closures in Python behave in an “odd” way, so to say. Consider the following code snippet where I have tried to build a list of closures based on foo in two ways: In bad_closure, closures are built ‘on the fly’, while in good_closure the closures are built by a helper function: def foo(d): return d + 1 def bad_closure(): ''' shares resources implicitly ''' # list of 5 closures # `i` is shared between all closures cls = [lambda : foo(i) for i in range(5)] return cls def good_closure(): ''' no resource sharing ''' def mk_cl(i): ''' helper to make a closure''' c_ = lambda : foo(i) return c_ # list of 5 closures # each closure has its own `i` cls = [mk_cl(i) for i in range(5)] return cls #--- TEST --- bs = bad_closure() print([f() for f in bs]) # output: [5, 5, 5, 5, 5] gs = good_closure() print([f() for f in gs]) # output: [1, 2, 3, 4, 5] The results are astoundingly different. It seems that in bad_closure, the closures take a fixed i each, but they all share the same i which updated by each iteration (and finally takes the value 5)! In contrast, in good_closure, i's are separate — as I expect. I'd like to see what is happening behind the scenes and why.

http://stackoverflow.com/q/51219213
has answer: http://stackoverflow.com/a/51219316
has comment: http://stackoverflow.com/comment/89419547
has comment: http://stackoverflow.com/comment/89419696
has body: So, I have a python file from another piece of software. In said python file, an error occurs when I try to run the software, where it complains that I (or rather, the people that somehow made this) cannot divide by zero: k = (c - 1.0) / (c + 1.0) At which point, I think, "Fair enough, I'll just prevent that from ever happening." if abs(c+10)&lt;0.001: k=0 else: k = (c - 1.0) / (c + 1.0) Now instead of getting my original error: File "/home/wurst/Programs/Armory/armsdk//armory/blender/arm/exporter.py", line 1675, in extract_projection k = (c - 1.0) / (c + 1.0) ZeroDivisionError: float division by zero I get this: File "/home/wurst/Programs/Armory/armsdk//armory/blender/arm/exporter.py", line 1675, in extract_projection if abs(c+10)&lt;0.001: ZeroDivisionError: float division by zero At which point, feeling foolish, I start to peruse python tutorials, but there's nothing on the subject. Even if I leave the line blank, it complains that the blank line is dividing by zero. So what am I doing wrong?
type: Question
accepted answer: http://stackoverflow.com/a/51219218
has title: In Python, the same line raises float division by zero despite contents of said line
has comment: http://stackoverflow.com/comment/89419555
score: 0
answer count: 3
has answer: http://stackoverflow.com/a/51219257
has answer: http://stackoverflow.com/a/51219218
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89419706
possible better answer: http://stackoverflow.com/a/51219257

http://stackoverflow.com/comment/89377920
has text: Your `global` directive is completely pointless if it is at the global scope. You could fix the SyntaxError by putting that statement at the top, but again, **it is totally pointless**. Python does not support true global variables, only *module global*.
score: 0
comment on: http://stackoverflow.com/q/51198019
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51213222
score: 1
has body: movfiles = open("movfiles.txt", "r")#open the file in reading mode a= (movfiles.readlines())#read all the lines and save in a list where each line is an element print (a)#print your list Guys maybe I miss understand the question, my code is working but convert each line in a list element, if you have more element in the same line it will not work. If this is the case please let me know and I'll provide an alternative solution
downvote count: 0
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/51213110

http://stackoverflow.com/q/51264283
favorite count: 0
has comment: http://stackoverflow.com/comment/89510211
downvote count: 0
has comment: http://stackoverflow.com/comment/89508582
has comment: http://stackoverflow.com/comment/89507680
tagged with: scrapy
has comment: http://stackoverflow.com/comment/89509888
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51266719
has comment: http://stackoverflow.com/comment/89507937
score: 1
tagged with: web-crawler
has comment: http://stackoverflow.com/comment/89510247
type: Question
has comment: http://stackoverflow.com/comment/89508807
has comment: http://stackoverflow.com/comment/89507409
has answer: http://stackoverflow.com/a/51266719
has body: To be clear I try to crawl forums about casino, for now, I have succeeded to do so using the same scheme as below : class test_spider(scrapy.Spider): count=0 name = "test_spyder" start_urls = [ 'https://casinogrounds.com/forum/search/?&amp;q=Casino&amp;search_and_or=or&amp;sortby=relevancy', ] rules = ( Rule(LinkExtractor(restrict_css=('a:contains("Next")::attr(href)')), callback='parse') ) def parse(self, response) : print(self.count) for href in response.css("span.ipsType_break.ipsContained a::attr(href)") : new_url = response.urljoin(href.extract()) #print(new_url) yield scrapy.Request(new_url, callback = self.parse_review) next_page = response.css('a:contains("Next")::attr(href)').extract_first() print(next_page) if next_page is not None: yield scrapy.Request(next_page, callback = self.parse) def parse_review(self, response): parsed_uri = urlparse(response.url) domain = '{uri.scheme}://{uri.netloc}/'.format(uri=parsed_uri) for review in response.css('article.cPost.ipsBox.ipsComment.ipsComment_parent.ipsClearfix.ipsClear.ipsColumns.ipsColumns_noSpacing.ipsColumns_collapsePhone') : yield { 'name': review.css('strong a.ipsType_break::text').extract_first(), 'date': review.css('time::attr(title)').extract_first(), 'review': review.css('p::text').extract(), 'url' : response.url } next_page = response.css('li.ipsPagination_next a::attr(href)').extract_first() if next_page is not None: yield response.follow(next_page, callback=self.parse_review) So when I execute that spider within a python scripts, normally (I mean for other forums) it crawled all the threads of all the pages from the start url. But for that one it does not, it scraps only all the threads of the first page, it gets the right URL for going onto the second page, but do call another time the parse function. And of course, if I put all the URL of the pages in the start_urls list it scraps all pages... Thank you for the help.
has comment: http://stackoverflow.com/comment/89507991
answer count: 1
has comment: http://stackoverflow.com/comment/89510702
has comment: http://stackoverflow.com/comment/89506931
linked to: http://stackoverflow.com/q/41725624
upvote count: 1
tagged with: python
has title: Web scraping forum with scrapy do not yield the next page

http://stackoverflow.com/comment/89502040
comment on: http://stackoverflow.com/q/51261969
score: 3
type: Comment
type: QuestionComment
has text: A good read: https://nedbatchelder.com/text/names.html

http://stackoverflow.com/comment/89616932
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51320544
has text: Please see the updated question.
score: 0

abstract-syntax-tree
tags question: http://stackoverflow.com/q/51253056
type: Tag
tags question: http://stackoverflow.com/q/51168035
tags question: http://stackoverflow.com/q/51271587
tags question: http://stackoverflow.com/q/51204212
tag name: abstract-syntax-tree

http://stackoverflow.com/a/51274059
type: AcceptedAnswer
downvote count: 0
has body: The problem here is that MethFunc() returns an IHandle *, but you're telling Python to treat it as a PyObject *. Presumably those are completely unrelated types. A PyObject * (or any struct you or Python defines that starts with an appropriate HEAD macro) begins with pointers to a refcount and a type, and the first thing Python is going to do with any object you hand it is deal with those pointers. So, if you give it an object that instead starts with, say, two ints, Python is going to end up trying to access a type at 0x00020001 or similar, which is almost certain to segfault. If you need to pass around a pointer to some C object, you have to wrap it up in a Python object. There are three ways to do this, from hackiest to most solid. First, you can just cast the IHandle * to a size_t, then PyLong_FromSize_t it. This is dead simple to implement. But it means these objects are going to look exactly like numbers from the Python side, because that's all they are. Obviously you can't attach a method to this number; instead, your API has to be a free function that takes a number, then casts that number back to an IHandle* and calls a method. It's more like, e.g., C's stdio, where you have to keep passing stdin or f as an argument to fread, instead of Python's io, where you call methods on sys.stdin or f. But even worse, because there's no type checking, static or dynamic, to protect you from some Python code accidentally passing you the number 42. Which you'll then cast to an IHandle * and try to dereference, leading to a segfault… And if you were hoping Python's garbage collector would help you know when the object is still referenced, you're out of luck. You need to make your users manually keep track of the number and call some CloseHandle function when they're done with it. Really, this isn't that much better than accessing your code from ctypes, so hopefully that inspires you to keep reading. A better solution is to cast the IHandle * to a void *, then PyCapsule_New…
has comment: http://stackoverflow.com/comment/89527103
has comment: http://stackoverflow.com/comment/89527034
has comment: http://stackoverflow.com/comment/89526403
has comment: http://stackoverflow.com/comment/89527550
upvote count: 2
accepted answer of: http://stackoverflow.com/q/51273804
type: Answer
answers question: http://stackoverflow.com/q/51273804
has comment: http://stackoverflow.com/comment/89526844
has comment: http://stackoverflow.com/comment/89526624
has comment: http://stackoverflow.com/comment/89526551
has comment: http://stackoverflow.com/comment/89527171
score: 2

http://stackoverflow.com/comment/89483335
has text: There are no error at all. I simply want to know how i can collapse the text back... readmore.py template tag shows more content, as the name says. I want to know how i can get back to the original shortened text made by the script from above.
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51250759

http://stackoverflow.com/comment/89423665
type: QuestionComment
has text: `find_all` returns a list, you have to loop on MAIN_DATA if you want to find something on each result
score: 1
comment on: http://stackoverflow.com/q/51221190
type: Comment

http://stackoverflow.com/comment/89366816
has text: See if [this package](https://pypi.org/project/csv-to-sqlite/) solves your problem?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51192552

http://stackoverflow.com/q/51228500
type: Question
duplicate of: http://stackoverflow.com/q/31915018
has title: Removing empty strings from a re.findall command
score: 4
answer count: 3
tagged with: python
tagged with: regex
favorite count: 0
has answer: http://stackoverflow.com/a/51228530
downvote count: 1
has body: import re name = 'propane' a = [] Alkane = re.findall('(\d+\W+)*(methyl|ethyl|propyl|butyl)*(meth|eth|prop|but|pent|hex)(ane)', name) if Alkane != a: print(Alkane) As you can see when the regular express takes in propane it will output two empty strings. [('', '', 'prop', 'ane')] For these types of inputs, I want to remove the empty strings from the output. I don't know what kind of form this output is in though, it doesn't look like a regular list.
type: AnsweredQuestion
upvote count: 5
has answer: http://stackoverflow.com/a/51228570
possible better answer: http://stackoverflow.com/a/51228560
linked to: http://stackoverflow.com/q/31915018
accepted answer: http://stackoverflow.com/a/51228530
has answer: http://stackoverflow.com/a/51228560

http://stackoverflow.com/comment/89386778
type: QuestionComment
has text: 32-bit or 64-bit Python?
comment on: http://stackoverflow.com/q/51202801
score: 0
type: Comment

http://stackoverflow.com/a/51396064
has body: First only the direct answers to your questions: Plotting the lines between the joints: First create "list of bones", a list which contains all the pairs of joints which build a line of the skeleton. It can be obtained from the picture with the enumerated joints that you posted: bone_list = [[1, 3], [2, 3], [3, 4], [4, 7], [5, 7], [6, 7], [1, 8], [2, 9], [8, 10], [9, 11], [10, 12], [11, 13], [5, 14], [6, 15], [14, 16], [15, 17], [16, 18], [17, 19], [3, 20]] As the enumeration starts from 1 but python indices start from 0, convert the list to a numpy-array to easily decrement all the values by 1: bone_list = np.array(bone_list) - 1 With this prepared, you can draw the lines in your movement loop with an extra loop for each line (right after plt.scatter(x, y, s=40)): for bone in bone_list: plt.plot([x[bone[0]], x[bone[1]]], [y[bone[0]], y[bone[1]]], 'r') and regarding your overlap-problem: this is just because in skeleton = movement[:z, :2] you slice always from zero on, i.e. [0:20, :2] in the first loop (drawing one skeleton), [0:40, :2] in the second loop (drawing two skeletons) and so on. Change it to skeleton = movement[z-20:z, :2] # or [z:z+20, :2] and do z+=20 afterwards However, if I may add some general hints to your script: there are far too many imports (at least for the part you posted) there are variables renamed which are already there there are unused variables you don't use the iteration variable m in your loop gridspec is for creating subplots in an unequally distributed grid - do you need that? With this in mind, the script you want could be like the following: import matplotlib.pyplot as plt import numpy as np movement = np.loadtxt("file01.txt") bone_list = [[1, 3], [2, 3], [3, 4], [4, 7], [5, 7], [6, 7], [1, 8], [2, 9], [8, 10], [9, 11], [10, 12], [11, 13], [5, 14], [6, 15], [14, 16], [15, 17], [16, 18], [17, 19], [3, 20]] bone_list = np.array(bone_list) - 1 number_of_postures = int(len(movement)/20) for i in range(number_of_postures): fig, ax = plt…
has comment: http://stackoverflow.com/comment/89940581
has comment: http://stackoverflow.com/comment/90018795
has comment: http://stackoverflow.com/comment/89940130
has comment: http://stackoverflow.com/comment/89981529
type: Answer
has comment: http://stackoverflow.com/comment/90018718
score: 4
has comment: http://stackoverflow.com/comment/89938983
has comment: http://stackoverflow.com/comment/89980305
accepted answer of: http://stackoverflow.com/q/51285630
has comment: http://stackoverflow.com/comment/90018227
answers question: http://stackoverflow.com/q/51285630
has comment: http://stackoverflow.com/comment/89939999
has comment: http://stackoverflow.com/comment/89940394
upvote count: 4
has comment: http://stackoverflow.com/comment/89940500
has comment: http://stackoverflow.com/comment/89940932
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/51222947
answers question: http://stackoverflow.com/q/51222918
type: AcceptedAnswer
has body: pip freeze will do it for you: $ pip freeze docutils==0.11 Jinja2==2.7.2 MarkupSafe==0.19 Pygments==1.6 Sphinx==1.2.2 You will probably need option -l too.
type: Answer
has comment: http://stackoverflow.com/comment/89426383
score: 0
accepted answer of: http://stackoverflow.com/q/51222918

http://stackoverflow.com/q/51266880
tagged with: environment-variables
upvote count: 7
has comment: http://stackoverflow.com/comment/89534282
favorite count: 0
downvote count: 0
tagged with: python
has answer: http://stackoverflow.com/a/60888441
accepted answer: http://stackoverflow.com/a/60888441
has comment: http://stackoverflow.com/comment/89556373
has answer: http://stackoverflow.com/a/51267131
type: AnsweredQuestion
score: 7
type: Question
answer count: 2
has body: Is it possible to detect whether Python is running in a Conda environment? I would prefer solutions that don't rely on running shell commands in a subprocess, but if that's the only option then so be it. I would assume there is something simple like an environment variable that is set inside the environment, but this kind of thing is hard to search for (and Conda documentation is not great).
has title: Detect if Python is running in a Conda environment
tagged with: conda
possible better answer: http://stackoverflow.com/a/51267131

http://stackoverflow.com/q/51177486
has title: Python for Robotics: How to generate an app for localization of a Pepper robot
score: 1
has answer: http://stackoverflow.com/a/51186832
type: Question
downvote count: 0
tagged with: nao-robot
answer count: 1
accepted answer: http://stackoverflow.com/a/51186832
tagged with: github
favorite count: 0
has body: These days I have tried to generate an application using the pythonapp template from the Github project Jumpstarter(https://github.com/aldebaran/robot-jumpstarter) to do the localization of Pepper. My basic idea is to combine the LandmarkDetector module in the generated app „Lokalisierung“(Localization of German). You can read the whole code of "LandmarkDetector.py","main.py" and"MainLandmarkDetection.py" here: "LandmarkDetector.py": #! /usr/bin/env python # -*- encoding: UTF-8 -*- """Example: Demonstrates a way to localize the robot with ALLandMarkDetection""" import qi import time import sys import argparse import math import almath class LandmarkDetector(object): """ We first instantiate a proxy to the ALLandMarkDetection module Note that this module should be loaded on the robot's naoqi. The module output its results in ALMemory in a variable called "LandmarkDetected". We then read this ALMemory value and check whether we get interesting things. After that we get the related position of the landmark compared to robot. """ def __init__(self, app): """ Initialisation of qi framework and event detection. """ super(LandmarkDetector, self).__init__() app.start() session = app.session # Get the service ALMemory. self.memory = session.service("ALMemory") # Connect the event callback. # Get the services ALMotion &amp; ALRobotPosture. self.motion_service = session.service("ALMotion") self.posture_service = session.service("ALRobotPosture") self.subscriber = self.memory.subscriber("LandmarkDetected") print "self.subscriber = self.memory.subscriber(LandmarkDetected)" self.subscriber.signal.connect(self.on_landmark_detected) print "self.subscriber.signal.connect(self.on_landmark_detected)" # Get the services ALTextToSpeech, ALLandMarkDetection and ALMotion. self.tts = session.service("ALTextToSpeech") self.landmark_detection = session.service("ALLandMarkDetection") # print "self.landmark_detection" is repr(self.landmark_detection) self.motion_service = session.service("ALMo…
upvote count: 1
tagged with: python
linked to: http://stackoverflow.com/q/30086384
type: AnsweredQuestion
tagged with: pepper

http://stackoverflow.com/comment/89570678
type: Comment
has text: Thank you so much!! I learned a great deal today. God bless you!
comment on: http://stackoverflow.com/a/51296648
type: AnswerComment
score: 0

http://stackoverflow.com/comment/89343045
type: QuestionComment
comment on: http://stackoverflow.com/q/51180293
score: 1
has text: Currently you're passing a generator to apply. If you meant that to be a lambda *returning* a generator, you need to add parentheses.
type: Comment

http://stackoverflow.com/q/51233865
upvote count: 3
linked to: http://stackoverflow.com/q/50839919
type: Question
tagged with: postgis
answer count: 2
tagged with: polygon
has answer: http://stackoverflow.com/a/51356279
has body: I have a set of polygons and they can overlap with each other, like this: I want to modify them in such a way that they don't overlap and the resulting surface area stays the same. Something like this: It is okay if the shape or the position changes. The main thing is that they should not overlap with each other and the area should not change much (I know the area changed a little in the second image but I drew it manually thus let's just assume that the areas did not change). I am trying to do it programmatically with the help of Python. Basically I stored polygons in a PostGIS database and with the help of a script I want to retrieve them and modify them. I am very new to GIS and thus this seems like a difficult task. What is the correct way of doing it? Is there an algorithm that solves this kind of problems?
downvote count: 0
tagged with: postgresql
has comment: http://stackoverflow.com/comment/89463262
tagged with: python
has title: Modify polygons so that they don't overlap and area stays the same
favorite count: 0
accepted answer: http://stackoverflow.com/a/51356279
has comment: http://stackoverflow.com/comment/89493754
possible better answer: http://stackoverflow.com/a/51235887
tagged with: gis
has answer: http://stackoverflow.com/a/51235887
type: AnsweredQuestion
score: 3

http://stackoverflow.com/q/51253417
favorite count: 0
has answer: http://stackoverflow.com/a/51253528
has title: Is Python's zip fundamentally different from a matrix transpose?
has comment: http://stackoverflow.com/comment/89485908
type: Question
has comment: http://stackoverflow.com/comment/89485955
score: 5
tagged with: python
answer count: 1
upvote count: 6
downvote count: 1
accepted answer: http://stackoverflow.com/a/51253528
has body: As I understand it, pythons zip takes a series of iterables and then returns an iterator to tuples containing one element from each iterator, such that the first tuple would contain the first element from each iterator. For example: A = [1, 2, 3] B = [4, 5, 6] for a, b in zip(A, B): print(f"{a}, {b}") Prints out: 1, 4 2, 5 3, 6 Transposing A and B separately then joining A and B results in that exact matrix. Is there any cases where the two operations vary in results or are they basically the same thing? Edit: *iterables
has comment: http://stackoverflow.com/comment/89485787
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89486226

http://stackoverflow.com/q/51225801
has body: The user is providing a string. I have a dictionary with words and phrases, and each key in the dictionary corresponds to a word or a phrase which is associated with a spam value. The goal is to match the user input to a word/phrase of the dictionary. My code works well for words, but it is not working for phrases. When I enter a word like prize, the results are as expected, but when I enter a phrase like Produced and sent out, it does not show any result. Here is my code #input should be : Hurry up , no fee , no cost , buy it now #output required : phrases should be matched and return key value as words does from nltk.tokenize import sent_tokenize,word_tokenize #taking user input string=input("enter your text: ? ") #tokenize the worlds for comparison #convert input into the lower case #tokenize the input champ_ids = (word_tokenize(string)) champ_dict ={Prize":9, "Prizes":9, "Produced and sent out":9, } #LOWER CASE ALL THE DICTIONARY VALUES result = "" value = 0 #iterate through dictionarty for k,v in champ_dict.items(): if k in champ_ids: result += k+" " value += v print("result = ", result) print("value = ", value) print("status = ", status)
has answer: http://stackoverflow.com/a/51225855
type: Question
has title: Dictionary which contains words and phrases, cannot match phrases
score: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/51225855
tagged with: python-3.x
tagged with: python
tagged with: dictionary
type: AnsweredQuestion

http://stackoverflow.com/q/51215904
has answer: http://stackoverflow.com/a/59948814
tagged with: python
has answer: http://stackoverflow.com/a/73038771
has answer: http://stackoverflow.com/a/60842224
type: AnsweredQuestion
upvote count: 19
has comment: http://stackoverflow.com/comment/135485818
has body: I was using AWS and am new to GCP. One feature I used heavily was AWS Batch, which automatically creates a VM when the job is submitted and deletes the VM when the job is done. Is there a GCP counterpart? Based on my research, the closest is GCP Dataflow. The GCP Dataflow documentation led me to Apache Beam. But when I walk through the examples here (link), it feels totally different from AWS Batch. Any suggestions on submitting jobs for batch processing in GCP? My requirement is to simply retrieve data from Google Cloud Storage, analyze the data using a Python script, and then put the result back to Google Cloud Storage. The process can take overnight and I don't want the VM to be idle when the job is finished but I'm sleeping.
has answer: http://stackoverflow.com/a/52575398
type: Question
accepted answer: http://stackoverflow.com/a/55287928
has answer: http://stackoverflow.com/a/52571940
answer count: 6
tagged with: amazon-web-services
score: 19
tagged with: google-cloud-platform
tagged with: batch-processing
has title: AWS Batch analog in GCP?
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/55287928
possible better answer: http://stackoverflow.com/a/73038771

http://stackoverflow.com/a/51221544
has comment: http://stackoverflow.com/comment/89426030
has comment: http://stackoverflow.com/comment/89424322
score: 2
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/89427533
answers question: http://stackoverflow.com/q/51221205
has body: I guess you'd better create an empty 2D array and fill it later... import numpy as np N = how_many() L = how_long() complete = np.empty((N, L), dtype=float) for i in range(N): complete(i, :) = extract_feature(i) In place of dtype=float you can use a different numeric type, as required by your problem. E.g., In [14]: a = np.empty((2,4), dtype=float) In [15]: for i in (0, 1): ...: a[i,:] = np.ones(4)*i ...: In [16]: a Out[16]: array([[0., 0., 0., 0.], [1., 1., 1., 1.]]) Addendum Comment on efficiency If one knows beforehand the dimensions of an array they are going to construct row-by-row, the approach sketched above is better, because it avoids constantly alllocating new memory, copying the temporary result and the new row to the new memory and deallocating the memory used to hold the previous temporary result. Alternative using concatenation If, on the other hand, one doesn't know beforehand how many rows will be produced during the creation of the array, or if one insists on using a sub-optimal solution, they can use np.vstack, encapsulating the productions of new rows in a generator import numpy as np def features_factory(stuff): while true: feature = new_feature(stuff) if feature: yield feature else: return complete = np.vstack(features_factory(todays_stuff)) E.g., In [1]: import numpy as np In [2]: np.random.seed((2018+7+8)) # today's stuff... ;) In [3]: def features_factory(stuff): ...: n = 0 ...: while True: ...: if n&lt;stuff: ...: yield np.ones(5)*n ...: n = n+1 ...: else: ...: return In [4]: complete = np.vstack(features_factory(np.random.randint(5,11))) In [5]: complete Out[5]: array([[0., 0., 0., 0., 0.], [1., 1., 1., 1., 1.], [2., 2., 2., 2., 2.], [3., 3., 3., 3., 3.], [4., 4., 4., 4., 4.], [5., 5., 5., 5., 5.], [6., 6., 6., 6., 6.], [7., 7., 7., 7., 7.]]) In [6]:
accepted answer of: http://stackoverflow.com/q/51221205
type: Answer
upvote count: 2
has comment: http://stackoverflow.com/comment/89429024

http://stackoverflow.com/a/51317158
downvote count: 0
has comment: http://stackoverflow.com/comment/89629255
has body: You could use depth attribute to achieve desired output. The default ModelSerializer uses primary keys for relationships, but you can also easily generate nested representations using the depth option.The depth option should be set to an integer value that indicates the depth of relationships that should be traversed before reverting to a flat representation. class FooSerializer(serializers.ModelSerializer): class Meta: model = Foo fields = '__all__' depth = 1 Apart from the answer, I would like to change your views.py code, cause it seems like very bad :(. Do it on DRF Way as serialized_data = FooSerializer(Foo.objects.all(), many=True).data&lt;br&gt; Example View from rest_framework.viewsets import ModelViewSet class FooViewset(ModelViewSet): serializer_class = FooSerializer queryset = Foo.objects.all() UPDATE-1 class UserSerializer(serializers.ModelSerializer): class Meta: model = User exclude = ('password',) # add fields that are need to be excluded class FooSerializer(serializers.ModelSerializer): user = UserSerializer() class Meta: model = Foo fields = '__all__' depth = 1 depth = 1 will serializer all fields in the model, (It's same as setting the fields=='__all__' in Meta class of serializer) UPDATE-2 class FooSerializer(serializers.ModelSerializer): user = UserSerializer() class Meta: model = Foo fields = '__all__' depth = 1 def to_representation(self, instance): real_data = super().to_representation(instance).copy() # DO YOUR EXTRA CHECKS child = UserSerializer(instance.child_foo).data if child: real_data.update({"child_data": child}) # After your checks, add it to "real_data" return real_data and I assumed I have a Foo model as class Foo(models.Model): example = models.ManyToManyField(Example) user = models.ForeignKey(User) child_foo = models.ForeignKey('self', null=True, blank=True)
has comment: http://stackoverflow.com/comment/89631438
has comment: http://stackoverflow.com/comment/89624600
has comment: http://stackoverflow.com/comment/89626164
has comment: http://stackoverflow.com/comment/89624949
has comment: http://stackoverflow.com/comment/89626082
upvote count: 2
accepted answer of: http://stackoverflow.com/q/51315694
has comment: http://stackoverflow.com/comment/89630035
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51315694
has comment: http://stackoverflow.com/comment/89624769
has comment: http://stackoverflow.com/comment/89642482
has comment: http://stackoverflow.com/comment/89630172
type: Answer
score: 2

http://stackoverflow.com/q/51203628
linked to: http://stackoverflow.com/q/51185509
has answer: http://stackoverflow.com/a/51210886
type: Question
tagged with: mongodb
score: 0
has title: Elasticsearch with Django and Mongoengine
answer count: 1
type: UnansweredQuestion
has body: I have a django REST application that uses Mongoengine. I want to integrate the application with elasticsearch. I understand that databases (like MySQL, Postgres etc.) can be integrated with elasticsearch using haystack but how to do it with MongoDB?
tagged with: elasticsearch
tagged with: django
tagged with: python

http://stackoverflow.com/a/51211130
score: 2
accepted answer of: http://stackoverflow.com/q/51211071
upvote count: 2
has body: OrderedDict(sorted(output.items(), key=lambda item: int(item[0].split('.')[0]))) Example output = {f'{i}.jpg': None for i in reversed(range(21))} od = OrderedDict(sorted(output.items(), key=lambda item: int(item[0].split('.')[0]))) Output: OrderedDict([('0.jpg', None), ('1.jpg', None), ('2.jpg', None), ('3.jpg', None), ('4.jpg', None), ('5.jpg', None), ('6.jpg', None), ('7.jpg', None), ('8.jpg', None), ('9.jpg', None), ('10.jpg', None), ('11.jpg', None), ('12.jpg', None), ('13.jpg', None), ('14.jpg', None), ('15.jpg', None), ('16.jpg', None), ('17.jpg', None), ('18.jpg', None), ('19.jpg', None), ('20.jpg', None)])
has comment: http://stackoverflow.com/comment/89403815
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/89403857
answers question: http://stackoverflow.com/q/51211071
type: Answer

http://stackoverflow.com/comment/89594725
comment on: http://stackoverflow.com/a/51308679
score: 0
type: Comment
has text: that's a copy-paste error, in my editor it's well formatted.
type: AnswerComment

http://stackoverflow.com/comment/89613870
type: Comment
comment on: http://stackoverflow.com/a/51317344
type: AnswerComment
has text: @AshishAcharya so now what i observe is if i go with totally another encoding in future i must have a separator to separate dictonary value in the string .
score: 0

asyncpg
tags question: http://stackoverflow.com/q/51224178
tag name: asyncpg
type: Tag
tags question: http://stackoverflow.com/q/51322347

http://stackoverflow.com/comment/89902777
has text: But for those _extra_ which are not empty, I would like to perform this action and live them inside the dictionary. So my target not is to adapt this piece of code `k: (item.get(k) if k != 'extra' else {i.get('k'): i.get('v') for i in item.iter('tag')})`
type: AnswerComment
comment on: http://stackoverflow.com/a/51236096
score: 0
type: Comment

http://stackoverflow.com/a/51280597
has comment: http://stackoverflow.com/comment/89540331
answers question: http://stackoverflow.com/q/51280487
has body: Try using a try/except around the loop to ignore the files you dont have permission to search: try: for root, dirs, files in os.walk(my_path): for f in files: if f.endswith(".7z"): print("found files: " , f) copy_files(my_path, arch_dest) except OSError: pass
has comment: http://stackoverflow.com/comment/89540234
score: 0
has comment: http://stackoverflow.com/comment/89540767
type: Answer
has comment: http://stackoverflow.com/comment/89539925
has comment: http://stackoverflow.com/comment/89544845
has comment: http://stackoverflow.com/comment/89540121

data-visualization
tags question: http://stackoverflow.com/q/51208817
tags question: http://stackoverflow.com/q/51176306
tags question: http://stackoverflow.com/q/51321411
tags question: http://stackoverflow.com/q/51314554
tags question: http://stackoverflow.com/q/51298772
tag name: data-visualization
tags question: http://stackoverflow.com/q/51300298
tags question: http://stackoverflow.com/q/51204505
type: Tag
tags question: http://stackoverflow.com/q/51255951

http://stackoverflow.com/a/51294081
accepted answer of: http://stackoverflow.com/q/51293478
answers question: http://stackoverflow.com/q/51293478
has body: It's really a matter of how you represent your data. In essence, this is not a Series, it is a DataFrame with 5 columns: for example: df = pd.DataFrame({"level_0":{"0":"bar","1":"bar","2":"baz","3":"baz","4":"foo","5":"foo","6":"qux","7":"qux"},"level_1":{"0":"one","1":"two","2":"one","3":"two","4":"one","5":"two","6":"one","7":"two"},"level_2":{"0":"a","1":"b","2":"c","3":"d","4":"e","5":"f","6":"g","7":"h"},"level_3":{"0":"1","1":"2","2":"3","3":"4","4":"5","5":"6","6":"7","7":"8"},"0":{"0":1.7686082254,"1":-1.2237523116,"2":-1.3066335651,"3":-1.3800965009,"4":-0.5995811728,"5":-1.4717242393,"6":-1.0613097567,"7":-0.3232780637}}) You get: and then you can set the index as a 4 level index df = df.set_index(['level_0', 'level_1', 'level_2', 'level_3']) and your get your 4 level indexed Series The original DataFrame could be missing values (i.e. your index array would originally be 'of different length') and that gives you what you are looking for.
score: 0
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/q/51184346
downvote count: 0
has answer: http://stackoverflow.com/a/51184492
has comment: http://stackoverflow.com/comment/89351133
has comment: http://stackoverflow.com/comment/89350890
tagged with: multiple-columns
favorite count: 0
has comment: http://stackoverflow.com/comment/89350737
has comment: http://stackoverflow.com/comment/89351110
has answer: http://stackoverflow.com/a/51184523
has comment: http://stackoverflow.com/comment/89350679
score: 6
has title: Pandas shift column data upon condition
tagged with: python
has comment: http://stackoverflow.com/comment/89350720
answer count: 4
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89350620
has comment: http://stackoverflow.com/comment/89350806
type: Question
has answer: http://stackoverflow.com/a/51184454
tagged with: indexing
possible better answer: http://stackoverflow.com/a/51184523
tagged with: if-statement
upvote count: 6
has answer: http://stackoverflow.com/a/51184421
accepted answer: http://stackoverflow.com/a/51184421
tagged with: pandas
has body: I have dataframe which look like this. Name Val Rating 0 ABC 123 B + 1 DEF 234 B + 2 567 B- NaN 3 GHI 890 D but instead I want to shift the data by checking (col['Name']) to next column (col['Val']) and successively shifting. Also if the shifting happens change the row index value. I want the following dataframe as output. Name Val Rating 0 ABC 123 B + 1 DEF 234 B + NaN 567 B - 2 GHI 890 D Anybody know how to do this?

http://stackoverflow.com/comment/89479456
type: AnswerComment
comment on: http://stackoverflow.com/a/51250214
score: 0
type: Comment
has text: @chepner: If they don’t realize you don’t need to compile, “you don’t need to compile” is helpful. Compare the Perl. It’s a common misconception.

http://stackoverflow.com/q/51288608
has comment: http://stackoverflow.com/comment/89573946
answer count: 0
tagged with: forms
has title: Passing request.POST vs the request itself to a django form when uploading multiple files
tagged with: post
type: Question
score: 0
has comment: http://stackoverflow.com/comment/89566613
has body: I am using following form to upload multiple images. class AlbumForm(forms.Form): album_name = forms.CharField(label='Titel', max_length=100, required=True) album_description = forms.CharField(label='Beschrijving', widget=forms.Textarea) images = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True})) In the receiving view i noticed that when i pass request.POST to the form I cannot access the images in the form. On the other hand when i pass the request itself to the form i can access the files but cannot use the form.isValid() method. Only the multiple image file is not available, the two other values are available as usual. def post(self, request, *args, **kwargs): images_form = AlbumForm(request) ... if images_form.is_valid(): images = images_form.data.FILES.getlist('images') Imgur().create_album(title=images_form.album_name, description=images_form.album_description, images=images) ... Following is the html code for the form &lt;form method="POST" enctype="multipart/form-data"&gt; {% csrf_token %} &lt;input class="" type="submit" value="save"&gt; &lt;/form&gt; What is the reason for this difference or what am i doing wrong? Edit : the name and description are not available when only using the request, so i guess the correct way to go is to use request.POST, but what is then the correct way to acces the files
type: UnansweredQuestion
tagged with: django
tagged with: python
tagged with: request

http://stackoverflow.com/q/51282109
tagged with: python
has body: Currently I have a few plots using Facet Grids in seaborn. I have the following code: g = sns.FacetGrid(masterdata1,col = "courseName") g=g.map(plt.scatter, "SubjectwisePercentage", "SemesterPercentage") The above code plots subjectwisepercentage vs semesterpercentage, for different courses across a semester. How can I plot the different scatter plots in a single plot, instead of multiple plots across the facet grid? In the single plot, the plotted points for each course should be a different color. There are links online that specify how to plot different datasets in a single plot. However I need to use the same dataset. Therefore I need to specify col="courseName", or something equivalent, to plot course wise data in a single plot. I am not sure of how to accomplish this. Thank you in advance for your help.
downvote count: 0
has title: Plotting multiple scattter plots in the same graph instead of Facet Grids
score: 1
type: Question
upvote count: 1
answer count: 1
has answer: http://stackoverflow.com/a/55132009
favorite count: 0
tagged with: seaborn
type: UnansweredQuestion

http://stackoverflow.com/comment/89462634
type: AnswerComment
comment on: http://stackoverflow.com/a/51206531
has text: You can measure it by hand or, if you are able to recognize the arm with your cam, you should be able to infer the theta by confronting the coordinates measured by your cam with those you "entered" in your arm.
type: Comment
score: 0

http://stackoverflow.com/a/51304069
type: AcceptedAnswer
downvote count: 0
score: 8
answers question: http://stackoverflow.com/q/51303546
upvote count: 8
type: Answer
accepted answer of: http://stackoverflow.com/q/51303546
has body: Even though one of the dictionary values is int, mypy is unable to infer that. Mypy is correct. Your code has a bug and mypy is correctly flagging it. There is no guarantee in your code that data['start'] and data['end'] are always going to be integers. Your data signature is Dict[str, Union[str, int]], so the values have the type Union[str, int]. Mypy must assume that it is always correct to pass in {'start': '2018-07-12', 'end': -42}, so the return value must be Tuple[Union[str, int], Union[str, int]]. Your claim that the function returns Tuple[int, int] clashes with this. It doesn't matter what actually happens at runtime. That's not the point; mypy is a static typechecker, and is designed to help keep your runtime behaviour bug-free. What matters here is that, according to the type hints, it is possible to pass in non-integer values for start and end, so the typechecker can't protect you from future bugs in your code that accidentally set a string value for either of those two keys. If you are passing around structured data in dictionaries, you will always have to fight mypy over this, as dictionaries are really the wrong structure for this. You really want to use a named tuple or a dataclass here. I'm using the name FooBar here, but for your specific application I'm sure there will be a better name for the data structure you are passing around: from typing import NamedTuple class FooBar(NamedTuple): start: int end: int # other fields, perhaps with defaults and Optionals def select_range(data: FooBar) -&gt; Tuple[int, int]: if data.start and data.end: return data.start, data.end return 1, 1

http://stackoverflow.com/comment/89604792
type: Comment
has text: Thank you a lot! It's officialy the best answer, after manually checking some addresses now they are actually very close. Have a good day !
comment on: http://stackoverflow.com/a/51313265
score: 0
type: AnswerComment

http://stackoverflow.com/q/51207298
has comment: http://stackoverflow.com/comment/89395500
downvote count: 4
has comment: http://stackoverflow.com/comment/89395400
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/51207351
has comment: http://stackoverflow.com/comment/89396492
favorite count: 0
has title: Strict search and replace text in Python
has body: Let's consider a list as such : listing = ['15.32','25.6','.','12.8','.'] What would be the way to search and erase (or replace) the values consisting of a single period (.)? In Python 3 would be best. EDIT: By "erase" I mean that I want a null value, I need to keep the same lenght of the list.
tagged with: python
has comment: http://stackoverflow.com/comment/89395462
has answer: http://stackoverflow.com/a/51207362
upvote count: 0
type: UnansweredQuestion
score: -4

properties
tags question: http://stackoverflow.com/q/51284801
type: Tag
tags question: http://stackoverflow.com/q/51285848
tag name: properties
tags question: http://stackoverflow.com/q/51244348

http://stackoverflow.com/q/51211769
score: 2
downvote count: 0
accepted answer: http://stackoverflow.com/a/51212012
type: AnsweredQuestion
has body: Normally when I spawn new process, I will have just 1 in-process python code. But when I use shared memory (shared value), Python will create another new process beside of my own process. Sample (shows 1 process): p = multiprocessing.Process(target=mytarget) p.daemon = True p.start() Sample (shows 2 processes while I spawned just 1 process): shared = Manager().Value(int, 0) p = multiprocessing.Process(target=mytarget, args=(shared)) p.daemon = True p.start() Is there any way to avoid creating new extra processes in Python?
tagged with: shared-memory
favorite count: 0
tagged with: python-3.x
has title: Why Shared Value in Python Creates Extra Processes
type: Question
upvote count: 2
tagged with: python
answer count: 1
has answer: http://stackoverflow.com/a/51212012
tagged with: parallel-processing

http://stackoverflow.com/a/51267770
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51265668
has body: Can you connect to your SQL Server from another application, including Excel? If you cannot, I would check the following: Remote into the server and open the SQL Server Configuration Manager. There should be a section labeled SQL Server Network Configuration that will have an entry for "Protocols for ". If you click on that entry, you will see which protocols are enabled for your database. Click on TCP/IP and select properties. Under the IP addresses, each IP listed may need to have a port listed. Once that is done, make sure that port is enabled in your firewall on the server for both Inbound and Outbound. When I managed a SQL-driven application, we normally got the Named Pipes error when there was other connection issues such as firewall issues or the SQL Server Browser or instance not running. If this is not sufficient to resolve the issue, there are a ton of other options on MSSQL Tips.

http://stackoverflow.com/comment/89588815
type: QuestionComment
has text: Can you share code for that *fake click* also?
score: 0
type: Comment
comment on: http://stackoverflow.com/q/51305711

http://stackoverflow.com/q/51252030
has answer: http://stackoverflow.com/a/51252602
score: 0
accepted answer: http://stackoverflow.com/a/51252602
answer count: 1
has body: I'm working on a Twilio texting program I can't install foundations I keep getting this issue. I've already tried reinstalling pip, easy_setup, pip wheel, django, and python. I have no idea why i'm still getting this error. I'm running Mac Osx Collecting Foundations==2.1.0 (from -r requirements.txt (line 14)) Using cached https://files.pythonhosted.org/packages/d4/c4/341b76267c3969b46170f715524259c1c170992253cb7c425d746cb2e322/Foundations-2.1.0.tar.gz 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 "/private/var/folders/l5/k0m1stsn5yz8x0sx_wj4z9qm0000gn/T/pip-install-xi0ft4n3/Foundations/setup.py", line 35, in &lt;module&gt; _setEncoding() File "/private/var/folders/l5/k0m1stsn5yz8x0sx_wj4z9qm0000gn/T/pip-install-xi0ft4n3/Foundations/setup.py", line 31, in _setEncoding reload(sys) NameError: name 'reload' is not defined ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in /private/var/folders/l5/k0m1stsn5yz8x0sx_wj4z9qm0000gn/T/pip-install-xi0ft4n3/Foundations/
tagged with: homebrew
tagged with: pip
tagged with: python
type: AnsweredQuestion
tagged with: anaconda
type: Question
has comment: http://stackoverflow.com/comment/89482993
linked to: http://stackoverflow.com/q/10142764
has title: Pip Install Foundations
has comment: http://stackoverflow.com/comment/89483093

http://stackoverflow.com/comment/89605118
type: AnswerComment
has text: thank you very much can you suggest a particular websocket client library and or a tutorial or something like that on how it works (you are right bs does not run the javascript but i thought by reconnecting to the website everytime i should get the updateted data everytime)
type: Comment
score: 0
comment on: http://stackoverflow.com/a/51313427

http://stackoverflow.com/comment/89651811
type: Comment
has text: I found the answer. In python 3, the object returned by dic.keys() is not a list but a range. So there needs to adding a list() to the statement: del dic[random.choice(list(dic.keys()))] It works now. No "support indexing Error". Thanks, Daniel!
comment on: http://stackoverflow.com/a/51262282
score: 1
type: AnswerComment

http://stackoverflow.com/comment/89537255
score: 0
type: QuestionComment
type: Comment
has text: what you point out in your question is the workaround :)
comment on: http://stackoverflow.com/q/51262056

http://stackoverflow.com/a/51200935
type: Answer
has body: It turns out that you indeed need to run pipenv install to actually install the packages. The pipenv shell command only activates the virtual environment.
score: 0
accepted answer of: http://stackoverflow.com/q/51200765
answers question: http://stackoverflow.com/q/51200765
type: AcceptedAnswer

http://stackoverflow.com/q/51201519
has body: I ran a following simple script: import sys import pandas as pd df = pd.DataFrame([[1,2,3], [4,5,6]]) df.to_csv(sys.stdout) Expected Output (as standard output) ,0,1,2 0,1,2,3 1,4,5,6 However, I got no outputs on standard output by the program under Python 2.7.15 on macOS 10.12.6. Instead, it generated a file named &lt;stdout&gt; which contains the expected output. Interestingly, on the same OS, Python 3.6.5 could show the result as standard output without any problems, and virtualenved Python 3.6.5 could not show it (and generated the &lt;stdout&gt; file). Does anyone identify the cause of this result? The version of Pandas is 0.23.1.
has answer: http://stackoverflow.com/a/51201819
has title: Pandas to_csv(sys.stdout) doesn't work under my environment
tagged with: python-2.7
answer count: 2
tagged with: pandas
accepted answer: http://stackoverflow.com/a/51201718
downvote count: 0
tagged with: macos
favorite count: 0
tagged with: python-3.x
tagged with: python
upvote count: 16
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51201718
score: 16
linked to: http://stackoverflow.com/q/10265593
possible better answer: http://stackoverflow.com/a/51201819
type: Question

http://stackoverflow.com/q/51211892
has comment: http://stackoverflow.com/comment/89404816
has comment: http://stackoverflow.com/comment/89405056
has answer: http://stackoverflow.com/a/51212275
has body: I've been trying for a while to solve this Fibonacci question and to write it correctly but I always getting not the right results and its stuck at the first If in the code. Code Below: def main(): num = 1 num2 = 1 num3 = 2 Katan = True while Katan == True: if (num3 == 2): print num,num2,num3 num3 = num2 + num3 num2 = num3 elif num3 &lt; 10000: num3 = num + num2 num2 = num print num,num2,num3 num = num2 else: Katan = False if __name__ == '__main__': main()
score: 0
type: Question
has comment: http://stackoverflow.com/comment/89405066
has comment: http://stackoverflow.com/comment/89404762
has comment: http://stackoverflow.com/comment/89404704
has comment: http://stackoverflow.com/comment/89405024
tagged with: python-2.7
answer count: 2
has answer: http://stackoverflow.com/a/51212802
has title: Fibonacci Sequence - using While True
has comment: http://stackoverflow.com/comment/89404786
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89405123
tagged with: python

http://stackoverflow.com/a/51311314
downvote count: 0
has comment: http://stackoverflow.com/comment/89603143
score: 1
has comment: http://stackoverflow.com/comment/89603293
has comment: http://stackoverflow.com/comment/89614296
accepted answer of: http://stackoverflow.com/q/51289763
upvote count: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51289763
has comment: http://stackoverflow.com/comment/89611276
has body: You are correct in your analysis of the output, but mistaken in your consideration of what matrix_balance does. From the docs, The balanced matrix satisfies the following equality, B = inv(T) * A * T (matrix products) Which we can verify easily with your matrices, &gt;&gt;&gt;print(np.dot(np.dot(np.linalg.inv(permscale), x), permscale)) [[ 1. 4. 7. ] [ 4.5 1. 0.5 ] [ 1. 4. 31.41592654]] Which is indeed y. This implies matrix_balance works as it claims to do. You claim, It doesn't look that it actually balancing the rows and cols of the matrix. Any idea what should I do? But this is not true: the L1 norms of this modified matrix are balanced, to within one order of magnitude of two, such that the precise orders of magnitude are reflected to the scaling matrix permscale. Is your aim instead to make your matrix doubly-stochastic, rather than (just) balanced? If so, you could look at e.g. this project. Following the guide presented there I found the following doubly-stochastic matrix for your data, &gt;&gt;&gt;print(sk.fit(x)) [[ 0.1385636 0.55482644 0.30660996] [ 0.79518122 0.17688932 0.02792947] [ 0.06695665 0.26810303 0.66494032]] &gt;&gt;&gt;print(sk.fit(x).sum(axis=0), sk.fit(x).sum(axis=1)) [ 1.00070147 0.99981878 0.99947975] [ 1. 1. 1.] Which ought to be 'close enough' for most use-cases.
type: Answer

http://stackoverflow.com/comment/89377771
has text: @chepner What are you talking about? There's no such thing as modifying the default value of a parameter. `all_keys1 = self._get_key_list(self.d)` does not do anything to change the default value of `_get_key_list`.
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51197809
score: 0

http://stackoverflow.com/comment/89418359
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51218527
has text: `print()` has a `key` param? Your link only has `sorted()`
type: AnswerComment

http://stackoverflow.com/a/51227277
score: 3
accepted answer of: http://stackoverflow.com/q/51227228
upvote count: 4
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/51227228
has body: a is assigned a string returned by input(), so you need to turn it into a list first before you can use list methods such as pop() on it. For example, by using a.split() you can treat a as a space-delimited string: a = input('enter a list : ') n = a.split() p = 2 i = 0 l = len(n) while l&gt;0: i = (p+i)%l print(n.pop(i)) l -= 1 Sample input and output: enter a list : 3 5 2 1 2 5 1 3
downvote count: 1

http://stackoverflow.com/a/51308280
type: Answer
has body: Changed my code to this: SCOPES = 'https://www.googleapis.com/auth/spreadsheets' store = file.Storage('credentials.json') flow = client.OAuth2WebServerFlow(client_id='619103408544-qbpfk38g9jk4tkc5gshvds9hs8g5ur9o.apps.googleusercontent.com', client_secret='faJQr2Wd3x25_yKYIWslxR4s', scope=SCOPES) creds = tools.run_flow(flow, store) service = build('sheets', 'v4', http=creds.authorize(Http())) Used a different function to create the flow, turns out you don't need to actually use the store to make the credentials so I just deleted the store.get() line.
answers question: http://stackoverflow.com/q/51294143
score: 0
has comment: http://stackoverflow.com/comment/89601001

http://stackoverflow.com/comment/89450049
has text: I am using the pre-made estimator (DNNRegressor) , so yes, I am using a canned estimator. And yes, I am using feature columns
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51217603
score: 0

http://stackoverflow.com/a/51336703
upvote count: 6
has comment: http://stackoverflow.com/comment/89690737
accepted answer of: http://stackoverflow.com/q/51323528
score: 6
answers question: http://stackoverflow.com/q/51323528
has body: It seems that a sel using a time slice combined with method='nearest' is simply not supported: cannot use method argument if any indexers are slice objects This somehow makes sense, as selecting the nearest for a slice seems a bit strange. You can work around this by doing the sel in two steps, i.e. first select the time slice, and from that time slice select a location (or the other way around). I'm not sure if this is the best solution, but at least it works. Quick example with some ERA5 data: import xarray as xr ds1 = xr.open_dataset('20160502_cabauw_model_fc.nc') # Works: dsloc1 = ds1.sel(time='2016-05-02 10:00', longitude=4.9, latitude=51.2, method='nearest') # Doesn't work: #dsloc2 = ds1.sel(time=slice('2016-05-02 10:00', '2016-05-02 12:00'), longitude=4.9, latitude=51.2, method='nearest') # Works: tmp = ds1.sel(time=slice('2016-05-02 10:00', '2016-05-02 12:00')) dsloc2 = tmp.sel(longitude=4.9, latitude=51.2, method='nearest') This results in something like: In [23]: dsloc2 Out[23]: &lt;xarray.Dataset&gt; Dimensions: (level: 137, time: 3) Coordinates: longitude float32 4.8 latitude float32 51.3 * level (level) int32 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 ... * time (time) datetime64[ns] 2016-05-02T10:00:00 2016-05-02T11:00:00 ... Data variables: z (time, level) float32 ...
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/q/51257857
tagged with: python-2.7
score: 0
has title: How to delete ADUser using Python pyad module
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89524667
tagged with: python
tagged with: pyad
answer count: 0
has comment: http://stackoverflow.com/comment/89496002
has comment: http://stackoverflow.com/comment/89494551
has body: I'm having a problem with deleting ADUser. pyad.set_defaults(ldap_server="dc1.domain.com", username="service_account", password="mypassword") user = aduser.ADUser.from_dn("cn=myuser, ou=staff, dc=domain, dc=com") user.delete() Unfortunately I could not figure out how to format this text to look like a real traceback Traceback (most recent call last): File "C:/Automation/qa/robot2/python_lib/keywords/AD/unittest.py", line 34, in &lt;module&gt; ad_connect.bg_ad_user_remove(user_login='vasya.oconnor@test-acme.com',dn_string= dn_string) File "C:\Automation\qa\robot2\python_lib\keywords\AD\_bg_ad_general.py", line 156, in bg_ad_user_remove user.delete() File "C:\Python27\lib\site-packages\pyad\adobject.py", line 537, in delete if not parent: File "C:\Python27\lib\site-packages\future\types\newobject.py", line 90, in __nonzero__ return type(self).__len__(self) AttributeError: type object 'ADContainer' has no attribute '__len__'
type: Question

http://stackoverflow.com/comment/89603124
type: Comment
comment on: http://stackoverflow.com/a/51312647
score: 0
type: AnswerComment
has text: Ok I get why it doesn't work now. But I need to plot these items in order to see the most frequent ones since I need to select a subset of those for performing a regression. What do you mean by 'delete that column from the graph'?

http://stackoverflow.com/comment/89334350
score: 0
type: Comment
has text: @Jean-FrançoisFabre: You are right. This should be even faster!
comment on: http://stackoverflow.com/a/51174640
type: AnswerComment

http://stackoverflow.com/comment/89359161
comment on: http://stackoverflow.com/a/51188768
has text: Thanks Rakesh, any idea why my approach didn't work?
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/51255660
score: 4
tagged with: flask
tagged with: python
has answer: http://stackoverflow.com/a/64011854
favorite count: 0
type: UnansweredQuestion
type: Question
upvote count: 4
answer count: 2
tagged with: plotly-dash
has title: Multi-Page Dash Application
downvote count: 0
has body: I'm trying to build a multi page Dash App. When I run the following code, everything works except it won't route to my /dash_1 or /dash_2 urls. Was wondering if someone could help me out. My structure looks like this: dash-project/ app1/ app.py app2/ app.py server.py run.py My run.py code is from app import server as application from app import app import app_1.dash_1 import app_2.dash_2 My app.py code is: from flask import Flask from flask_sqlalchemy import SQLAlchemy from werkzeug.wsgi import DispatcherMiddleware import os import pandas as pd import dash import flask import dash import dash_core_components as dcc import dash_html_components as html import pandas as pd import plotly.graph_objs as go from analysis import * server=flask.Flask(name) app = dash.Dash(name) app.config.suppress_callback_exceptions = True app.css.append_css({ ‘external_url’: ‘https://codepen.io/chriddyp/pen/bWLwgP.css’ }) My dash_1.py code is: import dash import dash_core_components as dcc import dash_html_components as html from dash.dependencies import Input, Output import pandas as pd import plotly.graph_objs as go from analysis import * from app import app, server app = dash.Dash(name='dash_1', sharing=True, url_base_pathname='/dash_1', csrf_protect=False) app.config['suppress_callback_exceptions']=True df = pd.read_csv('/Users/ds/app_1/main.csv') layout = html.Div([ dcc.Graph( id='Senators ', figure={ 'data': [ go.Scatter( x=df[df['candidate'] == i] ['contributor_individual'], y=df[df['candidate_name'] == i]['contributor'], #z=df[df['candidate_name'] == i]['contributor'], text=df[df['candidate_name'] == i]['contributorl'], mode='markers', opacity=0.7, marker={ 'size': 15, 'line': {'width': 0.5, 'color': 'white'} }, name=i ) for i in df.candidate_name.unique() ], 'layout': go.Layout( xaxis={'title': 'Contributor '}, yaxis={'title': 'Contributor '}, #margin={'l': 40, 'b': 40, 't': 10, 'r': 10}, #legend={'x': 0, 'y': 1}, hovermode='closest' ) } ) ]) layout = html.Div(children=[ html.H1(c…
has answer: http://stackoverflow.com/a/51255720

http://stackoverflow.com/a/51234801
accepted answer of: http://stackoverflow.com/q/51211443
has comment: http://stackoverflow.com/comment/89448844
has comment: http://stackoverflow.com/comment/89448569
has comment: http://stackoverflow.com/comment/89502454
score: 4
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89500966
type: Answer
has comment: http://stackoverflow.com/comment/89448961
upvote count: 4
has body: You have forgotten to add the temp as one of the inputs of the GAN (that's why the error says it can't feed the corresponding tensor since it is essentially disconnected): combined = Model([z, temp], valid) As a side note, I highly recommend to use Keras Functional API for building complicated and multi branch models like your discriminator. It is much easier to use, being more flexible and less error-prone. For example, this is the descriminator you have written but I have rewritten it using Functional API. I personally think it is much easier to follow: def build_discriminator(img_shape,embedding_shape): input_img = Input(shape=img_shape) x = Conv2D(32, kernel_size=5, strides=2, padding="same")(input_img) x = LeakyReLU(alpha=0.2)(x) x = Dropout(0.25)(x) x = Conv2D(48, kernel_size=5, strides=2, padding="same")(x) x = BatchNormalization(momentum=0.8)(x) x = LeakyReLU(alpha=0.2)(x) x = Dropout(0.25)(x) x = Conv2D(64, kernel_size=5, strides=2, padding="same")(x) x = BatchNormalization(momentum=0.8)(x) x = LeakyReLU(alpha=0.2)(x) x = Dropout(0.25)(x) x = Conv2D(128, kernel_size=5, strides=2, padding="same")(x) x = BatchNormalization(momentum=0.8)(x) x = LeakyReLU(alpha=0.2)(x) x = Dropout(0.25)(x) x = Conv2D(256, kernel_size=5, strides=2, padding="same")(x) x = BatchNormalization(momentum=0.8)(x) x = LeakyReLU(alpha=0.2)(x) x = Dropout(0.25)(x) x = Flatten()(x) output_img = Dense(200)(x) input_emb = Input(shape=embedding_shape) y = Dense(50)(input_emb) y = Dense(100)(y) y = Dense(200)(y) output_emb = Flatten()(y) merged = concatenate([output_img, output_emb]) output_merge = Dense(1, activation='sigmoid', name='output_layer')(merged) return Model([input_img, input_emb], output_merge)
answers question: http://stackoverflow.com/q/51211443
downvote count: 0
has comment: http://stackoverflow.com/comment/89448909

http://stackoverflow.com/q/51199585
tagged with: directory
score: 1
favorite count: 0
tagged with: python-3.x
has body: Let's say I have a root directory 'x' number of directories up from the current directory. How can I find the full path to this root directory in python assuming 'x' can change and thus can't be hard-coded in any way?
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51199652
has answer: http://stackoverflow.com/a/51199949
upvote count: 1
tagged with: python
tagged with: filepath
has title: Find location of directory 'x' number of directories up
type: Question
answer count: 2
downvote count: 0

http://stackoverflow.com/comment/89522937
has text: I'm using cuda 8. So after the first tensor is loaded, will it execute quickly? I have left the program even for 20 minutes, without any further progress below that line of output.
score: 0
comment on: http://stackoverflow.com/q/51271817
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51230188
has comment: http://stackoverflow.com/comment/89440111
type: Question
has answer: http://stackoverflow.com/a/51230393
has answer: http://stackoverflow.com/a/51230701
accepted answer: http://stackoverflow.com/a/51230701
has title: How to assign dictionary results to individual variables in python3?
linked to: http://stackoverflow.com/q/5036700
tagged with: python-3.6
possible better answer: http://stackoverflow.com/a/51230393
has body: I have this result: {'orderId': 1234567, 'price': '20.5', 'qty': '125', 'status': 'open'} {'orderId': 7654321, 'price': '15.5', 'qty': '15', 'status': 'open'} {'orderId': 9876543, 'price': '32.0', 'qty': '102', 'status': 'open'} I want to assign each orderID to individual variable, so I can do something to each of them. Above result is gained thru filtering code as follow: orders = product.get_open_orders(product='sample') keys = ['orderId', 'price', 'qty', 'status'] res = [{k: d[k] for k in keys} for d in orders] for status in res: if status['status'] == 'open': print(status)
has comment: http://stackoverflow.com/comment/89440356
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/89440190
has comment: http://stackoverflow.com/comment/89440449
tagged with: python
has comment: http://stackoverflow.com/comment/89440141
type: AnsweredQuestion

http://stackoverflow.com/q/51285559
type: Question
score: 3
tagged with: lstm
upvote count: 3
tagged with: pandas
downvote count: 0
has body: I have a data set with various samples, each sample having one or more events at irregular time intervals. There are several features associated with the events. I want to predict binary labels associated with each sample. The data set looks like this: import pandas as pd X = pd.DataFrame({'id': [1,1,1,2,2,3,3,3,3], 'time': [-1,-5,-10,-2,-4,-1,-4,-7,-10], 'var1': [1,2,1,3,1,2,1,3,1], 'var2': [3,3,1,4,1,3,3,1,2], 'var3': [4,5,6,1,3,5,6,7,8]}) Y = pd.DataFrame({'id': [1,2,3], 'label': [0,1,0]}) In X, the column id is the sample, time reflects how many days ago was the event. Var1..3 are features associated with the event (categorical). In Y, column label is the response to be predicted. In the actual data set, the number of events per sample varies quite a lot, from 1 to few hundered. How can I use Keras LSTM to render a prediction of the label in the Y data frame, using the features of the past events in the X data frame?
tagged with: keras
favorite count: 0
tagged with: python
has title: Keras LSTM for classification of time series with irregular intervals
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/125570136

http://stackoverflow.com/a/51317814
has body: The stack trace is from a run with multiprocessing enabled, so it's not really informative as to what else is going wrong. Reducing max_queue_size might work. Reducing the batch size is the usual recommendation when running out of GPU memory. But you're running out of regular RAM.
type: Answer
answers question: http://stackoverflow.com/q/51316658
has comment: http://stackoverflow.com/comment/89625665
has comment: http://stackoverflow.com/comment/89701630
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51316658
score: 0

http://stackoverflow.com/comment/89561426
has text: @ PRMoureu Thanks!
score: 0
comment on: http://stackoverflow.com/q/51291808
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/111202662
type: Comment
score: 2
type: AnswerComment
has text: How do you handle object of type ndarray with this?
comment on: http://stackoverflow.com/a/51286749

http://stackoverflow.com/a/51229262
score: 1
upvote count: 1
has body: You could loop through your list of data and then split each element. Then you can add that data to the product, cost and condition lists by using .append(): data = ["xbox 360 | 13000 | new","playstation 4 | 30000 | new","playstation 3 | 30000 | old","playstation 2 | 30000 | old"] product = [] cost = [] condition = [] for string in data: strSplit = string.split(" | ") product.append(strSplit[0]) cost.append(strSplit[1]) condition.append(strSplit[2]) print(product) print(cost) print(condition) Result of the following code: ['xbox 360', 'playstation 4', 'playstation 3', 'playstation 2'] ['13000', '30000', '30000', '30000'] ['new', 'new', 'old', 'old']
downvote count: 0
has comment: http://stackoverflow.com/comment/89438870
answers question: http://stackoverflow.com/q/51229187
type: Answer

http://stackoverflow.com/comment/89367840
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51192353
type: Comment
has text: @SanjayWadhwa: I'd get them sorted then; there are efficient command-line tools that can get you a sorted file output. Even if you only sort *subsets of each file*, you can use `heapq.merge()` to sort together any number of subsets if each subset is sorted.

http://stackoverflow.com/a/51512058
answers question: http://stackoverflow.com/q/51183901
type: AcceptedAnswer
upvote count: 5
type: Answer
has comment: http://stackoverflow.com/comment/105779898
downvote count: 0
has comment: http://stackoverflow.com/comment/132073734
has body: You will need to put a compiled terminfo entry in anaconda's temrinfo directory. The entry for urxvt needs to be placed in $_CONDA_ROOT/share/terminfo/r/. I ran the following copy and verified it works now: cp /usr/share/terminfo/r/rxvt-unicode-256color ~/anaconda/share/terminfo/r/ If you have multiple environments you will have to do it for them as well: cp /usr/share/terminfo/r/rxvt-unicode-256color ~/anaconda/envs/data_science/share/terminfo/r/
score: 5
accepted answer of: http://stackoverflow.com/q/51183901
has comment: http://stackoverflow.com/comment/95724052

http://stackoverflow.com/a/51186903
has body: The easiest way is to use the text() function. You can either link it to the figure: f.text(x=0.5, y=0.94, 'title', ha='center') You can use the following arguments that are quite straightforward: rotation='vertical' fontsize=10 You could also link the title to a subplot, and use the X, Y of this subplot to position it: ax[0].text(0, 1.02, "title above the first subplot", fontsize=10, transform=ax[0].transAxes) And finally, you might need to redefine the dimension of the plotting area. This can be done with: for a in f.axes: # Shrink the axes box = a.get_position() a.set_position([box.x0, box.y0, box.width * 0.9, box.height * 0.95])
upvote count: 1
answers question: http://stackoverflow.com/q/51186663
downvote count: 0
score: 1
type: Answer

urllib
tags question: http://stackoverflow.com/q/51256851
tags question: http://stackoverflow.com/q/51182538
type: Tag
tags question: http://stackoverflow.com/q/51216637
tags question: http://stackoverflow.com/q/51233792
tag name: urllib
tags question: http://stackoverflow.com/q/51257808
tags question: http://stackoverflow.com/q/51227425
tags question: http://stackoverflow.com/q/51181637
tags question: http://stackoverflow.com/q/51258627
tags question: http://stackoverflow.com/q/51245170

http://stackoverflow.com/comment/89441110
type: Comment
score: 0
type: AnswerComment
has text: I see, it's called intermixed parsing. Good to know, thanks. I just install Python 3.7 and it's working smoothly there.
comment on: http://stackoverflow.com/a/51227190

http://stackoverflow.com/a/51281994
has body: In urls.py you have to add the url that you will be calling. It could be something like: url(r'^call-main/$', views.call_main, name='call-main') And then the ajax call from the function that you wrote: $.ajax({ url: "{% url 'call-main' %}", type: "POST", data: { csrfmiddlewaretoken: '{{ csrf_token }}' }, success: function () { // something here on success }, error: function () { // something here on error } });
has comment: http://stackoverflow.com/comment/89550772
has comment: http://stackoverflow.com/comment/89549148
has comment: http://stackoverflow.com/comment/89548947
answers question: http://stackoverflow.com/q/51280126
has comment: http://stackoverflow.com/comment/89549942
score: 0
has comment: http://stackoverflow.com/comment/89549564
type: Answer
has comment: http://stackoverflow.com/comment/89549302

http://stackoverflow.com/q/51265816
answer count: 1
favorite count: 0
has title: countr += 0 shows none pi2go
tagged with: python
tagged with: global
has answer: http://stackoverflow.com/a/51265907
downvote count: 0
type: UnansweredQuestion
has body: I have no idea anymore. I've been struggling for hours now. I got a pi2golite here with wheel sensors. the wheelCount() isn't working anyway (or at least I dont know how) so I've been trying to find another solution. The 2 motors I've got seem to run on different speed's. I wanted to see that in numbers to change the speed of each motor so they run the same. import pi2go, time pi2go.init() running = True countL = 0 countR = 0 def counter1(): global countR countR += 0 speed = 60 try: pi2go.stepForward(50,10) time.sleep(2) print counter1() print countL finally: pi2go.cleanup() -> When I try to run it, the motor's run fine and turn off after the 10 steps (so it has to be counting) it outputs this: for countL -> 0 for counter1() ->None Why none?
score: 1
has comment: http://stackoverflow.com/comment/89509533
type: Question
tagged with: raspberry-pi
upvote count: 1

http://stackoverflow.com/comment/89472010
has text: Yeah you need to use the other site. If you register it in Azure Portal, you need to use the v1 endpoints.
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/51238476

http://stackoverflow.com/a/51232367
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51227181
has body: Solved. Thanks for all the hints. It was different swig versions.

http://stackoverflow.com/comment/122447237
has text: `import matplotlib as mpl` where `mpl` is the correct alias, not `plt`. [matplotlib Usage Guide](https://matplotlib.org/stable/tutorials/introductory/usage.html#splitting-lines-into-smaller-chunks)
type: Comment
comment on: http://stackoverflow.com/a/64450048
type: AnswerComment
score: 0

http://stackoverflow.com/a/51230387
upvote count: 7
downvote count: 1
has body: Try this instead with open('url.txt', 'a',encoding='utf-8') as file:
has comment: http://stackoverflow.com/comment/89442165
type: AcceptedAnswer
score: 6
type: Answer
accepted answer of: http://stackoverflow.com/q/51230307
answers question: http://stackoverflow.com/q/51230307

http://stackoverflow.com/q/51324202
possible better answer: http://stackoverflow.com/a/51324709
tagged with: python
has title: Check if an image contains blue pixels
has answer: http://stackoverflow.com/a/51324575
tagged with: opencv
score: 2
type: AnsweredQuestion
tagged with: image-processing
linked to: http://stackoverflow.com/q/17878254
type: Question
has body: I have this image: And I'm trying to write a function in Python that will return True if the image contains blue pixels, or False otherwise. That image is just an example. I will have others were the blue colour can be slightly different. But they will always be blue letters over a black background. So far I have this: def contains_blue(img): # Convert the image to HSV colour space hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) # Define a range for blue color hsv_l = np.array([100, 150, 0]) hsv_h = np.array([140, 255, 255]) # Find blue pixels in the image # # cv2.inRange will create a mask (binary array) where the 1 values # are blue pixels and 0 values are any other colour out of the blue # range defined by hsv_l and hsv_h return 1 in cv2.inRange(hsv, hsv_l, hsv_h) The function always returns False because no 1 values are found in the array returned by cv2.inRange. Maybe the range defined by hsv_l and hsv_h is not good? I took it from here: OpenCV &amp; Python -- Can&#39;t detect blue objects Any help is appreciated. Thanks.
upvote count: 3
answer count: 2
downvote count: 1
has answer: http://stackoverflow.com/a/51324709
accepted answer: http://stackoverflow.com/a/51324575
favorite count: 0

http://stackoverflow.com/comment/96231467
type: AnswerComment
comment on: http://stackoverflow.com/a/54723666
score: 0
type: Comment
has text: Place the file in C:\Users\<user> - Please note this correction Jomon

opencv
tags question: http://stackoverflow.com/q/51245502
tags question: http://stackoverflow.com/q/51270207
type: Tag
tags question: http://stackoverflow.com/q/51324202
tags question: http://stackoverflow.com/q/51261043
tags question: http://stackoverflow.com/q/51273639
tags question: http://stackoverflow.com/q/51178942
tags question: http://stackoverflow.com/q/51233359
tags question: http://stackoverflow.com/q/51185292
tags question: http://stackoverflow.com/q/51307561
tags question: http://stackoverflow.com/q/51233491
tags question: http://stackoverflow.com/q/51213730
tags question: http://stackoverflow.com/q/51285930
tags question: http://stackoverflow.com/q/51209343
tags question: http://stackoverflow.com/q/51315809
tags question: http://stackoverflow.com/q/51288756
tags question: http://stackoverflow.com/q/51277108
tags question: http://stackoverflow.com/q/51243562
tags question: http://stackoverflow.com/q/51252872
tags question: http://stackoverflow.com/q/51237354
tags question: http://stackoverflow.com/q/51229202
tags question: http://stackoverflow.com/q/51227437
tags question: http://stackoverflow.com/q/51309603
tags question: http://stackoverflow.com/q/51176438
tags question: http://stackoverflow.com/q/51270649
tags question: http://stackoverflow.com/q/51320121
tags question: http://stackoverflow.com/q/51303321
tags question: http://stackoverflow.com/q/51260994
tags question: http://stackoverflow.com/q/51213035
tags question: http://stackoverflow.com/q/51168268
tags question: http://stackoverflow.com/q/51314824
tags question: http://stackoverflow.com/q/51190561
tags question: http://stackoverflow.com/q/51284472
tags question: http://stackoverflow.com/q/51225657
tags question: http://stackoverflow.com/q/51288826
tags question: http://stackoverflow.com/q/51185172
tags question: http://stackoverflow.com/q/51205006
tags question: http://stackoverflow.com/q/51248709
tags question: http://stackoverflow.com/q/51291183
tags question: http://stackoverflow.com/q/51303361
tags question: http://stackoverflow.com/q/51312645
tag name: opencv
tags question: http://stackoverflow.com/q/51205328
tags question: http://stackoverflow.com/q/51220865
tags question: http://stackoverflow.com/q/51289629
tags question: http://stackoverflow.com/q/51227864
tags question: http://stackoverflow.com/q/51254244
tags question: http://stackoverflow.com/q/51229126
tags question: http://stackoverflow.com/q/51259233
tags question: http://stackoverflow.com/q/51276866
tags question: http://stackoverflow.com/q/51177099
tags question: http://stackoverflow.com/q/51285593
tags question: http://stackoverflow.com/q/51323364
tags question: http://stackoverflow.com/q/51183411
tags question: http://stackoverflow.com/q/51234114
tags question: http://stackoverflow.com/q/51323776
tags question: http://stackoverflow.com/q/51231989
tags question: http://stackoverflow.com/q/51290866
tags question: http://stackoverflow.com/q/51229355
tags question: http://stackoverflow.com/q/51190572
tags question: http://stackoverflow.com/q/51205502
tags question: http://stackoverflow.com/q/51217067
tags question: http://stackoverflow.com/q/51293754
tags question: http://stackoverflow.com/q/51320446
tags question: http://stackoverflow.com/q/51291991
tags question: http://stackoverflow.com/q/51272055
tags question: http://stackoverflow.com/q/51183023
tags question: http://stackoverflow.com/q/51285616
tags question: http://stackoverflow.com/q/51308292
tags question: http://stackoverflow.com/q/51313763
tags question: http://stackoverflow.com/q/51169162
tags question: http://stackoverflow.com/q/51182852
tags question: http://stackoverflow.com/q/51179926
tags question: http://stackoverflow.com/q/51172555
tags question: http://stackoverflow.com/q/51215625
tags question: http://stackoverflow.com/q/51173278
tags question: http://stackoverflow.com/q/51235043
tags question: http://stackoverflow.com/q/51295557
tags question: http://stackoverflow.com/q/51277907
tags question: http://stackoverflow.com/q/51299207

http://stackoverflow.com/comment/89414493
has text: No problem .Important thing is you have understood
type: Comment
comment on: http://stackoverflow.com/a/51216425
score: 0
type: AnswerComment

http://stackoverflow.com/a/51242742
answers question: http://stackoverflow.com/q/51210955
accepted answer of: http://stackoverflow.com/q/51210955
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 3
upvote count: 3
has body: I managed to find a solution that is exactly what I need. Thank to @ImportanceOfBeingErnest that gave me the idea to let the regplot only draw the regression line. Solution: import pandas as pd classes = np.array([1., 1., 1., 1., 1., 1., 1., 1., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 3., 3., 3., 3., 3., 3., 3., 3., 3., 3., 3., 3., 3., 3., 3., 3., 3., 3., 3., 3., 3.]) df = pd.DataFrame(map(list, zip(*[X.T, y.ravel().T]))) df = df.reset_index() df['index'] = classes[:] g = sns.jointplot(X, y, kind='reg', scatter = False ) for i, subdata in df.groupby("index"): sns.kdeplot(subdata.iloc[:,1], ax=g.ax_marg_x, legend=False) sns.kdeplot(subdata.iloc[:,2], ax=g.ax_marg_y, vertical=True, legend=False) g.ax_joint.plot(subdata.iloc[:,1], subdata.iloc[:,2], "o", ms = 8) plt.tight_layout() plt.show()

http://stackoverflow.com/comment/89591090
has text: Don't parse html using regex
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/51307191
type: Comment

http://stackoverflow.com/comment/89618690
score: 0
type: AnswerComment
type: Comment
has text: [i got a generic way to go around, working code in the link](http://txt.do/dzpkf)
comment on: http://stackoverflow.com/a/51280095

http://stackoverflow.com/a/51202924
downvote count: 1
answers question: http://stackoverflow.com/q/51202856
type: Answer
has body: Let the number be the input you are taking from the user. while(1): #To ensure that input is continuous number = int(input()) if number>=1 and number<=10 and number.isdigit(): break #if the input is valid, you can proceed with the number else: print("Enter a valid Number") The number can be used for further operations.
has comment: http://stackoverflow.com/comment/89386966
upvote count: 0
score: -1

http://stackoverflow.com/a/51282841
has comment: http://stackoverflow.com/comment/89543901
has comment: http://stackoverflow.com/comment/89542993
type: AcceptedAnswer
downvote count: 0
score: 2
answers question: http://stackoverflow.com/q/51279846
accepted answer of: http://stackoverflow.com/q/51279846
upvote count: 2
has comment: http://stackoverflow.com/comment/89548685
type: Answer
has body: A good way to solve your problem is to use regex. REGular EXpression are a common way in programming to parse strings. With regex you can define which pattern you want to search in a string (almost like you did), which is the core of your problem. This means that regex have their own formatting, similar, but not identical, to yours. You can also write some code to convert your formatting to regex formatting, but you probably should write another question, avoiding all the DNA stuff. Lets see how regex works: Here is how your summary looks like in regex pattern: Summary There can be these types in motifs, which need to be defined, and each locus would have different combination of motifs: Brackets: example [CTAT] – multiple copies of CTAT - RegEx: (CTAT)+ (one or more) or (CTAT)* (zero or more) No brackets: example CTAT – only one copy of CTAT - RegEx: (CTAT){1} N#: example N30 - means 30 unspecified nucleotides (A/C/G/T) - RegEx: .{30} Lower case: example ctat - means that these are not included in final allele number - RegEx: (?:CTAT) With this knowledge, we can apply our regex to our inputs: example 1: import re # import regex module tandem = r"((AGAT){1}(AGAC){1}(AGAT)+(?:GAT){1}(AGAT)+)" mystring = "TTAGTTCAGGATAGTAGTTGTTTGGAAGCGCAACTCTCTGAGAAACTTAGTTATTCTCTCATCTATTTAGCTACAGCAAACTTCATGTGACAAAAGCCACACCCATAACTTTTTTCCTCTAGATAGACAGATAGATGATAGATAGATAGATAGATAGATAGATAGATAGATAGATAGATAGATAGATATAGATTCTCTTTCTCTGCATTCTCATCTATATTTCTGTCTTTCTCTTAATTATGGGTAACTCTTAGCCTGCCAGGCTACCATGGAAAGACAACCTTTAT" #input string analyzed_input = re.findall(tandem, mystring)[0] print(analyzed_input) #see the match found tot = 0 max_len = max((len(al) for al in analyzed_input[1:] if len(al) &lt;= 4)) # longest allele, maximum 4 remaining_string = analyzed_input[0] #string to analyzed. will be cutted in for loop for allele in analyzed_input[1:]: #for each allele section = re.findall(r"((" + re.escape(allele) + ")+)", remaining_string)[0][0] # section where the allele is repeated value = section.co…

http://stackoverflow.com/comment/89372012
comment on: http://stackoverflow.com/q/51192795
type: QuestionComment
type: Comment
score: 2
has text: As far as I can see, Tkinter `askdirectory()` wraps the `Tk` function `tk_chooseDirectory` and this function does not take that option. See [Tk documentation](https://www.tcl.tk/man/tcl/TkCmd/chooseDirectory.htm)

http://stackoverflow.com/q/51266273
type: UnansweredQuestion
has title: Print statement gives not callable error
has comment: http://stackoverflow.com/comment/89512430
has body: print = ('Tell me about your pet. ') about_pet = input() if 'dog'.lower() in about_pet == True : print('ah, a dog') if 'cat'.lower() in about_pet == True : print ('ooh, a kitty') print ('Thanks for the story') when I run this code I get an error: str object is not callable What causes this?
type: Question
favorite count: 0
upvote count: 2
downvote count: 2
has answer: http://stackoverflow.com/a/51266502
tagged with: python
answer count: 1
has comment: http://stackoverflow.com/comment/89510833
score: 0
tagged with: callable

http://stackoverflow.com/a/51197884
upvote count: 1
score: 1
accepted answer of: http://stackoverflow.com/q/51197176
answers question: http://stackoverflow.com/q/51197176
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/89590384
has comment: http://stackoverflow.com/comment/89381586
has comment: http://stackoverflow.com/comment/89676693
type: Answer
has body: What I would do is write a regex expression to extract the numbers from your column join the tables, and maybe do the rest in excel... (the column updates) df1 = pd.DataFrame({'Department' : ['Merch - 1854', '1925 - WH','Montreal 10'],'TrueDeparment' : ['Empty','empty','empty']}) df2 = pd.DataFrame({'Dept_Nbr' : [1854, 1925, 10], 'Dept_Desc_HR' : ['Community Relations','Human Resources','Recruiting']}) Then here you can try what the function does: line = 'Merch - 1854 ' match = re.search(r'[0-9]+', line) if match is None: print(0) else: print(int(match[0])) If you need the match after a character as specified in your comment use this one: line = '12125 15151 Merch -1854 ' match = re.search(r'(?&lt;=-)[0-9]+', line) if match is None: print(0) else: print(int(match[0])) Note that if you have spaces or other characters after the "-" you need to add it to the regex to work! Important - you suppose that you only have one number in your text - if not it returns 0 you can change it as you wish the point is that at least it doesn't fail Write the function: def extract_number(field): match = re.search(r'(?&lt;=-)[0-9]+', field) if match is None: return 0 else: return int(match[0]) Apply to dataframe: df1['num_col'] = df1'Department'.apply(lambda row:extract_number(row['Department']),axis=1) Lastly do the join: df1.merge(df2, left_on = ['num_col'], right_on = ['Dept_Nbr']) From here you can figure out which column you need whether here in Python, or in excel.

http://stackoverflow.com/q/51293876
type: AnsweredQuestion
has body: I am doing image processing in python and am using the skimage rag_mean_color and segmentation methods to first segment the image. I then use graph.cut_threshold to merge adjacent regions with similar colors. At the end I have a very large region of a single color I want to extract. I have been using another method to try and get the most common color in the picture (kmeans) but am not getting the results I want. I was wondering if there is a way to get the color of the region directly from the graph. Thanks! RAG code: img = cv2.imread(path) # convert the image to HSV img = cv2.cvtColor(img, cv2.COLOR_RGB2HSV) # apply the RAG thresholding on the image labels1 = segmentation.slic(img, compactness=10, n_segments=600) out1 = color.label2rgb(labels1, img, kind='avg') # create the region adjacency graph from the labels and image g = graph.rag_mean_color(img, labels1) # merge similar regions in the image/graph labels2 = graph.cut_threshold(labels1, g, 20) out2 = color.label2rgb(labels2, img, kind='avg') # construct an updated graph for the image from the merged labels g2 = graph.rag_mean_color(out2, labels2) # merge similar regions a second time to ensure like regions are merged labels3 = graph.cut_threshold(labels2, g2, 30) out3 = color.label2rgb(labels3, out2, kind='avg') This is the image I get: Dominant Color Code: # get the dominant (most common) color in an image using kmeans # convert the image into HSV color space img = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) # reshape the photo to be rows of colors data = img.copy().reshape((img.shape[0]*img.shape[1], 3)).astype(float) # apply kmeans to the data centroids, codes = kmeans2(data, 5) # get the most common centroid centroid = np.argmax(np.bincount(codes)) d_color = centroids[centroid].astype(np.uint8) This is the color I get:
score: 1
has answer: http://stackoverflow.com/a/51297722
tagged with: scikit-image
tagged with: image-processing
tagged with: image
type: Question
accepted answer: http://stackoverflow.com/a/51297722
downvote count: 0
answer count: 1
tagged with: python
has title: How to access properties of skimage RAG
favorite count: 0
upvote count: 1

http://stackoverflow.com/comment/89598480
type: Comment
type: QuestionComment
has text: Welcome to StackOverflow. Please read and follow the posting guidelines in the help documentation, as suggested when you created this account. [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.
score: 3
comment on: http://stackoverflow.com/q/51310672

http://stackoverflow.com/comment/89369337
type: Comment
type: QuestionComment
has text: Yeah I don't understand the escaping codes either. I got this from the Postman application.
comment on: http://stackoverflow.com/q/51193819
score: 0

http://stackoverflow.com/a/51282190
has comment: http://stackoverflow.com/comment/89558471
answers question: http://stackoverflow.com/q/51279921
type: Answer
has body: This error message... An error has occured in 'site url': Uncaught TypeError: Cannot read property 'getColomnSet' of undefined ...implies that your program was unable to read the property getColomnSet while trying to download the desired file. Possibly, the main problem is the js involved to download the document is invoked before the client renders the HTML DOM completely. The relevant HTML, a bit more of your previous lines of code and the error stack trace would have given us some more idea about what's going wrong. Solution You can induce some measures to wait till the complete DOM Tree is rendered following the discussion: Generic funtion to check if page has completely loaded in Selenium A couple of facts: In your code trials I don't see you interacting with the element (By.ID,'element_1_id') so possibly you can remove the step of presence_of_element_located() for the element (By.ID,'element_1_id'). If you still require presence_of_element_located((By.ID,'element_1_id')) catch the exception and initiate required steps. As you invoke move_to_element() over elem1 and elem2 and moving ahead invoke perform() you need to induce WebDriverWait with expected_conditions as element_to_be_clickable(locator) tl;dr (references) Cannot read property 'getContext' of null, using canvas Uncaught TypeError: Cannot read property 'getContext' of undefined Uncaught Error remote.js
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51279921

instantiation
type: Tag
tags question: http://stackoverflow.com/q/51290827
tag name: instantiation

http://stackoverflow.com/q/51319318
favorite count: 0
has title: Regex replace in Spyder with case conversion
type: UnansweredQuestion
tagged with: python
tagged with: regex
answer count: 0
score: 1
duplicate of: http://stackoverflow.com/q/1175208
type: Question
has body: I would like to convert a string from camelCase to snake_case using regex. I could do this using python through the terminal or a text editor I am more familiar with, but I would like to know if this is possible in the built-in search and replace of Spyder. I am able to catch the groups, using Pattern: ([a-z])([A-Z]) Replace with: \1\2 , but not to convert the case like I read here.
linked to: http://stackoverflow.com/q/1175208
has comment: http://stackoverflow.com/comment/89614442
upvote count: 1
tagged with: spyder
downvote count: 0

http://stackoverflow.com/comment/89561905
score: 1
has text: The only difference of your case compared to the one in the linked duplicate is that you already have a "list" of images. I.e. you need to animate over the array `data[:,:,j]` where `j` is the animating variable.
type: Comment
comment on: http://stackoverflow.com/q/51291993
type: QuestionComment

http://stackoverflow.com/q/51318559
possible better answer: http://stackoverflow.com/a/51318747
has comment: http://stackoverflow.com/comment/89613789
tagged with: sql-server
has comment: http://stackoverflow.com/comment/89656020
favorite count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/89721292
tagged with: python
has title: Insert a dictionary into SQL database created using JSON in Python
has answer: http://stackoverflow.com/a/51318747
type: AnsweredQuestion
score: 2
has comment: http://stackoverflow.com/comment/89613840
has comment: http://stackoverflow.com/comment/89719892
has body: I have a JSON file from which I read data and get a dictionary I would like this complete dictionary to be inserted into a SQL Server database so that the same can be read as dictionary from the database. But upon insertion of the same I get an error as below. 07/13/2018 11:25:00: ERROR: Exception 102: Incorrect syntax near 'camera'.DB-Lib error Msg 102, severity 15: General SQL Server error: Check messages from the SQL Server Below is my INSERT query. INSERT INTO hw_info (hostname, peripheralsInfo) VALUES ('linux-host', '{u'camera': {u'ab': {u'model': u'Model1', u'version': u'Version1', u'selectorMask': u'Data1'}, u'cd': {u'model': u'Model2', u'version': u'Version2', u'selectorMask': u'Data2'}}}') How can this dictionary be inserted into the database?
has answer: http://stackoverflow.com/a/51344210
accepted answer: http://stackoverflow.com/a/51344210
has comment: http://stackoverflow.com/comment/89613378
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/89613965
downvote count: 0
tagged with: pymssql
has comment: http://stackoverflow.com/comment/89613889
has comment: http://stackoverflow.com/comment/89668505

http://stackoverflow.com/comment/89544856
type: Comment
score: 0
type: AnswerComment
has text: Thanks again Mike, that has helped, but looking at the options you gave I won't bother trying to order them as when I open them I can just use the file name rather than the order they are listed in. Also, I am new to stack overflow with and don't know how to mark a comment as accepted.
comment on: http://stackoverflow.com/a/51268642

http://stackoverflow.com/a/51271861
answers question: http://stackoverflow.com/q/51271569
type: Answer
has body: Trying to elaborate on what can be done: Intialize/ Merge the dataframe and convert the column into datetime type df= pd.DataFrame({'people':[1,2,0],'date': ['6/8/2015','7/10/2018','6/5/2015',]}) df.date=pd.to_datetime(df.date,format="%m/%d/%Y") print(df) Output: date people 0 2015-06-08 1 1 2018-07-10 2 2 2015-06-05 0 Sort on the basis of date df=df.sort_values('date') print(df) Output: date people 2 2015-06-05 0 0 2015-06-08 1 1 2018-07-10 2 Maintain the format again: df['date']=df['date'].dt.strftime('%m/%d/%Y') print(df) Output: date people 2 06/05/2015 0 0 06/08/2015 1 1 07/10/2018 2
score: 4
has comment: http://stackoverflow.com/comment/89523730
upvote count: 4
downvote count: 0

http://stackoverflow.com/comment/89588148
has text: Right @abarnert I've done, that I've moved from file to the pipe stdout, however, i've come back to the error, that made me move to a file in the first place, it just blocks it.
comment on: http://stackoverflow.com/q/51294742
score: 0
type: Comment
type: QuestionComment

snowflake-cloud-data-platform
tags question: http://stackoverflow.com/q/51298477
tag name: snowflake-cloud-data-platform
type: Tag

http://stackoverflow.com/q/51213862
tagged with: python
tagged with: regex
favorite count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/89409059
downvote count: 2
type: Question
has comment: http://stackoverflow.com/comment/89409245
has comment: http://stackoverflow.com/comment/89408941
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51214046
answer count: 1
has body: I have some list of titles and I need to know if they are valid. I was trying some variations of this one - ^\d{1}\.\d My list is something like this one: Valid - this need to be a valid title 1.1.1 - Abreviaturas utilizadas 1.10.6.7 - VII - Situações 1.11.2 - Membros Invalid - my regular expression cannot set this as valid title 3.5452/2012 9.8 Do you think it is possible to map this problem with regex? My idea is a regex who catch any quantity of numbers followed by a dot until find a empty space and a dash (-). My tests: https://regex101.com/r/bjTptv/3
has title: Validating section titles with regex
score: 0
has comment: http://stackoverflow.com/comment/89409677
has comment: http://stackoverflow.com/comment/89409582
has answer: http://stackoverflow.com/a/51214046

http://stackoverflow.com/comment/89490497
comment on: http://stackoverflow.com/a/51255720
score: 0
type: AnswerComment
has text: AttributeError: 'NoneType' object has no attribute 'traverse'
type: Comment

http://stackoverflow.com/comment/89630531
score: 0
type: AnswerComment
type: Comment
has text: Thanks for clarification!
comment on: http://stackoverflow.com/a/51272328

http://stackoverflow.com/comment/89389350
type: Comment
has text: @jedwards I agree, I think this is the correct version. (Note I reverse on purpose inside f).
comment on: http://stackoverflow.com/a/51199384
score: 0
type: AnswerComment

http://stackoverflow.com/a/51239175
answers question: http://stackoverflow.com/q/51238873
has body: Using collections.Counter Ex: import pandas as pd from decimal import Decimal from collections import Counter record = pd.DataFrame({"user": ("Anna", "Bell", "Anna", "Chad", "Bell", "Anna"), "speed": (1.0, 1.2, 1.3, 1.5, 1.4, 1.1)}) encounter = {} for k,v in Counter(record["user"].tolist()).items(): encounter[k] = [v, (record[record["user"] == k]["speed"].iloc[-1]).round(1).astype(Decimal)] print(encounter) Output: {'Anna': [3, 1.1], 'Chad': [1, 1.5], 'Bell': [2, 1.4]}
has comment: http://stackoverflow.com/comment/89459275
downvote count: 0
upvote count: 2
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/89459530

mysql
tags question: http://stackoverflow.com/q/51175480
tags question: http://stackoverflow.com/q/51200674
tags question: http://stackoverflow.com/q/51320402
tags question: http://stackoverflow.com/q/51243998
tags question: http://stackoverflow.com/q/51318547
tags question: http://stackoverflow.com/q/51299174
tags question: http://stackoverflow.com/q/51291362
tags question: http://stackoverflow.com/q/51317225
tags question: http://stackoverflow.com/q/51292058
tags question: http://stackoverflow.com/q/51251668
tags question: http://stackoverflow.com/q/51224948
tag name: mysql
tags question: http://stackoverflow.com/q/51179906
tags question: http://stackoverflow.com/q/51185664
tags question: http://stackoverflow.com/q/51315488
tags question: http://stackoverflow.com/q/51252470
tags question: http://stackoverflow.com/q/51199767
tags question: http://stackoverflow.com/q/51268587
tags question: http://stackoverflow.com/q/51261964
tags question: http://stackoverflow.com/q/51175841
tags question: http://stackoverflow.com/q/51235999
tags question: http://stackoverflow.com/q/51227351
tags question: http://stackoverflow.com/q/51252852
tags question: http://stackoverflow.com/q/51283475
tags question: http://stackoverflow.com/q/51236304
tags question: http://stackoverflow.com/q/51198019
tags question: http://stackoverflow.com/q/51202842
tags question: http://stackoverflow.com/q/51167985
type: Tag
tags question: http://stackoverflow.com/q/51226481
tags question: http://stackoverflow.com/q/51239428
tags question: http://stackoverflow.com/q/51169023
tags question: http://stackoverflow.com/q/51286264
tags question: http://stackoverflow.com/q/51176444
tags question: http://stackoverflow.com/q/51175581
tags question: http://stackoverflow.com/q/51187142
tags question: http://stackoverflow.com/q/51168661
tags question: http://stackoverflow.com/q/51231534
tags question: http://stackoverflow.com/q/51236787
tags question: http://stackoverflow.com/q/51296195
tags question: http://stackoverflow.com/q/51170918
tags question: http://stackoverflow.com/q/51283225
tags question: http://stackoverflow.com/q/51176000
tags question: http://stackoverflow.com/q/51251095
tags question: http://stackoverflow.com/q/51261700
tags question: http://stackoverflow.com/q/51269532
tags question: http://stackoverflow.com/q/51277801
tags question: http://stackoverflow.com/q/51294268
tags question: http://stackoverflow.com/q/51174140
tags question: http://stackoverflow.com/q/51202926

http://stackoverflow.com/comment/89408590
has text: An example of the returned data would be beneficial.
score: 0
comment on: http://stackoverflow.com/q/51213743
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51275756
type: AcceptedAnswer
has body: Just build a dict of lists: di={} for l0,l1 in zip(list_0,list_1): di.setdefault(l1[3],[]).append(l0) &gt;&gt;&gt; di {0: ['Have', 'we', 'all', 'had', 'lunch', 'yes'], 1: ['yes'], 2: ['not', 'yet']} For your specific output: &gt;&gt;&gt; '\n'.join("{}: {}".format(e, ", ".join(di[e])) for e in sorted(di)) 0: Have, we, all, had, lunch, yes 1: yes 2: not, yet
answers question: http://stackoverflow.com/q/51275578
has comment: http://stackoverflow.com/comment/89529598
type: Answer
accepted answer of: http://stackoverflow.com/q/51275578
upvote count: 4
downvote count: 0
has comment: http://stackoverflow.com/comment/89529833
has comment: http://stackoverflow.com/comment/89529397
score: 4

http://stackoverflow.com/comment/89581169
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51302030
score: 0
has text: And check your project for files and folders named `bluetooth` that would cause a name clash on import.

http://stackoverflow.com/a/51211873
has comment: http://stackoverflow.com/comment/89404947
has comment: http://stackoverflow.com/comment/89405094
type: Answer
has comment: http://stackoverflow.com/comment/89404761
has body: You just need to open for append: std::ofstream myfile; myfile.open("file.txt", std::ios_base::out | std::ios_base::app);
answers question: http://stackoverflow.com/q/51211758
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/89404847
accepted answer of: http://stackoverflow.com/q/51211758
has comment: http://stackoverflow.com/comment/89404920
upvote count: 1
type: AcceptedAnswer

http://stackoverflow.com/a/51291063
has comment: http://stackoverflow.com/comment/89559971
downvote count: 0
score: 7
has comment: http://stackoverflow.com/comment/89560238
answers question: http://stackoverflow.com/q/51290964
has body: Actually you can use post_mortem to access the traceback context import ipdb; ipdb.post_mortem() ipdb&gt; e ZeroDivisionError('division by zero',)
has comment: http://stackoverflow.com/comment/89560161
upvote count: 7
type: Answer

http://stackoverflow.com/comment/89470144
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51245311
has text: @MedAli With `pip freeze | grep scikit-learn` at the terminal, i got this `scikit-learn==0.19.1`.
type: Comment

http://stackoverflow.com/comment/89429387
comment on: http://stackoverflow.com/q/51212576
has text: code and explaination addded
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51189289
accepted answer: http://stackoverflow.com/a/51189350
type: AnsweredQuestion
has body: I have a dictionary which contains a dataframe for each key. The dictionary comes from this code: for city in a: forecast = api.get_forecast(city='city') b = pd.DataFrame(forecast.get_series(['temp','precip','clouds','weather'])) for lab,row in b.iterrows(): b.loc[lab,"Forecast"]=b.iloc[lab][4]['description'] b= b.drop(['weather'],axis=1) d[city]=b So that I have for each city the weather features for several time units. I would like to make a new dataframe containing all the keywords with an additional column for each key for all the keywords inside it. This step is necessary because I need to upload it to amazon redshift.
score: 1
upvote count: 1
type: Question
tagged with: dataframe
has answer: http://stackoverflow.com/a/51189350
tagged with: pandas
has title: How to create a DataFrame from a dictionary which contains DataFrames?
downvote count: 0
answer count: 1
tagged with: weather-api
favorite count: 0
tagged with: python
tagged with: dictionary

http://stackoverflow.com/q/51273000
score: 0
upvote count: 1
downvote count: 1
tagged with: scipy
accepted answer: http://stackoverflow.com/a/51273051
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89524557
type: Question
tagged with: numpy
answer count: 1
has title: solution for the flipping coin issue
favorite count: 0
has answer: http://stackoverflow.com/a/51273051
tagged with: coin-flipping
has comment: http://stackoverflow.com/comment/89524080
tagged with: python
has comment: http://stackoverflow.com/comment/89524073
has body: I am trying to solve this prolem : a random experiment of tossing a coin 10000 times and determine the count of Heads:: defining a binomial distribution with n = 1 and p = 0.5. using binom function from scipy.stats setting random seed to 1 Draw a sample of 10000 elements from defined distribution. Assume the values 0 and 1 represent Heads and Tails respectively. Counting the number of heads and display it by using 'bincount' method, the code snippet is : import scipy as sp from scipy import stats import numpy as np n, p = 1, .5 # number of trials, probability of each trial s = np.random.binomial(n, p, 1000) print(s) k = np.bincount(s) print(k[0]) print(k[1]) print(k.count(1)) Where it is going wrong? I need to find out the number of heads from bincount()

http://stackoverflow.com/q/51244309
tagged with: python
has title: Closing figure show vs. imshow
tagged with: python-3.x
upvote count: 0
has answer: http://stackoverflow.com/a/51244638
score: -3
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/21884271
tagged with: matplotlib
tagged with: figure
type: Question
answer count: 1
favorite count: 0
has body: Normally, I use following figure-closing pattern to prevent the error %matplotlib inline plt.figure() // plot here what necessary plt.show() // figure is displayed inline plt.close() Replacing show with imshow, within for in loop only 1 last figure is displayed. How to plot inline in loop with imshow, making sure that closing figures properly?
has comment: http://stackoverflow.com/comment/89467111
downvote count: 3
tagged with: inline
accepted answer: http://stackoverflow.com/a/51244638

http://stackoverflow.com/q/51289608
answer count: 2
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/51292055
has answer: http://stackoverflow.com/a/51289680
tagged with: python
possible better answer: http://stackoverflow.com/a/51292055
score: 2
upvote count: 2
has body: Say you have the following legacy model: class Foo(models.Model): bar_id = models.IntegerField(null=True, blank=True) # more fields bar_id is supposed to refer to a primary key from the Bar model, but for some reason, it's not registered as a foreign key. Now, how can I filter out all the Foos that do not have corresponding Bar objects?
tagged with: django
has title: Django - Check if a non-foreign-key integer field exists as a Primary Key to another Model?
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51289680
type: Question

http://stackoverflow.com/q/51222918
tagged with: python
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/51222947
possible better answer: http://stackoverflow.com/a/51222965
type: Question
has answer: http://stackoverflow.com/a/51222965
accepted answer: http://stackoverflow.com/a/51222947
answer count: 2
linked to: http://stackoverflow.com/q/18966564
has title: How do I get the list of third-party python packages that I have installed with pip?
tagged with: python-3.x
has body: I'm using Python 3.7 on Windows. I'm not looking for the packages which are shipped with Python. I just want the names of the 3rd party packages that I have manually installed using pip. Thanks.
tagged with: pip

multiprocess
tags question: http://stackoverflow.com/q/51263660
tag name: multiprocess
type: Tag
tags question: http://stackoverflow.com/q/51219136

http://stackoverflow.com/a/51264973
answers question: http://stackoverflow.com/q/51264680
has body: You need to create the figure with subplots at the start of the loop, then plot the graphs in the respective subplots: for m in range(num_plots): gs = gridspec.GridSpec(1, 2, width_ratios=[3, 1]) # create figure at start of loop img = matrixDistance[m] plt.subplot(gs[0]) # first subplot imgplot = plt.imshow(img) imgplot.set_cmap('PuBu') plt.colorbar() z += 20 esqueleto = movimento[:z,:2] x = esqueleto[:,0] y = -esqueleto[:,1] plt.subplot(gs[1]) # second subplot plt.scatter(x,y, s=50) plt.title('Esqueleto') plt.show()
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/51264680

http://stackoverflow.com/q/51189487
score: 6
has answer: http://stackoverflow.com/a/55752009
has answer: http://stackoverflow.com/a/59170977
has title: Django - post InMemoryUploadedFile to external REST api
type: Question
has comment: http://stackoverflow.com/comment/89360838
has answer: http://stackoverflow.com/a/79062911
answer count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/89365754
tagged with: django-rest-framework
favorite count: 0
has comment: http://stackoverflow.com/comment/89367364
type: UnansweredQuestion
has body: In the Django Rest Framework I would like to post a file, received as an InMemoryUploadedFile, to a different server as soon as it is received. It sounds simple, but the request.post() function does not seem to properly send over such a file : def post(self, request, *args, **kwargs): data = request.data print(data) # &lt;QueryDict: {'file': [&lt;InMemoryUploadedFile: myfile.pdf (application/pdf)&gt;]}&gt; endpoint = OTHER_API_URL + "/endpoint" r = requests.post(endpoint, files=data) My other server receives the request (through flask) with the name of the file, but not the content: @app.route("/endpoint", methods=["POST"]) def endpoint(): if flask.request.method == "POST": # I removed the many checks to simplify the code file = flask.request.files['file'] path = os.path.join(UPLOAD_FOLDER, file.filename) file.save(path) print(file) #&lt;FileStorage: u'file.pdf' (None)&gt; print(os.path.getsize(path)) #0 return [{"response":"ok"}] When posting a file directly to that api in form-data with postman, It works as expected: print(file) # &lt;FileStorage: u'file.pdf' ('application/pdf')&gt; print(os.path.getsize(path)) #8541 Any help on how to fix this, i.e. transform the InMemoryUploadedFile type in something a normal REST api can understand? Or maybe just adding the right headers?
tagged with: django
tagged with: python
upvote count: 6
has comment: http://stackoverflow.com/comment/89365059
has comment: http://stackoverflow.com/comment/89363855
has comment: http://stackoverflow.com/comment/89362961

http://stackoverflow.com/comment/135611174
type: AnswerComment
comment on: http://stackoverflow.com/a/51201819
score: 0
type: Comment
has text: FutureWarning: pyarrow.open_stream is deprecated as of 0.17.0, please use pyarrow.ipc.open_stream instead.

elastic-load-balancer
tags question: http://stackoverflow.com/q/51241012
tag name: elastic-load-balancer
type: Tag

http://stackoverflow.com/q/51261565
has title: Recommendation system to recommend similar companies
downvote count: 2
type: Question
upvote count: 0
score: -2
has answer: http://stackoverflow.com/a/51264751
has comment: http://stackoverflow.com/comment/89511328
answer count: 1
tagged with: recommendation-engine
favorite count: 0
type: UnansweredQuestion
tagged with: machine-learning
tagged with: python
has body: I am trying to build a recommendation system based on which industries they belong and what kind of work they do. eg. Microsoft, Apple and Google should show similar results, Tesla, General Motors, BMW should show similar results where can i find data for the following which gives me some description of the companies and also what industries they belong to.

http://stackoverflow.com/a/51443946
answers question: http://stackoverflow.com/q/51306666
has body: This problem can often be caused by the fact that the installed version is not the same as the version used in the project, or the differences in dependency sources. Please check the version of the hbase in your project.
score: 0
type: Answer

http://stackoverflow.com/q/51167542
type: Question
accepted answer: http://stackoverflow.com/a/51167774
has title: Tensorflow creating new variables despite reuse set to true
answer count: 2
downvote count: 0
tagged with: keras
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/51167774
score: 2
type: AnsweredQuestion
upvote count: 2
possible better answer: http://stackoverflow.com/a/51180807
has body: I am trying to build a basic RNN, but I get errors trying to use the network after training. I hold network architecture in a function inference def inference(inp): with tf.name_scope("inference"): layer = SimpleRNN(1, activation='sigmoid', return_sequences=False)(inp) layer = Dense(1)(layer) return layer but everytime i call it, another set of variables gets created despite using the same scope in training: def train(sess, seq_len=2, epochs=100): x_input, y_input = generate_data(seq_len) with tf.name_scope('train_input'): x = tf.placeholder(tf.float32, (None, seq_len, 1)) y = tf.placeholder(tf.float32, (None, 1)) with tf.variable_scope('RNN'): output = inference(x) with tf.name_scope('training'): loss = tf.losses.mean_squared_error(labels=y, predictions=output) train_op = tf.train.RMSPropOptimizer(learning_rate=0.1).minimize(loss=loss, global_step=tf.train.get_global_step()) with sess.as_default(): sess.run([tf.global_variables_initializer(), tf.local_variables_initializer()]) for i in tqdm.trange(epochs): ls, res, _ = sess.run([loss, output, train_op], feed_dict={x:x_input, y:y_input}) if i%100==0: print(f'{ls}: {res[10]} - {y_input[10]}') x_input, y_input = generate_data(seq_len) and prediction: def predict_signal(sess, x, seq_len): # Preparing signal (omitted) # Predict inp = tf.convert_to_tensor(prepared_signal, tf.float32) with sess.as_default(): with tf.variable_scope('RNN', reuse=True) as scope: output = inference(inp) result = output.eval() return result I have spent couple of hours reading about variables scopes by now, but on running prediction I still get an error Attempting to use uninitialized value RNN_1/inference/simple_rnn_2/kernel, with the number by RNN_1 increasing with each call
has answer: http://stackoverflow.com/a/51180807
linked to: http://stackoverflow.com/q/57396482
tagged with: tensorflow

http://stackoverflow.com/q/51296260
type: UnansweredQuestion
type: Question
has title: Numpy Array of Strings Has Both Strings And Arrays
has comment: http://stackoverflow.com/comment/89570680
tagged with: numpy
score: 0
has answer: http://stackoverflow.com/a/51296395
answer count: 1
tagged with: python
tagged with: python-3.x
has body: I created an array like this: current_pop = np.full(N, "W", dtype = object) and iterated over current_pop with for loop for i in np.arange(0, len(current_pop)): when I print(current_pop[i]) I mostly get "W" but occasionally ["W"] and it's screwing up my program. Full code here: #Table populations_index = { 'W' : 0, 'A' : 0, 'B' : 0, 'C' : 0 } #initialize our population of 100 N = 100 current_pop = np.full(N, "W", dtype = object) #create our probabiliy vector mutant_prob_dictionary = { "A" : 0.01, "B" : 0.015, "C" : 0.018 } trials = np.arange(0, 501, 1) for t in trials: #every time I need to refresh prob and mutant list mutant_p = [mutant_prob_dictionary['A'], mutant_prob_dictionary['B'],mutant_prob_dictionary['C']] mutant = ['A','B','C'] assert(len(mutant) == 3) #run through each cell for i in np.arange(0, len(current_pop)): #ERROR HERE: assert(type(current_pop[i]) == str) if current_pop[i][0] == "W": wild_prob = 1 - np.sum(mutant_p) mutant_p.append(wild_prob) #add wild prob at the end prob_vector = mutant_p mutant.append('W') #add wild self to end species_vector = mutant assert(np.sum(prob_vector) == 1) else: #must be mutant mutant_p.remove(mutant_prob_dictionary[current_pop[i][0]]) #remove its prob mutant.remove(current_pop[i][0]) #remove itself own_prob = 1 - np.sum(mutant_p) mutant_p.append(own_prob) #add its prob at the end mutant.append(current_pop[i][0]) #add itself at the end prob_vector = mutant_p species_vector = mutant #Now I have a probability vector and a species vector #draw a cell based off the mutation prob new_cell = np.random.choice(species_vector, size = 1, p = prob_vector) print(current_pop[i]) current_pop[i] = new_cell for s in list(populations_index): #iterate for each species populations_index[s] = list(current_pop).count(s) #adds the population count of that species

http://stackoverflow.com/q/51298477
score: 0
has answer: http://stackoverflow.com/a/56606947
accepted answer: http://stackoverflow.com/a/56606947
has comment: http://stackoverflow.com/comment/89841307
answer count: 1
tagged with: sql-server
tagged with: snowflake-cloud-data-platform
tagged with: python
has body: I am getting below error query = command % processed_params TypeError: not all arguments converted during string formatting I am trying to pull data from SQL server and then inserting it into Snowflake my below code import pyodbc import sqlalchemy import snowflake.connector driver = 'SQL Server' server = 'tanmay' db1 = 'testing' tcon = 'no' uname = 'sa' pword = '123' cnxn = pyodbc.connect(driver='{SQL Server}', host=server, database=db1, trusted_connection=tcon, user=uname, password=pword) cursor = cnxn.cursor() cursor.execute("select * from Admin_tbldbbackupdetails") rows = cursor.fetchall() #for row in rows: # #data = [(row[0], row[1],row[2], row[3],row[4], row[5],row[6], row[7])] print (rows[0]) cnxn.commit() cnxn.close() connection = snowflake.connector.connect(user='****',password='****',account='*****') cursor2 = connection.cursor() cursor2.execute("USE WAREHOUSE FOOD_WH") cursor2.execute("USE DATABASE Test") sql1="INSERT INTO CN_RND.Admin_tbldbbackupdetails_ip" "(id,dbname, dbpath, backupdate, backuptime, backupStatus, FaildMsg, Backupsource)" "values (?,?,?,?,?,?,?,?)" cursor2.execute(sql1,*rows[0])
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89655913
has comment: http://stackoverflow.com/comment/89826795
has comment: http://stackoverflow.com/comment/89683904
type: Question
has title: Getting error on python while transferring data from SQL server to snowflake
has comment: http://stackoverflow.com/comment/89861910

http://stackoverflow.com/q/51226450
tagged with: classification
tagged with: machine-learning
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51226779
type: Question
score: 0
upvote count: 1
answer count: 1
downvote count: 1
has title: Classifiers on floating point numbers
has body: I have dataset with 1 feature and N samples. I am trying to predict the below "target" column from "feature" column. All ​of the values are floating point numbers between 1 and 4: e.g 1.2, 2.2, etc target feature 0.0 0.0 6.0 8.0 7.2 1.0 2.3 2.0 1.1 5.0 5.0 1.0 0.0 0.0 0.0 1.0 0.0 0.0 I am working with scikit-learn. Error I am getting is (with either a DecisionTreeClassifier, or RandomForest): ValueError("Unknown label type: %r" % y_type) ValueError: Unknown label type: 'continuous' I am unable to get any classifier to work on this data, unless I convert them to strings or integers.​ However, I need to be able to predict the​se​ decimal points​, so that is not an option. ​I am a beginner at machine learning, and want to make sure that I am not making any stupid mistakes in the process. First off: is it correct to convert these floats to strings and simply run a classifier on those strings? (e.g, randomforest... ) What would be the caveats for this method? What are some classifie​rs that I can run on floats? Should I instead be using regressors? ​Thanks!​
favorite count: 0
has comment: http://stackoverflow.com/comment/89433549
tagged with: python
has comment: http://stackoverflow.com/comment/89433004
accepted answer: http://stackoverflow.com/a/51226779

http://stackoverflow.com/a/51257687
score: 0
has body: I'd suggest that you start off by reading up on unsupervised learning, specially clustering using K-means and it's applications/concepts in general, not just for images. I'll comment each line of this code to explain what is happening. from matplotlib.image import imread #import module image = imread(os.path.join("images","unsupervised_learning","ladybug.png")) #Read Image image.shape #Get shape of image, which is height, width and channel(colours) X = image.reshape(-1, 3) #Reshaping to get color channel first kmeans = KMeans(n_clusters=8, random_state=42).fit(X) #Applying and fitting K-means clustering segmented_img = kmeans.cluster_centers_[kmeans.labels_] #centres of the 8 clusters made segmented_img = segmented_img.reshape(image.shape) #reshape them using the changed image shape segmented_imgs = [] n_colors = (10, 8, 6, 4, 2) for n_clusters in n_colors: kmeans = KMeans(n_clusters=n_clusters, random_state=42).fit(X) #Applyting kmeans for each colour, using 10,8,6.... as number of clusters segmented_img = kmeans.cluster_centers_[kmeans.labels_] #Repeating as mentioned above segmented_imgs.append(segmented_img.reshape(image.shape)) plt.figure(figsize=(10,5)) #Plotting code plt.subplots_adjust(wspace=0.05, hspace=0.1) plt.subplot(231) plt.imshow(image) plt.title("Original image") plt.axis('off') for idx, n_clusters in enumerate(n_colors): plt.subplot(232 + idx) plt.imshow(segmented_imgs[idx]) plt.title("{} colors".format(n_clusters)) plt.axis('off') plt.show() In this line of code, segmented_img = kmeans.cluster_centers_[kmeans.labels_] As the names suggest, cluster_centers_ is an array attribute that returns the coordinates of the cluster centers and labels_ is an attribute that returns the Labels of each point. Hence segmented_img contains the cluster centre coordinates of the labels of each point. points.
type: Answer
answers question: http://stackoverflow.com/q/51245877

http://stackoverflow.com/comment/92276856
comment on: http://stackoverflow.com/q/51269269
score: 0
type: Comment
has text: Thank you for the informations :)
type: QuestionComment

http://stackoverflow.com/q/51311521
upvote count: 4
accepted answer: http://stackoverflow.com/a/51312676
has body: I'm working on a project where I need to embed some python code in C++. I've been trying Cython for a while, but I still have a lot of questions. Here's a demo that I have tried. Here I have a couple files with struct and functions: First, this is file cat.pyx cdef public struct Cat: int num cdef public setCatNum(Cat* cat): cat.num = 100 cdef public int getCatNum(Cat* cat): return cat.num And its .pxd file cat.pxd: cdef public struct Cat: int num cdef public setCatNum(Cat* ) cdef public int getCatNum(Cat* ) And this is my setup.py: from distutils.extension import Extension from Cython.Distutils import build_ext ext_modules = [ Extension("cat", ["cat.pyx"], include_dirs=['.']), ] setup( name='dotest', cmdclass={'build_ext': build_ext}, ext_modules=ext_modules, script_args=['build_ext'], options={'build_ext':{'inplace':True, 'force':True}} ) It could compile correctly, but in the generated cat.h file, the function declarations are something else: __PYX_EXTERN_C PyObject *__pyx_f_3cat_setCatNum(struct Cat *); __PYX_EXTERN_C int __pyx_f_3cat_getCatNum(struct Cat *); So how could I call those functions in my C/C++ program? Thank you in advance.
favorite count: 0
tagged with: python-3.x
has title: Call Cython (Python3.6) in C++ Program
tagged with: python
has answer: http://stackoverflow.com/a/51312676
has comment: http://stackoverflow.com/comment/89601561
linked to: http://stackoverflow.com/q/22589868
tagged with: c++
type: AnsweredQuestion
score: 1
tagged with: cython
type: Question
has answer: http://stackoverflow.com/a/51311567
answer count: 2
has comment: http://stackoverflow.com/comment/89600939
tagged with: http://stackoverflow.com/tag/c
possible better answer: http://stackoverflow.com/a/51311567
downvote count: 3

http://stackoverflow.com/comment/89539233
type: QuestionComment
comment on: http://stackoverflow.com/q/51280942
has text: Why don't you read this small file only once and keep it in memory?
score: 0
type: Comment

http://stackoverflow.com/q/51172092
has answer: http://stackoverflow.com/a/52974603
score: 0
tagged with: python
type: UnansweredQuestion
tagged with: suds
has title: AXL Python getLine using pattern instead of uuid does not work (CUCM 11.5)
tagged with: cucm
type: Question
has body: I'm struggling with getting for example line info via getLine using pattern instead of uuid. According to getLine AXL schema for CUCM 11.5 it should be possible to choose either uuid or pattern as lookup criteria. The python (2.7) module that I'm using is suds-jurko 0.6. Base code is as follows: from suds.client import Client import ssl wsdl = 'file:///C:/Users/xyz/Documents/axlplugin/schema/current/AXLAPI.wsdl' location = 'https://10.10.20.1/axl/' username = '***' password = '***' ssl._create_default_https_context = ssl._create_unverified_context client = Client(wsdl, location=location, username=username, password=password) First of all, the proof that the pattern I want to use as a lookup string for getLine actually exists: &gt;&gt;&gt; line2 = client.service.listLine({'pattern': '1018'}, returnedTags={'description': ''}) &gt;&gt;&gt; line2 (reply){ return = (return){ line[] = (LLine){ _uuid = "{1EC56035-6B5D-283A-4DF0-EFEFA01FCEFF}" description = None }, } } Then, I try getLine using uuid which works well: &gt;&gt;&gt; line5 = client.service.getLine('1EC56035-6B5D-283A-4DF0-EFEFA01FCEFF') &gt;&gt;&gt; line5 (reply){ return = (return){ line = (RLine){ _uuid = "{1EC56035-6B5D-283A-4DF0-EFEFA01FCEFF}" pattern = "1018" description = None usage = "Device" routePartitionName = "" aarNeighborhoodName = "" ----Rest omitted for brevity--- Now, if I try to use pattern, not uuid, I have following error: line6 = client.service.getLine({'pattern': '1018'}, {'routePartitionName': ''}) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "C:\Python27\lib\site-packages\suds\client.py", line 521, in __call__ return client.invoke(args, kwargs) File "C:\Python27\lib\site-packages\suds\client.py", line 576, in invoke soapenv = binding.get_message(self.method, args, kwargs) File "C:\Python27\lib\site-packages\suds\bindings\binding.py", line 109, in get_message content = self.bodycontent(method, args, kwargs) File "C:\Python27\lib\site-packages\suds\…
answer count: 1

http://stackoverflow.com/q/51205824
has answer: http://stackoverflow.com/a/51206106
score: 0
tagged with: matrix
answer count: 1
accepted answer: http://stackoverflow.com/a/51206106
tagged with: python
type: AnsweredQuestion
has title: Making a line in a matrix go up (Python) - issue with Append that replace instead of Appending item
type: Question
has body: I want to make an "animation" of an element of matrix going from the bottom line to the top ligne of the matrix. I have the following code, but something not wanted is ongoing with append function : import time #size of the matrix PixelCarac=4 #List that cointain all the matrixs ListMatrix=[] #matrix filled with 0 tempo =[[0 for x in range(PixelCarac)] for y in range(PixelCarac)] #last line have a difference tempo[3][0]=1 print("First step") print(tempo) #making the line going up. for x in range(0,PixelCarac-1,1): #append in the list ListMatrix.append(tempo) #display print("length of the list is " + str(len(ListMatrix))) for elem in ListMatrix: print(elem) #Making the line going up by recopie from 1 line to the upper one for i in range(0,len(tempo)-1,1): tempo[i]=tempo[i+1] time.sleep(20) the ouput I have is : First step [[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,1] length of the list is 1 [[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,1] length of the list is 2 [[0,0,0,0],[0,0,0,0],[0,0,0,1],[0,0,0,1] [[0,0,0,0],[0,0,0,0],[0,0,0,1],[0,0,0,1] length of the list is 2 [[0,0,0,0],[0,0,0,1],[0,0,0,1],[0,0,0,1] [[0,0,0,0],[0,0,0,1],[0,0,0,1],[0,0,0,1] [[0,0,0,0],[0,0,0,1],[0,0,0,1],[0,0,0,1] the ouput I want is : First step [[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,1] length of the list is 1 [[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,1] length of the list is 2 [[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,1] [[0,0,0,0],[0,0,0,0],[0,0,0,1],[0,0,0,1] length of the list is 2 [[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,1] [[0,0,0,0],[0,0,0,0],[0,0,0,1],[0,0,0,1] [[0,0,0,0],[0,0,0,1],[0,0,0,1],[0,0,0,1] Question : Why the append function is changing the previous items in the list?
tagged with: arrays

http://stackoverflow.com/q/51186217
tagged with: alpine-linux
has body: I'm building an Alpine Docker image for deploying Python web applications. The image I use contains Alpine-3.7, Python-3.6.5 and Apache2.4 with mod_wsgi4.6.4 (downloaded from pip3). Whenever I try to start my apache2 server, I get the following errors: [Thu Jul 05 09:56:16.257991 2018] [so:debug] [pid 97] mod_so.c(266): AH01575: loaded module authn_file_module from /var/www/modules/mod_authn_file.so [Thu Jul 05 09:56:16.258274 2018] [so:debug] [pid 97] mod_so.c(266): AH01575: loaded module authn_core_module from /var/www/modules/mod_authn_core.so [Thu Jul 05 09:56:16.258385 2018] [so:debug] [pid 97] mod_so.c(266): AH01575: loaded module authz_host_module from /var/www/modules/mod_authz_host.so [Thu Jul 05 09:56:16.258486 2018] [so:debug] [pid 97] mod_so.c(266): AH01575: loaded module authz_groupfile_module from /var/www/modules/mod_authz_groupfile.so [Thu Jul 05 09:56:16.258701 2018] [so:debug] [pid 97] mod_so.c(266): AH01575: loaded module authz_user_module from /var/www/modules/mod_authz_user.so [Thu Jul 05 09:56:16.258805 2018] [so:debug] [pid 97] mod_so.c(266): AH01575: loaded module authz_core_module from /var/www/modules/mod_authz_core.so [Thu Jul 05 09:56:16.258888 2018] [so:debug] [pid 97] mod_so.c(266): AH01575: loaded module access_compat_module from /var/www/modules/mod_access_compat.so [Thu Jul 05 09:56:16.258981 2018] [so:debug] [pid 97] mod_so.c(266): AH01575: loaded module auth_basic_module from /var/www/modules/mod_auth_basic.so [Thu Jul 05 09:56:16.259478 2018] [so:debug] [pid 97] mod_so.c(266): AH01575: loaded module reqtimeout_module from /var/www/modules/mod_reqtimeout.so [Thu Jul 05 09:56:16.259660 2018] [so:debug] [pid 97] mod_so.c(266): AH01575: loaded module filter_module from /var/www/modules/mod_filter.so [Thu Jul 05 09:56:16.259768 2018] [so:debug] [pid 97] mod_so.c(266): AH01575: loaded module mime_module from /var/www/modules/mod_mime.so [Thu Jul 05 09:56:16.260283 2018] [so:debug] [pid 97] mod_so.c(266): AH01575: loaded module log_confi…
type: Question
accepted answer: http://stackoverflow.com/a/51189996
has title: Mod_Wsgi missing symbol
score: 0
has answer: http://stackoverflow.com/a/51189996
tagged with: apache
answer count: 1
tagged with: python
type: AnsweredQuestion
tagged with: mod-wsgi

http://stackoverflow.com/a/51285302
has body: Following Django tutorials on main page you probabily will have this structure, keep in mind some paths is required since overrides django framework like static, migrations, templates... but about your application you can make some changes but you will have to handle it manualy mysite/ manage.py mysite/ __init__.py settings.py urls.py wsgi.py polls/ __init__.py admin.py migrations/ __init__.py 0001_initial.py models.py static/ polls/ images/ background.gif style.css templates/ polls/ detail.html index.html results.html tests.py urls.py views.py templates/ admin/ base_site.html https://docs.djangoproject.com/en/2.0/intro/reusable-apps/
answers question: http://stackoverflow.com/q/51282539
type: Answer
downvote count: 1
score: -1
upvote count: 0

http://stackoverflow.com/a/51252988
has comment: http://stackoverflow.com/comment/89488072
has body: First thing: to take the contents of each CSV and concatenate into one huge CSV is simple enough, you do not need pandas or anything else for that (or even python) outfile = open('outpath.csv', 'w') for files_gz in files: with gzip.open(os.path.join(subdir, files_gz)) as f: for line in f: outfile.write(line) outfile.close() (you may want to ignore the first line of each CSV, if it has a header with column names). To do processing on the data is harder. The reason is, that although Dask can read all the files and work on the set as a single data-frame, if any file results in more memory than your system can handle, processing will fail. This is because random-access doesn't mix with gzip compression. The output file, however, is (presumably) uncompressed, so you can do: import dask.dataframe as dd df = dd.read_csv('outpath.csv') # automatically chunks input df[filter].groupby(fields).mean().compute() Here, only the reference to dd and the .compute() are specific to dask.
type: Answer
has comment: http://stackoverflow.com/comment/89488433
score: 1
has comment: http://stackoverflow.com/comment/89487681
accepted answer of: http://stackoverflow.com/q/51243386
answers question: http://stackoverflow.com/q/51243386
downvote count: 0
upvote count: 1
type: AcceptedAnswer

http://stackoverflow.com/comment/89427517
type: Comment
type: QuestionComment
has text: if am using int('-jj',20) am getting 399. which is true!! But i want it in reverse that is I want to convert 399 to the equivalent number in base 20
score: 0
comment on: http://stackoverflow.com/q/51223527

http://stackoverflow.com/a/51228185
upvote count: 4
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/89436335
has body: You can't directly do this in Python any more than you can in C++. But you can indirectly do it in Python the exact same way you can in C++: by writing an object that holds onto both lists and dispatches appropriately. For example: class TwoLists(collections.abc.Sequence): def __init__(self, a, b): self.a, self.b = a, b def __len__(self): return len(self.a) + len(self.b) def __getitem__(self, idx): # cheating a bit, not handling slices or negative indexing if idx &lt; len(self.a): return self.a[idx] else: return self.b[idx - len(self.a)] Now: &gt;&gt;&gt; first_list = [1,2,3] &gt;&gt;&gt; second_list = [5,6] &gt;&gt;&gt; two_lists = TwoLists(first_list, second_list) &gt;&gt;&gt; print(*two_lists) 1 2 3 5 6 &gt;&gt;&gt; first_list.append(4) &gt;&gt;&gt; print(*two_lists) 1 2 3 4 5 6 What I think you were missing here is a fundamental distinction between Python and C++ in how variables work. Briefly, every Python variable (and attribute and list position and so on) is, in C++ terms, a reference variable. Less misleadingly: C++ variables (and attributes, etc.) are memory locations—they're where values live. If you want a to be a reference to the value in b, you have to make a reference-to-b value, and store that in a. (C++ has a bit of magic that lets you define a reference variable like int&amp; a = b, but you can't later reassign a to refer to c; if you want that, you have to explicitly use pointers, C-style.) Python variables (and etc.) are names for values, while the values live wherever they want to. If you want a to be a reference to the value in a, you just bind a to the same value b is bound to: a = b. (And, unlike C++, you can reassign a = c at any time.) Of course the cost is performance: there's an extra indirection to reach any value from its name in Python, while in C++, that only happens when you use pointer variables. But that cost is pretty much always invisible compared to the other overhead of Python (interpreting bytecode and dynamically looking name…
type: Answer
score: 4
accepted answer of: http://stackoverflow.com/q/51228164
answers question: http://stackoverflow.com/q/51228164

http://stackoverflow.com/comment/89369532
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51193969
has text: do you think `login_method is NOT equal to resend` ?
score: 0

http://stackoverflow.com/comment/89405441
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51208252
has text: So if you really want to improve on pandas, check the brilliant [Modern Pandas](https://tomaugspurger.github.io/modern-1-intro.html) blog series.

wifi
tag name: wifi
type: Tag
tags question: http://stackoverflow.com/q/51237841

http://stackoverflow.com/q/51187933
favorite count: 0
accepted answer: http://stackoverflow.com/a/51188441
tagged with: python
has body: In a rather complex python-selenium test script (which is not accessible from the outside, so I cannot provide an example), I have the following line waiting for an element to become visible: WebDriverWait(basedriver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.ID,"clb-iframe-workspace"))) elem = WebDriverWait(basedriver, 20).\ until(EC.element_to_be_clickable((By.XPATH, '//div[contains(text(), "Feature extraction")]'))) In most cases there is no problem and the web driver finds the element in question. But sometimes (about 1 in 10 cases) I get the following error: WebDriverException: Message: TypeError: can't access dead object And strangely that happens right away! Selenium does not even bother to wait the 20 seconds I want selenium to wait by using WebDriverWait! Maybe the iframe switch could have something to do with it? I also tried to make a screenshot just before the failing line - I get a blank white screen in both cases. So how to debug this any further myself? And why does the WebDriverWait not wait...? Addendum I have implemented the suggestion from DebanjanB, but I still get the same error at a level of 5%. If I use a slower internet connection, the error takes place almost all the time! When I insert code to take screenshots and write out the page source (which takes some time to do), the error rate decreases again. So I would say its definitive a timing issue, combined with a bug in selenium...
tagged with: selenium-webdriver
has comment: http://stackoverflow.com/comment/89357882
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89366329
downvote count: 0
has answer: http://stackoverflow.com/a/51188441
tagged with: selenium
has comment: http://stackoverflow.com/comment/89358182
type: Question
has title: WebDriverException: Message: TypeError: can't access dead object
linked to: http://stackoverflow.com/q/47811895
upvote count: 2
has comment: http://stackoverflow.com/comment/89358144
answer count: 1
has comment: http://stackoverflow.com/comment/89357784

http://stackoverflow.com/comment/89392460
type: AnswerComment
has text: @AlexTuna as I said, the code outside the function runs once for each process. Your code overwrites the file every time a new process is created
type: Comment
score: 0
comment on: http://stackoverflow.com/a/51199800

http://stackoverflow.com/a/51185106
has comment: http://stackoverflow.com/comment/89353058
upvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/89352905
answers question: http://stackoverflow.com/q/51184734
has comment: http://stackoverflow.com/comment/89353237
downvote count: 0
has body: I would rather keep it simple and use the below: book_dict = {"Book1" : {7:1,4:2}, "Book2" : {5:1,9:1,3:2,2:1}} for k,v in book_dict.items(): print (k, v) book_dict["Book1"][7] = book_dict["Book1"][7]+1 print (book_dict["Book1"]) book_dict["Book1"][8] = 1 print (book_dict["Book1"]) Result: Book1 {7: 1, 4: 2} Book2 {5: 1, 9: 1, 3: 2, 2: 1} {7: 2, 4: 2} {7: 2, 4: 2, 8: 1}
has comment: http://stackoverflow.com/comment/89352612
score: 1

http://stackoverflow.com/a/51211267
type: Answer
score: 1
has body: Only sorted is a function - list.sort is a method of the list type. Functions such as sorted are applicable to more than a specific type. For example, you can get a sorted list, set, or even a temporary generator. Only the output is concrete (you always get a new list) but not the input. Methods such as sort are applicable only to the type that holds them. For example, there is a list.sort method but not a dict.sort method. Even for types whose methods have the same name, switching them is not sensible - for example, set.copy cannot be used to copy a dict. An easy way to distinguish the two is that functions live in regular namespaces, such as modules. On the other hand, methods only live inside classes and their instances. sorted # function list.sort # method import math math.sqrt # function math.pi.as_integer_ratio # method Conventionally, Python usually uses functions for immutable actions and methods for mutating actions. For example, sorted provides a new sorted list leaving the old one untouched; my_list.sort() sorts the existing list, providing no new one. my_list = [4, 2, 3, 1] print(sorted(my_list)) # prints [1, 2, 3, 4] print(my_list) # prints [4, 2, 3, 1] - unchanged by sorted print(my_list.sort()) # prints None - no new list produced print(my_list) # prints [1, 2, 3, 4] - changed by sort
accepted answer of: http://stackoverflow.com/q/51210887
answers question: http://stackoverflow.com/q/51210887
upvote count: 1
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/89399715
has text: thanks so much for the response. I'm such a goof for overlooking the python version. When it was working, I had logged into my container and done a `python -V` and it came up with 3.6.6. Anyway, I tried your suggestion of installing jira from git but ran into the following error while building...`Could not find a version that satisfies the requirement jira==2.0.0.dev20`. Is there any other way to get around this? Can I install an older version? Or, can I peg my python version to 3.6.x? Just exploring my options in case the jira fix doesn't come out for a while.
comment on: http://stackoverflow.com/a/51202320
type: AnswerComment
type: Comment
score: 0

http://stackoverflow.com/comment/89507596
score: 1
comment on: http://stackoverflow.com/q/51264665
has text: If you're certain the arguments will always be booleans, `x |= y` is functionally identical to your proposed `x =or y` statement.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/72957789
type: Answer
score: 0
answers question: http://stackoverflow.com/q/51293632
has body: i'm quoting the comment of Kiran Subbaraman, just with addition of the exact keyword (otherwise, whole months will be returned even if ranges fall beyond the start or the end). #!pip install arrow from arrow import Arrow Arrow.span_range('month', start, end, exact=True)

http://stackoverflow.com/a/51385600
accepted answer of: http://stackoverflow.com/q/51320665
upvote count: 1
answers question: http://stackoverflow.com/q/51320665
type: Answer
downvote count: 0
score: 1
has body: So after a bit of trial an error and help from @Ponkadoodle I got it work. It worked for two recordings I had done on the same computer using quicktime and a online wav-converter. If I used wav-files from the internet the end sample sounded really messed up, I do not know if this is due to frequency etc. Here is the final code import wave import array w1 = wave.open("path/to/file/audiofile1.wav") w2 = wave.open("path/to/file/audiofile2.wav") #get samples formatted as a string. samples1 = w1.readframes(w1.getnframes()) samples2 = w2.readframes(w2.getnframes()) #takes every 2 bytes and groups them together as 1 sample. ("123456" -&gt; ["12", "34", "56"]) samples1 = [samples1[i:i+2] for i in range(0, len(samples1), 2)] samples2 = [samples2[i:i+2] for i in range(0, len(samples2), 2)] #convert samples from strings to ints def bin_to_int(bin): as_int = 0 for char in bin[::-1]: #iterate over each char in reverse (because little-endian) #get the integer value of char and assign to the lowest byte of as_int, shifting the rest up as_int &lt;&lt;= 8 as_int += char return as_int samples1 = [bin_to_int(s) for s in samples1] #['\x04\x08'] -&gt; [0x0804] samples2 = [bin_to_int(s) for s in samples2] #average the samples: samples_avg = [(s1+s2) for (s1, s2) in zip(samples1, samples2)] samples_array = array.array('i') samples_array.fromlist(samples_avg) wave_out = wave.open ("out.wav", "wb") wave_out.setnchannels(1) wave_out.setsampwidth(2) wave_out.setframerate(w1.getframerate()*4) wave_out.writeframes(samples_array) I still have an issue with setframerate(). I multiplied it by 4 and it worked, again this might depend on the frequency/framerate etc. of your original recording. wave_out.setframerate(w1.getframerate()*4)
type: AcceptedAnswer

http://stackoverflow.com/a/54108528
has comment: http://stackoverflow.com/comment/107036206
accepted answer of: http://stackoverflow.com/q/51213730
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51213730
has body: I just went through a similar issue myself and had a 'good' time debugging it. Here is my related post. Your question gives no discrete insight, as to how you installed your cv2 python module. In case you used pip to get the package, you can't enable gstreamer for the package. That is because pip only deploys pre-built binaries of the cv2 package and none of them support gstreamer. What you would need to do (it is indeed fairly easy) is, follow these instructions to build OpenCV from the source distribution. Beware not to make the same mistake I did. When configuring the build using cmake or ccmake, make sure to only set WITH_GSTREAMER to ON. Make sure WITH_GSTREAMER_0_10 is set OFF. Also, before you do the installation from source, make sure to whipe all existing binaries. For pip installations of cv2 that is going to mean something like: pip unistall opencv-python In case you already built binaries from the opencv source, you'll have to: sudo make uninstall from the &lt;opencv-src&gt;/build folder. Then go ahead and give it another go.
type: Answer
upvote count: 3
score: 3
has comment: http://stackoverflow.com/comment/95094867

http://stackoverflow.com/comment/89478350
comment on: http://stackoverflow.com/q/51248810
has text: You should check if you have, for whatever reasons, `np.nan` or `0`-only columns in `X_std`, I believe. Besides that, I would need to provide some data showing the issue, if you want other people to actually being able to solve the problem,
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89598991
comment on: http://stackoverflow.com/a/51308337
has text: Thanks for advise. Could you explain it a bit? What is the difference between **df.values** and **df.values[:,None]**. Whats does **None** do here?
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/89386403
comment on: http://stackoverflow.com/q/51202437
type: QuestionComment
type: Comment
has text: That is not a typo, The purpose of that is `detect_collide` requires two players to be compared for collisions.
score: 0

http://stackoverflow.com/q/51193459
tagged with: dataframe
score: 0
answer count: 2
tagged with: pandas
favorite count: 0
has answer: http://stackoverflow.com/a/51193534
upvote count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/51193534
possible better answer: http://stackoverflow.com/a/51194897
type: AnsweredQuestion
has title: Convert a Column to Column Header
downvote count: 1
has body: I have a list of dict containing x and y. I want to make x the index and y the column headers. How can I do it? import pandas pt1 = {"x": 0, "y": 1, "val": 3,} pt2 = {"x": 0, "y": 2, "val": 6,} lst = [pt1, pt2] print(lst) # [{'x': 0, 'y': 1, 'val': 3}, {'x': 0, 'y': 2, 'val': 6}] df = pandas.DataFrame(lst) print(df) # val x y # 0 3 0 1 # 1 6 0 2 How can I convert df to this format? # 1 2 # 0 3 6
has answer: http://stackoverflow.com/a/51194897
type: Question

http://stackoverflow.com/comment/89360513
type: Comment
has text: Yeah, but you wanted to just count a row that contains just 1 `-`. Unless you need to match any type of dashes, like in the `Pd` Unicode class, you can safely use `.contains('-')`
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51189048

http://stackoverflow.com/q/51222105
duplicate of: http://stackoverflow.com/q/22743548
has answer: http://stackoverflow.com/a/58514930
has title: Python script not working in crontab, but working when called otherwise
answer count: 2
downvote count: 0
favorite count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89425080
score: 2
type: Question
has body: I have a python script to take snapshots of the volumes of all running instances in AWS. The script is not working in crontab but it will will work when called otherwise. I've written the output of the cronjob to a file and this is the output: Traceback (most recent call last): File "completeBackUp2.py", line 2, in &lt;module&gt; import boto3 ImportError: No module named boto3 boto3 is installed and as previously mentioned, the script would work fine when called otherwise. This is what my crontab looks like: 0 1 * * * /usr/bin/python /opt/scripts/backup/completeBackUp2.py &gt; /opt/scripts/backup/output 2&gt;&amp;1
linked to: http://stackoverflow.com/q/22743548
has answer: http://stackoverflow.com/a/51222162
tagged with: ubuntu-16.04
tagged with: amazon-web-services

http://stackoverflow.com/q/51247761
has body: I am getting an error : "XMLSyntaxError: Premature end of data in tag _io.TextIOWrapper line 1, line 1, column 119" and I don't understand why... I checked my XML file for any left open brackets but nothing... Ideas? Thanks a lot ! <Materials_database> </Materials_database> Python code: with open(os.getcwd() + '\\materials.xml', "r" , encoding="utf-8") as dtfile: temp, start, stop = f.Get_MaterialDatabase(str(dtfile), matName) Function: def Get_MaterialDatabase(xml, MaterialName): Motor = objectify.fromstring(xml) for mat in Motor.Material_database.iterchildren(): xmlMat = mat.get("name") print (xmlMat) if xmlMat == MaterialName: temp = mat.CurveProperties.get("Temperature") start = mat.CurveProperties.get("Start") stop = mat.CurveProperties.get("Stop") return temp, start, stop
type: Question
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51249175
score: 0
tagged with: syntax-error
tagged with: xml-parsing
answer count: 1
has answer: http://stackoverflow.com/a/51249175
has title: XMLSyntaxError: Premature end of data in tag _io.TextIOWrapper - Python
tagged with: python

javascript
tags question: http://stackoverflow.com/q/51254518
tags question: http://stackoverflow.com/q/51298207
tags question: http://stackoverflow.com/q/51303550
tags question: http://stackoverflow.com/q/51322551
tags question: http://stackoverflow.com/q/51199996
tags question: http://stackoverflow.com/q/51266008
tags question: http://stackoverflow.com/q/51176193
tags question: http://stackoverflow.com/q/51285561
tags question: http://stackoverflow.com/q/51219641
tags question: http://stackoverflow.com/q/51234876
tags question: http://stackoverflow.com/q/51215137
tags question: http://stackoverflow.com/q/51323651
tags question: http://stackoverflow.com/q/51311365
tag name: javascript
tags question: http://stackoverflow.com/q/51284879
tags question: http://stackoverflow.com/q/51313850
tags question: http://stackoverflow.com/q/51287084
tags question: http://stackoverflow.com/q/51300744
tags question: http://stackoverflow.com/q/51201107
tags question: http://stackoverflow.com/q/51256657
type: Tag
tags question: http://stackoverflow.com/q/51197551
tags question: http://stackoverflow.com/q/51306375
tags question: http://stackoverflow.com/q/51323152
tags question: http://stackoverflow.com/q/51234560
tags question: http://stackoverflow.com/q/51243126
tags question: http://stackoverflow.com/q/51279452
tags question: http://stackoverflow.com/q/51209334
tags question: http://stackoverflow.com/q/51182153
tags question: http://stackoverflow.com/q/51206880
tags question: http://stackoverflow.com/q/51279921
tags question: http://stackoverflow.com/q/51224319
tags question: http://stackoverflow.com/q/51307228
tags question: http://stackoverflow.com/q/51284448
tags question: http://stackoverflow.com/q/51277851
tags question: http://stackoverflow.com/q/51243907
tags question: http://stackoverflow.com/q/51282011
tags question: http://stackoverflow.com/q/51195318
tags question: http://stackoverflow.com/q/51249989
tags question: http://stackoverflow.com/q/51197615
tags question: http://stackoverflow.com/q/51182921
tags question: http://stackoverflow.com/q/51290499

http://stackoverflow.com/comment/95509303
score: 0
type: Comment
has text: the problem is in the espeak library, at some point it is calling subprocess.Popen, and there is a bad string there
type: AnswerComment
comment on: http://stackoverflow.com/a/51268926

http://stackoverflow.com/a/51251962
answers question: http://stackoverflow.com/q/51251835
has body: d={'A': 0, 'B' : 1, 'C' : 2, 'D' : 3} e={'dfg': 3, 'dec': 2, 'aaa': 0, 'cbbb': 1} def remElem(l, i): del l[i] [l.update({k: v-1}) for k, v in l.items() if k &gt; i] print(d) remElem(d, 'B') print(d) print(e) remElem(e, 'cbbb') print(e) Gives: {'A': 0, 'C': 2, 'B': 1, 'D': 3} {'A': 0, 'C': 1, 'D': 2} {'dfg': 3, 'dec': 2, 'aaa': 0, 'cbbb': 1} {'dfg': 2, 'dec': 1, 'aaa': 0}
has comment: http://stackoverflow.com/comment/89483369
has comment: http://stackoverflow.com/comment/89482809
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/89483742

http://stackoverflow.com/comment/89366793
score: 1
comment on: http://stackoverflow.com/q/51192540
has text: If you're asking how you can differentiate **a string** from **a word**, you can't (unless you have some other info): can we refine the question as differentiate **a string with spaces** and **a string without spaces**?
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51271791
type: Answer
has body: Use reindex to include wl as new columns (whose values will be filled with NaNs). Then use interpolate(axis=1) to interpolate across the columns. Strictly speaking interpolation is only done between known values. You could, however, use limit_direction='both' to fill NaN edge values in both the forward and backward directions: &gt;&gt;&gt; df_new.reindex(columns=df_new.columns.union(wl)).interpolate(axis=1, limit_direction='both') 400.0 402.3 407.2 408.2 412.3 412.5 415.8 417.2 419.9 420.5 423.3 423.5 425.0 428.3 0 0.342346 0.342346 1.502418 1.102496 0.702573 0.379089 0.055606 -0.135563 -0.326732 -0.022298 0.282135 0.586569 0.164917 -0.256734 1 -0.220773 -0.220773 -0.567199 -0.789194 -1.011190 -0.485832 0.039526 -0.426771 -0.893069 -0.191818 0.509432 1.210683 0.414023 -0.382636 2 0.078147 0.078147 0.335040 -0.146892 -0.628824 -0.280976 0.066873 -0.881153 -1.829178 -0.960608 -0.092038 0.776532 0.458758 0.140985 3 -0.792214 -0.792214 0.254805 0.027573 -0.199659 -1.173250 -2.146841 -1.421482 -0.696124 -0.073018 0.550088 1.173194 -0.049967 -1.273128 4 -0.485818 -0.485818 0.019046 -1.421351 -2.861747 -1.020571 0.820605 0.097722 -0.625160 -0.782700 -0.940241 -1.097781 -0.809617 -0.521453 Note that Pandas DataFrames store values in a primarily column-based data structure. So computations are generally more efficient when done column-wise, not row-wise. Therefore, it might be better to transpose your dataframe: df = df_new.T and then proceed similarly as described above: df = df.reindex(index=df.index.union(wl)) df = df.interpolate(limit_direction='both') If you want to extrapolate edge values, you could use scipy.interpolate.interp1d with : fill_value='extrapolate': import numpy as np import pandas as pd import scipy.interpolate as interpolate np.random.seed(2018) df_new = pd.DataFrame(np.random.randn(5,7), columns=[402.3, 407.2, 412.3, 415.8, 419.9, 423.5, 428.3]) wl = np.array([400.0, 408.2, 412.5, 417.2, 420.5, 423.3, 425.0, 500]) x = df_new.columns y = df_new.values ne…
has comment: http://stackoverflow.com/comment/89523233
has comment: http://stackoverflow.com/comment/89522066
has comment: http://stackoverflow.com/comment/89539026
has comment: http://stackoverflow.com/comment/89561315
score: 5
upvote count: 5
has comment: http://stackoverflow.com/comment/89521834
answers question: http://stackoverflow.com/q/51271709
has comment: http://stackoverflow.com/comment/89560660
has comment: http://stackoverflow.com/comment/89560249
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51271709
downvote count: 0

http://stackoverflow.com/comment/89449125
has text: Updated the question
comment on: http://stackoverflow.com/q/51227871
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/q/51290658
has answer: http://stackoverflow.com/a/51291006
has answer: http://stackoverflow.com/a/51290695
tagged with: dataframe
has body: I have two dfs, one is longer than the other but they both have one column that contain the same values. Here is my first df called weather: DATE AWND PRCP SNOW WT01 WT02 TAVG 0 2017-01-01 5.59 0.00 0.0 NaN NaN 46 1 2017-01-02 9.17 0.21 0.0 1.0 NaN 40 2 2017-01-03 10.74 0.58 0.0 1.0 NaN 42 3 2017-01-04 8.05 0.00 0.0 1.0 NaN 47 4 2017-01-05 7.83 0.00 0.0 NaN NaN 34 Here is my 2nd df called bike: DATE LENGTH ID AMOUNT 0 2017-01-01 3 1 5 1 2017-01-01 6 2 10 2 2017-01-02 9 3 100 3 2017-01-02 12 4 250 4 2017-01-03 15 5 45 So I want my df to copy over all rows from the weather df based upon the shared DATE column and copy it over. DATE LENGTH ID AMOUNT AWND SNOW TAVG 0 2017-01-01 3 1 5 5.59 0 46 1 2017-01-01 6 2 10 5.59 0 46 2 2017-01-02 9 3 100 9.17 0 40 3 2017-01-02 12 4 250 9.17 0 40 4 2017-01-03 15 5 45 10.74 0 42 Please help! Maybe some type of join can be used.
answer count: 3
tagged with: pandas
upvote count: 0
favorite count: 0
tagged with: python
score: -1
linked to: http://stackoverflow.com/q/18792918
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51290742
has comment: http://stackoverflow.com/comment/89559068
downvote count: 1
type: Question
duplicate of: http://stackoverflow.com/q/18792918
has title: merging two dataframes together with similar column values

http://stackoverflow.com/comment/89400462
has text: You are getting an error because your classes `JB` and KL` expect additional inputs when you initialize the class (i.e. date, timeslot, and group), but you are trying to initialize the classes without providing that information, which will throw a `TypeError`.
comment on: http://stackoverflow.com/q/51209737
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89525077
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51271333
has text: appreciate your time and inputs on this, i am able to partially fix the issue, i am able to write [1] and [2] in col4, for some reason if the email id is blank in col4 it is not writing remaining columns col0, col1, col2, col3
score: 0

http://stackoverflow.com/a/51201718
accepted answer of: http://stackoverflow.com/q/51201519
answers question: http://stackoverflow.com/q/51201519
score: 5
type: Answer
has body: Looks like this is a known issue: https://github.com/pandas-dev/pandas/issues/21561 https://github.com/pandas-dev/pandas/pull/21478
upvote count: 5
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/51260786
has comment: http://stackoverflow.com/comment/89503016
has comment: http://stackoverflow.com/comment/89501331
has comment: http://stackoverflow.com/comment/89501195
type: AcceptedAnswer
has body: According to the docs for describe_events() found here "by default, the past hour of events are returned." So if no events occurred within the last hour then it returns an empty list. I tested this with an instance of my own and calling the function with just rds.describe_events( SourceIdentifier='db-instance-identifier', SourceType='db-instance' ) returns the same empty response that you got. But if I actually specify a date range/number of records to return like so: rds.describe_events( SourceIdentifier='db-instance-identifier', SourceType='db-instance', StartTime=datetime(2018, 7, 1), EndTime=datetime(2018, 7, 10), MaxRecords=20 ) Then I get a response that actually contains the events I'd expect.
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51259595
answers question: http://stackoverflow.com/q/51259595
type: Answer
has comment: http://stackoverflow.com/comment/89503766
score: 2
upvote count: 2

http://stackoverflow.com/a/51335622
upvote count: 10
score: 10
has comment: http://stackoverflow.com/comment/123868190
has comment: http://stackoverflow.com/comment/123870029
type: AcceptedAnswer
downvote count: 0
has body: The hash is computed with input arbitrary length data. Most hash functions do this by using a function that updates an internal state based on a fixed block of data, and the file (e.g.) you're hashing is processed in chunks of this fixed block size. So most hash functions have a fixed initial state (often of digest_size, but sometimes larger) that gets initialised in an initialise function (or the constructor of an hash with empty input, as well). For SHA-256 (and SHA-224 as well) this is 32 bytes, or actually 8 integers. Then it processes input data in chunks (for SHA-256 this is 64 bytes, which are transformed into 16 32-bit integers, then a longish computation is done on 8 state integers and 16 data integers after which we have a new state of 8 integers. This goes on for as long as there is input data. The size of the input chunk is the block_size. When we want to compute a digest (typically at the end of the data) we pad out the last data (if the last input chunk was smaller than the block size) and also put the total hashed length so far into the final 64 bytes (16 integers) and do the transformation from before one final time. The digest function then outputs the (part of) the final state (SHA-224 only outputs 224 bits=28 bytes of its 32 byte state) as the digest. The size of the final output (in bytes) is digest_size.
has comment: http://stackoverflow.com/comment/89739826
type: Answer
accepted answer of: http://stackoverflow.com/q/51253262
answers question: http://stackoverflow.com/q/51253262

http://stackoverflow.com/comment/89547060
comment on: http://stackoverflow.com/a/51284713
type: Comment
has text: @AmanSharma: indeed, this will also first check if the user is logged in (since techhnically it is for example possible that your know the user, but that user is not logged in, if you "change" the login procedure).
score: 1
type: AnswerComment

http://stackoverflow.com/comment/89403724
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/51209383
type: Comment
has text: I am trying to pass `df.select(*removedSpecials)` to a new variable, but simply doing `df_new = df.select(*removedSpecials)` does not seem to do the trick. Is there a way to create a new independent copy variable from the original dataframe with only those columns ?

http://stackoverflow.com/comment/89671484
comment on: http://stackoverflow.com/a/51308134
has text: t means title ?
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/51170581
type: AcceptedAnswer
score: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/51170264
has body: You are never defining the function you're trying to call. You're printing from the function but never returning a value, thus your variable "a" will never get a value. Take a look at this, hopefully you'll see where you went wrong: def odd(x): if int(x) % 2 == 0: return("this number is even") else: return("this number is odd") x = input("Enter number") print(odd(x)) Good luck! :) To further answer your question "how to put an input in a function" (which was never actually done in the first place), you could instead do it like this which would give you the same result. def odd(): x = input("Enter number ") if int(x) % 2 == 0: return("this number is even") else: return("this number is odd") print(odd())
answers question: http://stackoverflow.com/q/51170264

http://stackoverflow.com/comment/89345542
type: AnswerComment
has text: Is all the inner list creation required?
type: Comment
comment on: http://stackoverflow.com/a/51181262
score: 0

http://stackoverflow.com/q/51198184
has comment: http://stackoverflow.com/comment/89380817
has comment: http://stackoverflow.com/comment/89378731
upvote count: 4
has body: I have a pandas dataframe with 12 columns. When plotting with seaborn's heatmap, only 9 columns are shown. Three of them ('card','owner','selfemp') are missing. The code I used for plotting is: sns.heatmap(data.corr(),xticklabels=True, yticklabels=True) where data is my dataframe's name and those 3 columns are missing were converted to numeric from string using following code: data.selfemp[data.selfemp == 'yes'] = 1 data.selfemp[data.selfemp == 'no'] = 0 data.card[data.card == 'yes'] = 1 data.card[data.card == 'no'] = 0 data.owner[data.owner == 'yes'] = 1 data.owner[data.owner == 'no'] = 0 I want the heatmap to correlate between all columns since 'card' is my outcome attribute.
tagged with: pandas
has answer: http://stackoverflow.com/a/62238263
answer count: 1
favorite count: 0
tagged with: seaborn
tagged with: python
has title: Seaborn heatmap not showing columns converted from string to numerical
tagged with: heatmap
type: UnansweredQuestion
tagged with: machine-learning
downvote count: 1
type: Question
score: 3

http://stackoverflow.com/comment/89445202
comment on: http://stackoverflow.com/q/51225555
type: Comment
has text: Can you explain how can i access the chances? Should i use global chances and then use self.chances?
score: 0
type: QuestionComment

http://stackoverflow.com/a/51304337
upvote count: 3
answers question: http://stackoverflow.com/q/51304222
type: AcceptedAnswer
type: Answer
has body: Use: #create DataFrame df = df.reset_index() df.columns = ['A','B'] #boolean mask for check no NaNs to variable for reuse m = df['B'].notnull() #create index by cumulative sum for unique groups for consecutive NaNs df.index = m.cumsum() #filter only NaNs row and aggregate first and last value, convert to list missing = df[~m.values].groupby(level=0)['A'].agg(['first','last']).values.tolist() print (missing) [['10:03', '10:05'], ['10:07', '10:08']] #get length of nested lists N_missing = len(missing) print (N_missing) 2 Detail: print (df[~m.values]) A B B 2 10:03 NaN 2 10:04 NaN 2 10:05 NaN 3 10:07 NaN 3 10:08 NaN Similar solution with Series: m = s.notnull() cum = m.cumsum() missing = s[~m.values].index.to_series().groupby(cum).agg(['first','last']).values.tolist() print (missing) [['10:03', '10:05'], ['10:07', '10:08']] N_missing = len(missing) print (N_missing) 2
downvote count: 0
score: 3
accepted answer of: http://stackoverflow.com/q/51304222

http://stackoverflow.com/q/51237381
has title: Bot won't respond and also won't give me any errors
has comment: http://stackoverflow.com/comment/89453735
score: 0
has comment: http://stackoverflow.com/comment/89453974
linked to: http://stackoverflow.com/q/49331096
tagged with: discord
linked to: http://stackoverflow.com/q/51112373
type: UnansweredQuestion
tagged with: python
duplicate of: http://stackoverflow.com/q/49331096
answer count: 0
type: Question
has body: So I've recently switched to a client to bot as I've been told it a lot better than using the client. I asked a question a few weeks ago about a text-based game you can see it here How to use commands only when a current command is triggered? Somebody gave me an example of my question however the code doesn't work for some reason. All of my other commands work fine. class Game: def __init__(self): self.points = 0 self.inventory = [] sessions = {} @bot.command(pass_context=True) async def play(ctx): if ctx.message.author.id in sessions: await bot.say("You're already playing") return sessions[ctx.message.author.id] = Game() await bot.say("Welcome to the game!")
tagged with: discord.py

http://stackoverflow.com/comment/89483866
type: Comment
type: QuestionComment
has text: Also: if `dir1` and `dir2` are independent self-contained programs (with their own modules), then perhaps the most correct way to invoke them from your `main.py` program is by launching a separate Python process. E.g. you can use `subprocess.run([sys.executable, '-m', 'module'], cwd='dir1')`, which will launch a separate Python process where `dir1` is the root of `sys.path`. For sufficiently complex enough child programs this is often the simplest integration path.
score: 0
comment on: http://stackoverflow.com/q/51252214

http://stackoverflow.com/a/51311487
has comment: http://stackoverflow.com/comment/89609994
type: AcceptedAnswer
has body: Change your Hotel_image class to add related name at your foreign to use it further class Hotel_image(models.Model): hotel_img = models.ImageField(upload_to = 'hotel_images/') hotel = models.ForeignKey(Hotel, on_delete=models.CASCADE, related_name="hotel_images") Clean up a bit your views, you dont really need use values in that case. from .models import Hotel def get_hotels_by_location(request): location = request.POST.get('location').lower() result = Hotel.objects.filter(location=location) context = {'hotels': result, 'header': ['Hotel_Name', 'Rating', 'image'] } return render( request, template_name='display_hotel_by_location.html', context=context ) HTML 1 - If you consuming the hotel_img from class Hotel use this one {% for i in header %} {{ i }} {% endfor %} {% for hotel in hotels %} {% if forloop.counter0 == 2 and hotel.hotel_img %} {% endif %} {{ hotel.Hotel_Name }} {% endfor %} HTML 2 - If you using the class Hotel_image use like that {% for i in header %} {{ i }} {% endfor %} {% for hotel in hotels %} {% for img in hotel.hotel_images %} {% if img.hotel_img %} {% endif %} {% endfor %} {{ hotel.Hotel_Name }} {% endfor %} More info about Django relations: https://docs.djangoproject.com/en/2.0/ref/models/fields/#django.db.models.ForeignKey.related_name You can use Template Tags too to filter all images from your Hotel_Image 1 - Create one folder called templatetag and inside that one file inside it to be your templatetag inside your app folder hotel/templatetags/hotel_templatetag.py Inside the file put that code from django import template from .models import Hotel_image register = template.Library() def get_hotel_images(self): return Hotel_image.objects.filter(id=self.id) You Html should be like that {% for i in header %} {{ i }} {% endfor %} {% for hotel in hotels %} {% for img in hotel|get_hotel_images %} {% if img.hotel_img %} {% endif %} {% endfor %} {{ hotel.Hotel_Name }} {% endfor %} More info about templatetags: https://docs.djangoproject.com/en/2.0/ho…
answers question: http://stackoverflow.com/q/51310577
has comment: http://stackoverflow.com/comment/89624359
score: 0
has comment: http://stackoverflow.com/comment/89624373
type: Answer
accepted answer of: http://stackoverflow.com/q/51310577

http://stackoverflow.com/a/65457941
has body: maybe you forget, export FLASK_APP you can try this command export FLASK_APP=&lt;your flask file&gt;.py FLASK_ENV=development &amp;&amp; flask run you can see in documentation
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/51188027
downvote count: 0
type: Answer

http://stackoverflow.com/comment/89470540
type: QuestionComment
comment on: http://stackoverflow.com/q/51238476
score: 0
has text: @juunas oh sorry, sure. It says the following: https://login.live.com/err.srf?lc=1033#error=unauthorized_client&error_description=The+client+does+not+exist.+If+you+are+the+application+developer%2c+configure+a+new+application+through+the+application+management+site+at+https://apps.dev.microsoft.com/.&state=8KTdw8GkMVb4xC8RstBfOy7fn6MQ1e
type: Comment

http://stackoverflow.com/comment/89427299
has text: @sckol I think my answer was unclear, I‘ve reworded it
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51221023

http://stackoverflow.com/comment/89399043
comment on: http://stackoverflow.com/a/51195585
has text: Thank you very much this is all really helpful!!
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/51264665
has comment: http://stackoverflow.com/comment/89507698
score: 1
has comment: http://stackoverflow.com/comment/89507441
has comment: http://stackoverflow.com/comment/89507377
has title: Assignment operators using logical operators in Python
has comment: http://stackoverflow.com/comment/89507892
type: Question
has comment: http://stackoverflow.com/comment/89507541
downvote count: 0
tagged with: assignment-operator
has answer: http://stackoverflow.com/a/51264937
has comment: http://stackoverflow.com/comment/89508186
has comment: http://stackoverflow.com/comment/89508246
tagged with: logical-operators
has body: I know I can use assignment operators with arithmetic operators in Python, for example: x = 0x8 x |= 0x1 # x equals 9 I'd like to know if this is also possible with logical operators, for example something like: x = 2 &gt; 3 # False y = 4 &gt; 3 # True x or= y # x equals True Is there something similar to that =or operation that I can use?
has comment: http://stackoverflow.com/comment/89507339
answer count: 1
has comment: http://stackoverflow.com/comment/89507758
favorite count: 0
has comment: http://stackoverflow.com/comment/89507720
has comment: http://stackoverflow.com/comment/89510372
has comment: http://stackoverflow.com/comment/89507718
type: UnansweredQuestion
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/89549929
has comment: http://stackoverflow.com/comment/89507667
has comment: http://stackoverflow.com/comment/89507834
has comment: http://stackoverflow.com/comment/89507596

http://stackoverflow.com/q/51188782
tagged with: sqlite
downvote count: 0
score: 1
favorite count: 0
type: Question
has body: I want to get a query with SQLAlchemy on the example query that is shown on the page https://www.sqlite.org/lang_with.html: WITH RECURSIVE under_alice(name,level) AS ( VALUES('Alice',0) UNION ALL SELECT org.name, under_alice.level+1 FROM org JOIN under_alice ON org.boss=under_alice.name ORDER BY 2 DESC ) SELECT substr('..........',1,level*3) || name FROM under_alice; I'm trying to execute a my self recursive query that falls into syntax error for SQLite: OperationalError: (sqlite3.OperationalError) near "(": syntax error An exception is raised when SQLAlchemy adds parentheses on time compilation SQL statement for the bottom query in the recursive query, if it uses a orderring. How to remove parentheses from a SQL? Reproducing the exception: from flask import Flask from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///:memory:' app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False # app.config['SQLALCHEMY_ECHO'] = True db = SQLAlchemy(app) class Category(db.Model): id = db.Column(db.Integer, primary_key=True) parent_id = db.Column(db.Integer, nullable=True) name = db.Column(db.String(100), nullable=False) def __repr__(self): return f'&lt;Category {self.name}&gt;' import logging logging.basicConfig() logger = logging.getLogger('sqlalchemy.engine') logger.setLevel(logging.INFO) db.create_all() Data of Category: data = [ {'parent_id': None, 'name': 'Everything for rehabilitation'}, {'parent_id': 1, 'name': 'Wheelchairs'}, {'parent_id': 1, 'name': 'Wheelchairs 2'}, {'parent_id': 1, 'name': 'Scooters for the disabled'}, {'parent_id': 2, 'name': 'Active wheelchairs'}, {'parent_id': 2, 'name': 'Children wheelchairs'}, {'parent_id': 2, 'name': 'Children wheelchairs 2'}, {'parent_id': 2, 'name': 'Wheelchair Otto Bock'}, {'parent_id': 2, 'name': 'Wheelchair Vermeiren'}, {'parent_id': 3, 'name': 'Folding wheelchairs'}, {'parent_id': 3, 'name': 'Wheelchair for disabled people'}, {'parent_id': 3, 'name': 'Wheelchairs for t…
tagged with: python
has comment: http://stackoverflow.com/comment/89359957
tagged with: common-table-expression
has answer: http://stackoverflow.com/a/51209071
upvote count: 1
answer count: 1
type: UnansweredQuestion
tagged with: sqlalchemy
has comment: http://stackoverflow.com/comment/89374298
tagged with: sql
has title: Syntax error with recursive SQL query and order by for SQLAlchemy

http://stackoverflow.com/q/51238476
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89457566
has comment: http://stackoverflow.com/comment/89472010
answer count: 0
tagged with: azure-active-directory
tagged with: microsoft-graph-api
has comment: http://stackoverflow.com/comment/89471059
has comment: http://stackoverflow.com/comment/89470540
type: Question
has body: I am trying to get data from an Azure Active Directory that I created. I want to retrieve this data through Microsoft's Graph API. I used one of the code samples that Microsoft provides to make HTTP GET Requests: Config.py file: """Configuration settings for running the Python auth samples locally. In a production deployment, this information should be saved in a database or other secure storage mechanism. """ CLIENT_ID = 'Here I Pasted my application ID' CLIENT_SECRET = 'Here I Pasted the key i generated' REDIRECT_URI = 'http://localhost:5000/login/authorized' # AUTHORITY_URL ending determines type of account that can be authenticated: # /organizations = organizational accounts only # /consumers = MSAs only (Microsoft Accounts - Live.com, Hotmail.com, etc.) # /common = allow both types of accounts AUTHORITY_URL = 'https://login.microsoftonline.com/common' AUTH_ENDPOINT = '/oauth2/v2.0/authorize' TOKEN_ENDPOINT = '/oauth2/v2.0/token' RESOURCE = 'https://graph.microsoft.com/' API_VERSION = 'v1.0' SCOPES = ['User.Read.All'] # Add other scopes/permissions as needed. # This code can be removed after configuring CLIENT_ID and CLIENT_SECRET above. if 'ENTER_YOUR' in CLIENT_ID or 'ENTER_YOUR' in CLIENT_SECRET: print('ERROR: config.py does not contain valid CLIENT_ID and CLIENT_SECRET') import sys sys.exit(1) sample_requests.py file: """Requests-OAuthlib sample for Microsoft Graph """ # Copyright (c) Microsoft. All rights reserved. Licensed under the MIT license. # See LICENSE in the project root for license information. import os import uuid import bottle import requests_oauthlib import config MSGRAPH = requests_oauthlib.OAuth2Session(config.CLIENT_ID, scope=config.SCOPES, redirect_uri=config.REDIRECT_URI) # Enable non-HTTPS redirect URI for development/testing. os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1' # Allow token scope to not match requested scope. (Other auth libraries allow # this, but Requests-OAuthlib raises exception on scope mismatch by default.) os.environ…
has comment: http://stackoverflow.com/comment/89472810
score: 0
has comment: http://stackoverflow.com/comment/89479010
has title: Microsoft Graph API: I get stuck in the authorization workflow
has comment: http://stackoverflow.com/comment/89471421
has comment: http://stackoverflow.com/comment/89475172

http://stackoverflow.com/comment/89512194
score: 0
type: Comment
has text: @JakubZbudniewek possibly yes, I didn't bother checking the whole implementation, I just focused on your question.
type: AnswerComment
comment on: http://stackoverflow.com/a/51265033

http://stackoverflow.com/comment/89461321
comment on: http://stackoverflow.com/a/51218356
type: AnswerComment
has text: There is the possibility to [annotate](https://matplotlib.org/users/annotations_intro.html) features. Are you looking for something like this?
score: 0
type: Comment

http://stackoverflow.com/comment/89527467
has text: @hoefling that worked, thanks! It'd be great if you could add your comment and an explanation as the answer, I'll mark it as accepted.
comment on: http://stackoverflow.com/q/51271647
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51320509
type: Answer
score: 2
upvote count: 2
has body: Try to use below solution: driver.get(url) WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CLASS_NAME, "sbSelector"))).click() WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.LINK_TEXT, "Kowloon"))).click()
answers question: http://stackoverflow.com/q/51320294
accepted answer of: http://stackoverflow.com/q/51320294
has comment: http://stackoverflow.com/comment/89616710
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/89334039
type: AnswerComment
has text: @yol - It is expected, check [this](http://pandas.pydata.org/pandas-docs/stable/categorical.html#operations). Just convert columns to `string` for prevent it. `cols = ['a','b']` and then `df[cols] = df[cols].astype(str)`
type: Comment
comment on: http://stackoverflow.com/a/51169833
score: 0

http://stackoverflow.com/comment/89619768
type: QuestionComment
comment on: http://stackoverflow.com/q/51319199
has text: @MikeCC Your last comment seems to be the relevant portion that should be in the question, otherwise it's not clear what you're after. (I do however not think that what excel provides is anywhere close to showing the median as midpoint value of the colormap, so please clarify that as well).
score: 0
type: Comment

http://stackoverflow.com/q/51235043
has comment: http://stackoverflow.com/comment/89449008
answer count: 1
has answer: http://stackoverflow.com/a/51253062
type: UnansweredQuestion
tagged with: python
has title: How can I remove noise from this picture?
tagged with: image-processing
type: Question
tagged with: opencv
score: 0
has body: i have applied some filters to this image but it's always very noisy how can i remove noise and leave only the characters ? here is my code : import cv2 import numpy as np img = cv2.imread('12.jpg',0) img1=cv2.pyrDown(img) im=cv2.pyrDown(img1) final = cv2.medianBlur(im,5) cv2.imshow('image',final) cv2.waitKey(0) th2 = cv2.adaptiveThreshold(final,255,cv2.ADAPTIVE_THRESH_MEAN_C,\ cv2.THRESH_BINARY_INV,11,2) cv2.imshow('image1',th2) cv2.waitKey(0) laplacian = cv2.Laplacian(im,cv2.CV_64F) cv2.imshow('image2',laplacian) cv2.waitKey(0) original image:

http://stackoverflow.com/comment/130436297
type: AnswerComment
has text: Note: this will not work with `datetime64` arrays; you get `ValueError: cannot include dtype 'M' in a buffer`
score: 0
type: Comment
comment on: http://stackoverflow.com/a/60196911

http://stackoverflow.com/comment/89504509
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51247685
has text: Then you can divide all data by a factor of 3 to get the average per month, e.g. d = np.array([0,54957.84767,0,0,0,56285.54879,0,0])/3 followed by the rest of the code.

http://stackoverflow.com/q/51279618
score: 1
has comment: http://stackoverflow.com/comment/102149577
type: Question
answer count: 2
accepted answer: http://stackoverflow.com/a/51279701
downvote count: 0
favorite count: 0
has body: def main(): cash = float(input("How much money: ")) coins = 0 def changeCounter(n): while True: if cash - n &gt; 0: cash -= n coins += 1 else: break return main() changeCounter(0.25) When I run this code, I get the error UnboundLocalError: local variable 'cash' referenced before assignment How can I fix this?
has title: Fixing UnboundLocalError
tagged with: python
possible better answer: http://stackoverflow.com/a/51279680
has answer: http://stackoverflow.com/a/51279680
linked to: http://stackoverflow.com/q/19158339
has answer: http://stackoverflow.com/a/51279701
upvote count: 1
linked to: http://stackoverflow.com/q/423379
type: AnsweredQuestion

http://stackoverflow.com/q/51188380
has body: I need to convert database in form (3- column form) Col1 Col2 Col3 45 23 A 18 17 A 16 14 B ................ 27 33 B 13 19 C to (4-column form) Col1 A B C 45 23 18 17 16 14 .................. 27 33 13 19 I thought originally of iterating through original database (in Pandas form), accessing each string in Col3, and then based on if its A, B etc., dynamically create a SQL Insert INTO statement that enters into new table the required values only. However, my dataset (database) is huge. So is there any better way to do this?
type: UnansweredQuestion
upvote count: 1
downvote count: 1
type: Question
answer count: 1
favorite count: 0
score: 0
tagged with: pandas
tagged with: sql
tagged with: sqlite
tagged with: python
has answer: http://stackoverflow.com/a/51188972
has title: Change database from one format to another. What is most efficient way to do this?

http://stackoverflow.com/comment/89378701
comment on: http://stackoverflow.com/a/51181361
type: AnswerComment
score: 0
type: Comment
has text: In order to create a list using a type constructor, you can either do `list()` or `list([iterable])`. 'key' in your case, is an integer, and that produces an error. You can look at https://docs.python.org/3/library/stdtypes.html#list for a detailed explanation as well.

http://stackoverflow.com/comment/89547539
comment on: http://stackoverflow.com/q/51285073
has text: You can try this `subprocess.call([TOOL, 'p1 5000', target], shell=False)`
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89422963
has text: A thousand thank you's <3
comment on: http://stackoverflow.com/q/51208207
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/89461875
type: QuestionComment
comment on: http://stackoverflow.com/q/51239428
has text: I think below command fails at the background on mysql. CONSTRAINT `company__worker_worker_id_d949_fk_company_workerduty_uuid` FOREIGN KEY (`workerduty_id`) REFERENCES `company_workerduty` (`uuid`)
score: 0
type: Comment

http://stackoverflow.com/comment/89610437
type: QuestionComment
has text: Generally, to get random access (the ability to modify parts of a file without reading the whole thing into memory) you need to use some sort of database. If your only problem with the ones listed is that they store things in multiple files, then there are plenty of databases which use only a single file. I believe, for instance, that sqlite stores the entire database and indexing information in a single file, and comes with [built in Python bindings](https://docs.python.org/3/library/sqlite3.html) to boot.
score: 0
comment on: http://stackoverflow.com/q/51316955
type: Comment

http://stackoverflow.com/q/51309603
linked to: http://stackoverflow.com/q/41019222
type: Question
score: 0
tagged with: grayscale
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/89603047
tagged with: python
has title: Image de-blurring
type: UnansweredQuestion
upvote count: 1
downvote count: 1
tagged with: opencv
has comment: http://stackoverflow.com/comment/89603337
has answer: http://stackoverflow.com/a/51313701
has body: This post is divided in two Part One I have a little issue converting an image from grayscale back to RGB. Image in question: I use this code to convert it: equ = cv2.cvtColor(equ, cv2.COLOR_GRAY2RGB) without any success though... Part Two Moreover I need to de-blur such image. Here I found some code that uses a wiener filter to do so, but when I implement it it doesn't seem to work effectively. Here is the code: psf = np.ones((5, 5)) / 25 img = convolve2d(equ, psf, 'same') img += 0.1 * img.std() * np.random.standard_normal(img.shape) #deconvolved_img = restoration.wiener(img, psf, 1100) deconvolved = restoration.wiener(img, psf, 1, clip=False) plt.imshow(deconvolved, cmap='gray') and this is the output: Any help for the two problems is greatly appreciated!
has comment: http://stackoverflow.com/comment/89602706
tagged with: scikit-image
tagged with: rgb

http://stackoverflow.com/comment/89418787
type: Comment
has text: Thanks! As a follow up question, is there a quick way to add label to the chart (the % each bar represents)?
type: AnswerComment
comment on: http://stackoverflow.com/a/51218356
score: 0

http://stackoverflow.com/comment/89578524
type: Comment
type: AnswerComment
has text: @Lafayette - I am confused, I check [`percentileofscore`](https://docs.scipy.org/doc/scipy-1.0.0/reference/generated/scipy.stats.percentileofscore.html) and parameter `score`, in your function it is `y` is scalar, e.g. `3` and values from `Value` column is `x`
score: 0
comment on: http://stackoverflow.com/a/51300422

http://stackoverflow.com/q/51214979
has comment: http://stackoverflow.com/comment/89411790
tagged with: transpiler
has comment: http://stackoverflow.com/comment/89411163
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/89411564
has title: How to transform strings in a python source-file to multiline strings?
downvote count: 0
has body: To improve readability of a Python code base i want to apply a transform on all strings containing newlines to multiline strings. e.g. foo = 'line 1\nline2\nline3' Should be transformed to: foo = '''line 1 line 2 line3''' I assume this can be done by applying a regex substitution? Are there better options? One that comes to mind is using tools that actually analyze the python AST and allow to regenerate the code a bit differently, or is this direction an overkill?
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python
tagged with: regex
has answer: http://stackoverflow.com/a/51215233
score: 2
has comment: http://stackoverflow.com/comment/89411263

http://stackoverflow.com/comment/89679032
type: Comment
has text: I was getting the same error as the title of the referenced link. _Getting AttributeError 'Workbook' object has no attribute 'add_worksheet' - while writing data frame to excel sheet_. The function by @MaxU seems quite versatile with how data is inserted into excel. I hope it works well for you too!
comment on: http://stackoverflow.com/a/51292014
score: 0
type: AnswerComment

http://stackoverflow.com/comment/89516736
comment on: http://stackoverflow.com/a/51267903
type: AnswerComment
has text: When you do `lambda x: funct(x)`, you bind the *variable* `x` as argument, not the *value* of `x` at that time. Because the variable `x` changes throughout the loop, at the time the lambda function is evaluated `x` always has the last value. You can circumvent this by giving your argument a default value, which does bind the current value. You could do `lambda x=x: funct(x)`, but for clarity I prefer to give the argument a different name, so I use `lambda n=x: funct(n)`. Searching for `python lambda for loop` on google gives you a lot more questions about this with great answers.
score: 0
type: Comment

http://stackoverflow.com/comment/89493804
score: 0
type: AnswerComment
has text: @johnashu You have to improve your imports, import complete modules usually have those problems. :)
type: Comment
comment on: http://stackoverflow.com/a/51253559

http://stackoverflow.com/comment/89594737
score: 0
type: Comment
has text: Got you, in order to use the last sigmoid function, the input cant have multiple dimensions. Thank you for the kind help!
type: AnswerComment
comment on: http://stackoverflow.com/a/51294937

http://stackoverflow.com/q/51240431
upvote count: 1
answer count: 1
downvote count: 1
accepted answer: http://stackoverflow.com/a/51240539
has title: Concatenate two dataframes by two columns
has body: I need to concatenate 2 pandas DataFrames by 2 colunms. Example: df1 = pd.DataFrame({'col1':[1,2,3],'col2':[11,22,33]}) df2 = pd.DataFrame({'col1':[1,2,3,4,5,6],'col2':[11,22,33,44,55,66],'col3':[111,222,333,444,555,666]}) df2 col1 col2 col3 1 11 111 2 22 222 3 33 333 4 44 444 5 55 555 6 66 666 df1 col1 col2 1 11 2 22 3 33 Result: col1 col2 col3 1 11 111 2 22 222 3 33 333 Here col1 and col2 used as index for values form df2.col3. Thanks. (Sorry, my English is bad)
tagged with: dataframe
tagged with: concatenation
has comment: http://stackoverflow.com/comment/89459689
tagged with: pandas
type: AnsweredQuestion
tagged with: python
favorite count: 0
type: Question
score: 0
has answer: http://stackoverflow.com/a/51240539

http://stackoverflow.com/comment/89575230
type: QuestionComment
comment on: http://stackoverflow.com/q/51299087
score: 0
has text: A computer could do it the exact same way you do. Python before 3.2 didn't, but since then, it does.
type: Comment

http://stackoverflow.com/comment/89490609
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51255828
has text: What is the shape of x?

http://stackoverflow.com/a/51201073
has comment: http://stackoverflow.com/comment/89390896
has body: This should be a good starting point. Of course, I don't have your table names. DECLARE @total_matches INT DECLARE @non_matches INT DECLARE @region_or_zip_matches INT -- this will return a count of all matches SELECT @total_matches = COUNT(m.'8') FROM Matches as m -- this will return a count of matches where there is no zip/region match SELECT @non_matches = COUNT('8') FROM Matches AS m INNER JOIN Clients AS c ON c.client_id = m.client_id INNER JOIN Partners AS p ON p.partner_id = m.partner_id WHERE AND c.geo_region IS NOT NULL --not null's may be unnecessary based on column criteria. AND p.geo_region IS NOT NULL AND c.geo_zip_code IS NOT NULL AND p.geo_zip_code IS NOT NULL AND (c.geo_region != p.geo_region AND c.geo_zip_code != p.geo_zip_code) SET @region_or_zip_matches = @total_matches - @non_matches SELECT (CAST(@region_or_zip_matches AS FLOAT) / CAST(@total_matches AS FLOAT) * 100;
accepted answer of: http://stackoverflow.com/q/51200674
score: 0
answers question: http://stackoverflow.com/q/51200674
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/q/51267895
has title: Django router retrieve specific account
has comment: http://stackoverflow.com/comment/89515011
has answer: http://stackoverflow.com/a/51271585
tagged with: django
tagged with: python
type: UnansweredQuestion
tagged with: http
type: Question
score: 0
has comment: http://stackoverflow.com/comment/89517553
answer count: 1
has body: This code works for retrieving the entire list of accounts with localhost:8000/accounts/, but not for a specific account when given the email associated with the account (localhost:8000/accounts/[email of account]/. Instead, the data sent back is an HTML file. Sometimes if I put in an email that doesn't exist, it tells me the detail was not found. But only sometimes. Any help would be greatly appreciated! Here are my different files: VIEWS.PY class AccountViewSet(views.ModelViewSet): lookup_field = 'email' queryset = Account.objects.all() serializer_class = AccountSerializer URLS.PY router = routers.SimpleRouter() router.register(r'accounts', AccountViewSet) url patterns = [ url(r'api/v1/', include(router.urls)), ] MODELS.PY class Account(AbstractBaseUser): email = models.EmailField(unique=True) name = models.CharField(max_length=40, blank=True) objects = AccountManager()

http://stackoverflow.com/a/51278883
accepted answer of: http://stackoverflow.com/q/51278841
answers question: http://stackoverflow.com/q/51278841
has body: Use isnumeric for boolean mask and then swap values by 2d numpy array: mask = df['Item_category'].str.isnumeric() #if necessary check numeric #mask = pd.to_numeric(df['Item_category'], errors='coerce').notnull() df.loc[mask, ['Item_category','Price']] = df.loc[mask, ['Price','Item_category']].values print (df) Id Item_category Price 0 1 Food 647 1 2 Drinks 672 2 3 Food 627 3 4 Drinks 678 4 5 Snacks 679 5 6 Snacks 742 6 7 Snacks 743 7 8 Drinks 689
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/89536009
has comment: http://stackoverflow.com/comment/89535943

http://stackoverflow.com/q/51314424
has comment: http://stackoverflow.com/comment/89605816
upvote count: 2
has body: So I have a long list of column headers. All are strings, some are several words long. I've yet to find a way to write a function that extracts the first word from each value in the list and returns a list of just those singular words. For example, this is what my list looks like: ['Customer ID', 'Email','Topwater -https:', 'Plastics - some uml'] And I want it to look like: ['Customer', 'Email', 'Topwater', 'Plastics'] I currently have this: def first_word(cur_list): my_list = [] for word in cur_list: my_list.append(word.split(' ')[:1]) and it returns None when I run it on a list.
downvote count: 1
tagged with: string
has answer: http://stackoverflow.com/a/63784572
favorite count: 0
answer count: 5
has answer: http://stackoverflow.com/a/51314516
has title: Extracting the first word from every value in a list
tagged with: python
accepted answer: http://stackoverflow.com/a/51314551
type: AnsweredQuestion
tagged with: list
score: 1
has answer: http://stackoverflow.com/a/51314492
has answer: http://stackoverflow.com/a/51314551
has comment: http://stackoverflow.com/comment/89605547
has answer: http://stackoverflow.com/a/51314708
type: Question
tagged with: split
possible better answer: http://stackoverflow.com/a/51314492

http://stackoverflow.com/q/51173801
downvote count: 0
score: 1
has body: I want to feed a timeseries into an LSTM to perform a forecast. Lets say I have 10000 samples. Now in order to feed the timeseries into my LSTM I reshape it to (samples,timesteps,features). In my case I use timesteps=50 to create subsequences and perform a forecast of t+1. So I end up with x.shape=(9950,50,1). So far so good. My Model model= Sequential() model.add(LSTM(50,return_sequences=True,input_shape=(50,1))) model.add(Dense(out_dim, activation = 'sigmoid')) model.compile(loss='mse', optimizer='adam') NOW I want to create artificial features e.g. I want to use the fft of the signal as a feature. How I can feed it into my LSTM? Is it legitimate to just compute the fft, append it to the Dataframe and reshape all together so I end up with (9950,50,2)?? Questions are basically: How I input artifical created features into an LSTM? Its the same way for rolling statistics or correlation features? Thanks in advance
tagged with: keras
favorite count: 0
type: Question
tagged with: python
upvote count: 1
answer count: 1
has title: Feature extraction for Timeseries LSTM
tagged with: feature-extraction
has answer: http://stackoverflow.com/a/51174782
type: UnansweredQuestion
tagged with: lstm

http://stackoverflow.com/comment/89570608
type: Comment
has text: Oh, I didn't know that, maybe the `underscore` is confusing to something?
type: AnswerComment
comment on: http://stackoverflow.com/a/51296607
score: 0

http://stackoverflow.com/q/51291349
has title: Adding button in pygame and said color "green" is undefined variable
has comment: http://stackoverflow.com/comment/89562153
favorite count: 0
possible better answer: http://stackoverflow.com/a/51291424
has answer: http://stackoverflow.com/a/51291424
has comment: http://stackoverflow.com/comment/89560699
tagged with: python
tagged with: pygame
has answer: http://stackoverflow.com/a/51291400
score: -1
has comment: http://stackoverflow.com/comment/89561966
type: AnsweredQuestion
downvote count: 2
has comment: http://stackoverflow.com/comment/89589229
upvote count: 1
has comment: http://stackoverflow.com/comment/89562792
has comment: http://stackoverflow.com/comment/89562712
type: Question
accepted answer: http://stackoverflow.com/a/51291400
has comment: http://stackoverflow.com/comment/89560419
answer count: 2
has body: I'm making a small game using pygame. I'm trying to add a rectangle button on the screen and I'm using the pygame drawing function, which is pygame.draw.rect(background, green, [20, 20, 50, 20], 0) However, in the color part, it said that "green" is a undefined variable. I don't know why this happens, since "green" is not a variable, it's the color of the button. Can anyone tell me how to fix this? Update: this problem is fixed and I updated the function in this post that is works.

http://stackoverflow.com/comment/89578490
has text: the percentileofscore function from scipy.stats requires 2 inputs. it's basically the respective value from the 'Value' column. Not sure how to reference to that.
comment on: http://stackoverflow.com/a/51300422
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/89387715
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51195041
type: AnswerComment
has text: splitting arg is not a issue , i am facing issue with how to tell my function that sometime fargs will be a string sometimes it can be just a letter or say a word.

http://stackoverflow.com/q/51286170
tagged with: linux-mint
favorite count: 0
has body: My issue is that i am able to import a python module in the terminal using the shell but when i import the same module in a file, i get an error. This is the message i get: Traceback (most recent call last): File "/home/dalcoy/Desktop/Projects/Scripts/something.py", line 1, in &lt;module&gt; import pygame ImportError: No module named pygame [Finished in 0.0s with exit code 1] [shell_cmd: python -u "/home/dalcoy/Desktop/Projects/Scripts/something.py"] [dir: /home/dalcoy/Desktop/Projects/Scripts] [path:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games] this is the program: import pygame Any solution?
type: UnansweredQuestion
tagged with: python
tagged with: module
has title: Python module installed and can be run in terminal but not in file
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/89549806
type: Question
answer count: 2
linked to: http://stackoverflow.com/q/2812520
has answer: http://stackoverflow.com/a/51287031
has answer: http://stackoverflow.com/a/51286220
downvote count: 0

http://stackoverflow.com/a/51172494
upvote count: 3
has comment: http://stackoverflow.com/comment/89328714
answers question: http://stackoverflow.com/q/51171966
downvote count: 0
has comment: http://stackoverflow.com/comment/89328263
has comment: http://stackoverflow.com/comment/89329535
type: Answer
score: 3
has body: If you reformat your data file as follows, you can then use configparser module to parse it. You can install it by doing pip install configparser Data file [managers] ip = 1.2.3.4 [workers] ip = 2.3.45.5 3.5.6.7 5.7.8.9 Sample Usage from configparser import ConfigParser # from ConfigParser import ConfigParser # for python3 data_file = 'tmp.txt' config = ConfigParser() config.read(data_file) config.sections() # ['managers', 'workers'] config['managers']['ip'] # '1.2.3.4' config['workers']['ip'] #'2.3.45.5\n3.5.6.7\n5.7.8.9' config['workers']['ip'].splitlines() #['2.3.45.5', '3.5.6.7', '5.7.8.9']

http://stackoverflow.com/a/51298032
has comment: http://stackoverflow.com/comment/89573120
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/89573143
upvote count: 2
has body: datetime.time does not support the subtraction operator. Since you already have the hours and minutes as integers, you might as well calculate the difference yourself. print(((16 * 60 + 38) - (10 * 60 + 49)) / 60) This outputs: 5.816666666666666
answers question: http://stackoverflow.com/q/51297844
type: Answer

http://stackoverflow.com/a/51234584
type: Answer
score: 2
upvote count: 2
accepted answer of: http://stackoverflow.com/q/51234534
has body: From the docs: Permutations are emitted in lexicographic sort order. So, if the input iterable is >sorted, the permutation tuples will be produced in sorted order. So the answer to your question is yes, for an input like range(x) the permutations are going to be sorted in lexicographic order.
answers question: http://stackoverflow.com/q/51234534
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/51234035
has answer: http://stackoverflow.com/a/51243396
score: 2
answer count: 1
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: python
has title: Neural networks pytorch
tagged with: conv-neural-network
upvote count: 2
tagged with: pytorch
tagged with: machine-learning
type: Question
has body: I am implementing my own image classifier network. However I see for each epoch training accuracy is very good but validation accuracy is 0 till 5th epoch. I am using Adam optimizer and have learning rate .001. also resampling the whole data set after each epoch into training n validation set. Where am I going wrong? Here is my code: ### where is data? data_dir_train = '/home/sup/PycharmProjects/deep_learning/CNN_Data/training_set' data_dir_test = '/home/sup/PycharmProjects/deep_learning/CNN_Data/test_set' # Define your batch_size batch_size = 64 allData = datasets.ImageFolder(root=data_dir_train,transform=transformArr) # We need to further split our training dataset into training and validation sets. def split_train_validation(): # Define the indices num_train = len(allData) indices = list(range(num_train)) # start with all the indices in training set split = int(np.floor(0.2 * num_train)) # define the split size #train_idx, valid_idx = indices[split:], indices[:split] # Random, non-contiguous split validation_idx = np.random.choice(indices, size=split, replace=False) train_idx = list(set(indices) - set(validation_idx)) # define our samplers -- we use a SubsetRandomSampler because it will return # a random subset of the split defined by the given indices without replacement train_sampler = SubsetRandomSampler(train_idx) validation_sampler = SubsetRandomSampler(validation_idx) #train_loader = DataLoader(allData,batch_size=batch_size,sampler=train_sampler,shuffle=False,num_workers=4) #validation_loader = DataLoader(dataset=allData,batch_size=1, sampler=validation_sampler) return (train_sampler,validation_sampler) Training: from torch.optim import Adam import torch import createNN import torch.nn as nn import loadData as ld from torch.autograd import Variable from torch.utils.data import DataLoader # check if cuda - GPU support available cuda = torch.cuda.is_available() #create model, optimizer and loss function model = createNN.ConvNet(class_num=2) optimizer = Adam(m…

http://stackoverflow.com/q/51289592
tagged with: pandas
tagged with: python
has answer: http://stackoverflow.com/a/51289624
accepted answer: http://stackoverflow.com/a/51289624
tagged with: indexing
type: AnsweredQuestion
tagged with: dataframe
type: Question
upvote count: 4
has body: I have a pandas data frame df like this. In [1]: df Out[1]: country count 0 Japan 78 1 Japan 80 2 USA 45 3 France 34 4 France 90 5 UK 45 6 UK 34 7 China 32 8 China 87 9 Russia 20 10 Russia 67 I want to remove rows with the maximum value in each group. So the result should look like: country count 0 Japan 78 3 France 34 6 UK 34 7 China 32 9 Russia 20 My first attempt: idx = df.groupby(['country'], sort=False).max()['count'].index df_new = df.drop(list(idx)) My second attempt: idx = df.groupby(['country'])['count'].transform(max).index df_new = df.drop(list(idx)) But it didn't work. Any ideas?
tagged with: pandas-groupby
has title: Python: remove rows with max value in each group
answer count: 1
downvote count: 0
score: 4
favorite count: 0

http://stackoverflow.com/comment/89341447
type: Comment
has text: @AliHalawa Also, remove the useless `try/except` - it is hiding the errors in your code, very hard to write code when errors get silenced and you can't easily know what is wrong from the error messages.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51179433

http://stackoverflow.com/q/51219321
tagged with: python
answer count: 1
has title: matplotlib 'int' object not callable with basic plot
has body: I'm just starting to learn how to use mpl, and I'm getting a weird 'int not callable' error. x = np.linspace(0, 10, 100) plt.plot(x, np.sin(x)) plt.xlim = -1, 11 plt.ylim = -1.5, 1.5 TypeError: 'int' object is not callable Anybody know why this could be? It's totally perplexing to me. Here's an image of the error. EDIT: x was defined as above in a different cell, to clarify.
has answer: http://stackoverflow.com/a/51223660
tagged with: matplotlib
accepted answer: http://stackoverflow.com/a/51223660
has comment: http://stackoverflow.com/comment/89422178
score: 2
has comment: http://stackoverflow.com/comment/89419869
downvote count: 0
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89421702
favorite count: 0
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/89419880

http://stackoverflow.com/comment/89446404
has text: now I have changed that and its working and also I have changed the `Posts.objects.get(pk=slug)` to `Posts.objects.get(slug=slug)` but now whenever I go to the **admin page** it gives the error `"Posts matching query does not exist."` so what's wrong now?
type: Comment
comment on: http://stackoverflow.com/a/51232576
type: AnswerComment
score: 0

http://stackoverflow.com/comment/89401794
type: AnswerComment
has text: thank you for your reply. I tried it but nothing still happens.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51210358

http://stackoverflow.com/a/51255961
type: Answer
score: 2
answers question: http://stackoverflow.com/q/51255922
downvote count: 0
has body: This is most likely because you are not executing it using Python 3+. Please check the output of python -V to see which version you are executing your code with. On mac you may already have both installed, Python 3 is sometimes aliased under python3 file.py Here's your program converted to valid Python2: first_name = raw_input ("Hi, what's your first name? ") print ("Hi, {}".format(first_name))
upvote count: 2

http://stackoverflow.com/comment/89632283
score: 0
comment on: http://stackoverflow.com/a/51311714
type: Comment
has text: I will accept your answer but I would recommend you edit it based on my answer below. You don't need the userChange column, because the window partitions on the user_id
type: AnswerComment

http://stackoverflow.com/a/51268523
type: Answer
downvote count: 0
upvote count: 28
has comment: http://stackoverflow.com/comment/89517125
has body: It seems the python-requests/&lt;version&gt; User-Agentis being served the 403 response from the site: In [98]: requests.head('https://www.h2o.ai', headers={'User-Agent': 'Foo bar'}) Out[98]: &lt;Response [200]&gt; In [99]: requests.head('https://www.h2o.ai') Out[99]: &lt;Response [403]&gt; You can contact the site owner if you want or just use a different user-agent via the User-Agent header (like i used above). How did i debug this: I have run curl with -v (--verbose) option to check the headers being sent, and then checked out the same with requests using response.request (assuming the response is saved as response). I did not find any significant difference apart from the User-Agent header; hence, changing the User-Agent header worked as i expected.
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89517590
answers question: http://stackoverflow.com/q/51268405
score: 28
accepted answer of: http://stackoverflow.com/q/51268405

binary-tree
tag name: binary-tree
tags question: http://stackoverflow.com/q/51313190
type: Tag
tags question: http://stackoverflow.com/q/51298838

http://stackoverflow.com/a/51203611
type: AcceptedAnswer
downvote count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/89392245
has body: Unfortunately blender doesn't provide info to python while it is rendering, feedback is limited to the line at the top of the render result which you show. This answer shows a way of using bpy.app.handlers to get notifications at certain stages. For a script to monitor a render inside blenders gui, that is probably the best you will find. If you provide a way to control rendering from outside of blender you have some other options. You can start blender as a CLI tool, the -b argument will keep it in the background (no gui) and allow you to read its output to monitor where it is. I would first run a small script to get the number of frames blender -b proj.blend --python-expr "import bpy;print(bpy.context.scene.frame_start, bpy.context.scene.frame_end)" Then when you render the animation you will get progress output like blender -b project.blend -a ... Fra:3 Mem:17.40M (0.00M, Peak 23.73M) | Time:00:00.10 | Scene, Part 230-240 Fra:3 Mem:17.37M (0.00M, Peak 23.73M) | Time:00:00.10 | Scene, Part 228-240 Fra:3 Mem:17.35M (0.00M, Peak 23.73M) | Time:00:00.10 | Scene, Part 231-240 ... The first number is the frame being rendered, the last two are the tile just finished and the total tiles being rendered, you can see the time blender reports for the frame but you would want to monitor how long between each line being received and do something if it takes too long between output lines.
has comment: http://stackoverflow.com/comment/133885966
type: Answer
has comment: http://stackoverflow.com/comment/89407577
score: 2
accepted answer of: http://stackoverflow.com/q/51195307
answers question: http://stackoverflow.com/q/51195307

http://stackoverflow.com/comment/89575065
type: QuestionComment
comment on: http://stackoverflow.com/q/51299087
has text: Because in second one, you also take time to convert range into a list?
score: 0
type: Comment

http://stackoverflow.com/a/51199560
upvote count: 1
answers question: http://stackoverflow.com/q/51199548
has body: Your problem is that when your function recurses, it returns nothing. You should change else: create_client() to else: return create_client() Now, not a direct answer, but you really shouldn't use recursion in this case, it is better with a loop: def create_client(): while True: client_type = input() if client_type == 'Mickey': return 'Mickey' elif client_type == 'Jenny': return 'Jenny' elif client_type == 'McElroy': return 'McElroy' That won't exhaust the recursive call stack, and saves resources. I would even go ahead and use a dict instead of a sequence of if/elif: client_types = { 'Mickey': (3, 5, 2), 'Jenny': (5, 2, 3), 'McElroy': (4, 1, 5), } then you can make your code search the dict and return the correct numbers: while True: t = input() if t in client_types: break client = functions.client(*client_types[t])
score: 1
accepted answer of: http://stackoverflow.com/q/51199548
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/a/51315984
has comment: http://stackoverflow.com/comment/89608314
upvote count: 2
answers question: http://stackoverflow.com/q/51315922
type: Answer
has body: You iterate from 0 to len(s)-1 in your first for loop, but you're addressing i+1 which, on the last iteration, is len(s). s[len(s)] is an IndexError -- it is out of bounds. Additionally your while loop is off-by-one. while i!= " " and i&lt;=len(s): # do something referencing s[i] Your first condition makes no sense (i is a number, how could it be " "?) and your second introduces the same off-by-one error as above, where i is maximally len(s) and s[len(s)] is an error. Your logic is a bit off here, too, since you're wrapping this inside the for loop which is already referencing i. This appears to be a takewhile loop, but isn't really doing that.
score: 2
downvote count: 0

http://stackoverflow.com/comment/89363902
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/51191019
type: Comment
has text: Nice! Of course, without changing the defintion of `B`, `R = A.dot(B.astype(object))` works too.

http://stackoverflow.com/comment/89514375
type: QuestionComment
comment on: http://stackoverflow.com/q/51267790
score: 0
has text: Edited your title in the hope of making it more specific.
type: Comment

http://stackoverflow.com/q/51255494
tagged with: web-crawler
has comment: http://stackoverflow.com/comment/89504329
downvote count: 0
has comment: http://stackoverflow.com/comment/89490421
favorite count: 0
tagged with: beautifulsoup
has comment: http://stackoverflow.com/comment/89504108
has body: I have a list of url like this: url = ['url_1','url_2', 'url_3'] and there are 300 elements in the list. As their HTML structure is similar, I have written a function to crawl it and extract the information that I need: def get_department_and_units_hours(url): res = requests.get(url) soup = BeautifulSoup(res.content, "html.parser") data = [item.string for item in soup.find_all('td')] data = data[1:] return data Then, I iterate through the list and append the data into an array department_and_units_hours = [] for item in url: department_and_units_hours.append(get_department_and_units_hours(item)) print(department_and_units_hours) When I run it, it is no response. Just nothing happened. It can't print out the content of the array. Error message: I want to ask why the problem occurs and how to fix it? I really have no idea about it.
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89494200
has title: How to crawl a list of url in python web crawler?
tagged with: python
tagged with: request
score: 2
answer count: 0
upvote count: 2
type: Question
has comment: http://stackoverflow.com/comment/89497466
has comment: http://stackoverflow.com/comment/89497437

http://stackoverflow.com/comment/89482213
has text: And in fact, i do not want to merge which with which. I just wanted to create a flattened list.
comment on: http://stackoverflow.com/q/51223026
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89523569
type: Comment
comment on: http://stackoverflow.com/q/51272748
score: 0
has text: You never programmed that into the function
type: QuestionComment

http://stackoverflow.com/comment/89383238
type: AnswerComment
has text: But why ThreadPoolExecutor? If bottleneck is data processing it won't help due to GIL. ProcessPoolExecutor then?
type: Comment
comment on: http://stackoverflow.com/a/51199584
score: 1

http://stackoverflow.com/comment/89428526
comment on: http://stackoverflow.com/a/51221040
type: Comment
score: 0
type: AnswerComment
has text: Do you call `populate_cache` manually each time when you retrieve an object? Above in comments I made a proposal: create some CachedManager(models.Manager), override get_queryset() and use some custom QuerySet class there that makes caching. How do you think, is it a correct approach? Per process caching is okay.

http://stackoverflow.com/q/51225057
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/1373164
has body: How can I create variable with name from result of input? Example: username = input() result of username is example for John Now I need to create variable with name John a content will be empty string. John = ""
has comment: http://stackoverflow.com/comment/89430725
type: Question
has comment: http://stackoverflow.com/comment/89430491
has comment: http://stackoverflow.com/comment/89430680
has comment: http://stackoverflow.com/comment/89430533
has comment: http://stackoverflow.com/comment/89430593
has title: Automatically create variable with accurate content by input
duplicate of: http://stackoverflow.com/q/1373164
score: 0
tagged with: python
has comment: http://stackoverflow.com/comment/89430715
has comment: http://stackoverflow.com/comment/89430743
answer count: 0
has comment: http://stackoverflow.com/comment/89430704

http://stackoverflow.com/q/51176429
tagged with: alexa-skills-kit
has body: Hi I am trying to get a respond from Alexa requesting on a backend using requests. I am using Python with these example: https://github.com/alexa/skill-sample-python-fact. However my backend is NodeJS. From my Lambda: URL = 'https://alexa-app-nikko.herokuapp.com/alexa' def get_post_response(): r = requests.get(URL) speech_output = str(r.text) return response(speech_response(speech_output, True)) On my backend, it is routed to /alexa: router.get('/', function(request, response) { //console.log('Logged from Alexa.'); response.send('Hello World, Alexa!'); }); I tested it on the Lambda and works fine with these results: { "version": "1.0", "response": { "outputSpeech": { "type": "PlainText", "text": "Hello World, Alexa!" }, "shouldEndSession": true } } However I get a null on the Skill Output or this response from Alexa: "There was a problem with the requested skill's response" How do I debug from the Developer Console, because it seems the Lambda is fine.
has comment: http://stackoverflow.com/comment/89336158
score: 0
answer count: 2
tagged with: aws-lambda
possible better answer: http://stackoverflow.com/a/51183457
has answer: http://stackoverflow.com/a/51187307
has answer: http://stackoverflow.com/a/51183457
tagged with: python
has comment: http://stackoverflow.com/comment/89336190
type: AnsweredQuestion
has title: Alexa python get request returns null. Lambda is fine
tagged with: python-requests
has comment: http://stackoverflow.com/comment/89347668
accepted answer: http://stackoverflow.com/a/51187307
has comment: http://stackoverflow.com/comment/89347728
type: Question

http://stackoverflow.com/comment/89404152
has text: Are you using the same versions of all packages on both machines?
score: 0
comment on: http://stackoverflow.com/q/51202801
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89399344
has text: I don't have access to the server that sends the configuration files over websocket, I only want to create a client that listens to the messages it sends inside the test script. The part I couldn't get past is: I want to initate the client before I activate the trigger (navigating to a certain page) that sends a message over websocket, so it gets stuck at listening since no messages are coming.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/51208401
type: QuestionComment

http://stackoverflow.com/comment/89503392
comment on: http://stackoverflow.com/q/51258120
has text: I manage mine previous error but i got new error :with Image(filename="scansmpl.pdf[0]", resolution=300) as img: TypeError: object of type 'NoneType' has no len()
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/90222361
type: Comment
has text: @maxrt is right. The script should be in the same directory as pyinstaller and by looking at the command window it doesn't look like it is in the same directory.
comment on: http://stackoverflow.com/a/51289483
type: AnswerComment
score: 0

http://stackoverflow.com/a/51170599
answers question: http://stackoverflow.com/q/51168040
type: AcceptedAnswer
downvote count: 0
has body: from docx import Document from docx.enum.text import WD_COLOR_INDEX source_folder = 'D:/project/data2/' f = source_folder+'test.docx' document = Document(f) for para in document.paragraphs: for run in para.runs: run.font.highlight_color = WD_COLOR_INDEX.RED document.save(source_folder+'new.docx')
accepted answer of: http://stackoverflow.com/q/51168040
type: Answer
score: 2
upvote count: 2

http://stackoverflow.com/q/51210485
tagged with: python
favorite count: 0
upvote count: 3
has comment: http://stackoverflow.com/comment/89401677
type: UnansweredQuestion
score: 3
has answer: http://stackoverflow.com/a/51210734
type: Question
has answer: http://stackoverflow.com/a/51210669
has title: How to use replace double backslashes to single one for byte string in Python
has comment: http://stackoverflow.com/comment/89401937
downvote count: 0
has comment: http://stackoverflow.com/comment/89402044
has comment: http://stackoverflow.com/comment/89401563
has body: I want to replace double backslashes to single one for byte string in Python. For example, there is a bytes string. word = b'Z\xa6\x97\x86j2\x08q\\r\xca\xe6m' I need this bytes string. word = b'Z\xa6\x97\x86j2\x08q\r\xca\xe6m' If I use replace like: word = word.replace(b"\\",b"\") I got this error. File "test.py", line 79 word = word.replace(b"\\", b"\") ^ SyntaxError: EOL while scanning string literal Does anyone know how to do it?
has answer: http://stackoverflow.com/a/51210531
answer count: 3
tagged with: byte

http://stackoverflow.com/comment/89366307
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51191313
score: 0
has text: You can also use the `command` option of the button instead of using bindings: `b1 = Button(top, text="1", command=lambda: t.insert(END,"1"))`

http://stackoverflow.com/comment/89555388
has text: Please answer in English!
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51288759

ubuntu-server
type: Tag
tag name: ubuntu-server
tags question: http://stackoverflow.com/q/51218152

http://stackoverflow.com/a/51409362
upvote count: 2
has comment: http://stackoverflow.com/comment/117694574
type: AcceptedAnswer
downvote count: 1
accepted answer of: http://stackoverflow.com/q/51311383
has comment: http://stackoverflow.com/comment/109349230
has body: Basically, it's due to Python's GIL. If you don't want to dig into asyncio internals, just pip3 install telethon-sync and you're good to go.
answers question: http://stackoverflow.com/q/51311383
has comment: http://stackoverflow.com/comment/111398478
type: Answer
has comment: http://stackoverflow.com/comment/117394135
has comment: http://stackoverflow.com/comment/89855406
score: 1
has comment: http://stackoverflow.com/comment/117394106

http://stackoverflow.com/q/51211113
has body: I have a dictionary where the keys are some strings and they hold string values. Now I want to write a code which takes input from the user and if the input matches with any of the keys, prints the value contained in the keys. How do I access the elements contained in the keys and print them?
score: 0
has answer: http://stackoverflow.com/a/51220100
upvote count: 1
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/51220196
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51211145
tagged with: python
answer count: 4
has answer: http://stackoverflow.com/a/51220077
has title: How can i print the elements of a dictionary if an input string matches with a key?
type: Question

http://stackoverflow.com/a/51297983
type: Answer
answers question: http://stackoverflow.com/q/51297877
has body: import glob path="location/of/folder" allFiles = glob.glob(path + "\\*.txt") list_ = [] for file in allFiles: print(file) df = pd.read_csv(io.StringIO(file.decode('utf-8')), sep='\t', parse_dates=['Time']) list_.append(df) combined_files = pd.concat(list_)
has comment: http://stackoverflow.com/comment/89585131
score: 0

http://stackoverflow.com/a/52657280
has body: Try selecting 'Hook in to sub-processes...' in the test suite settings.
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51264303

http://stackoverflow.com/comment/89614348
score: 0
type: Comment
has text: You assign the return value of your `display()` function to `display_1`. This is None and that does not have a `doc` attribute. Do `display_1=display`
type: QuestionComment
comment on: http://stackoverflow.com/q/51319234

http://stackoverflow.com/a/51372414
score: 1
answers question: http://stackoverflow.com/q/51276704
has body: I found an easy way of center cropping in SO, which is applicable in N-dimentional arrays. @Losses Don response, which is an smart way of center cropping. The padding part, I added my self. def cropND(img, bounding): start = tuple(map(lambda a, da: a//2-da//2, img.shape, bounding)) end = tuple(map(operator.add, start, bounding)) slices = tuple(map(slice, start, end)) return img[slices]
upvote count: 1
type: Answer
downvote count: 0

http://stackoverflow.com/q/51199031
answer count: 1
has comment: http://stackoverflow.com/comment/89379811
downvote count: 3
has answer: http://stackoverflow.com/a/51248309
type: AnsweredQuestion
has title: Python 3 dataclass initialization
score: 114
type: Question
accepted answer: http://stackoverflow.com/a/51248309
has body: Do dataclasses have a way to add additional initialization aside from what is provided with its built in initializer, without overriding it? Specifically, I want to check some values of a list of integers that is one of the fields in the data class upon initialization.
tagged with: python
favorite count: 0
upvote count: 117
tagged with: python-3.x

http://stackoverflow.com/q/51177475
possible better answer: http://stackoverflow.com/a/68714427
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/79286612
tagged with: python
has answer: http://stackoverflow.com/a/51177846
type: AnsweredQuestion
score: 7
tagged with: truetype
has answer: http://stackoverflow.com/a/68714427
upvote count: 8
type: Question
has comment: http://stackoverflow.com/comment/89337942
has body: I wanted to install .ttf font file on windows 10 with python3 (more precise Python 3.6) code, I googled but the only thing I found was this one Install TTF fonts on windows with python, I tested it but it didn't do anything. Is there a way to install .ttf with python3 code? Thanks in advance.
has title: Python3 how to install .ttf font file?
linked to: http://stackoverflow.com/q/19767822
answer count: 3
downvote count: 1
has comment: http://stackoverflow.com/comment/89340481
accepted answer: http://stackoverflow.com/a/51177846

http://stackoverflow.com/comment/89347269
comment on: http://stackoverflow.com/q/51182464
score: 0
type: Comment
type: QuestionComment
has text: @DyZ Ok, I see. I suppose my issue then was I wasn't sure how to escape the latex braces. I tried using extra quotations and also \{ \} as you would in a normal latex document, however none of it worked. It's working now. If you want to make it an answer, I'll accept it. Thanks for your help.

xpath
tags question: http://stackoverflow.com/q/51231743
tags question: http://stackoverflow.com/q/51243809
tags question: http://stackoverflow.com/q/51235730
tag name: xpath
tags question: http://stackoverflow.com/q/51185284
tags question: http://stackoverflow.com/q/51240272
tags question: http://stackoverflow.com/q/51227511
tags question: http://stackoverflow.com/q/51188330
tags question: http://stackoverflow.com/q/51273382
tags question: http://stackoverflow.com/q/51224314
tags question: http://stackoverflow.com/q/51248734
tags question: http://stackoverflow.com/q/51263444
tags question: http://stackoverflow.com/q/51233901
tags question: http://stackoverflow.com/q/51207243
tags question: http://stackoverflow.com/q/51302719
tags question: http://stackoverflow.com/q/51261145
tags question: http://stackoverflow.com/q/51235304
tags question: http://stackoverflow.com/q/51238738
type: Tag
tags question: http://stackoverflow.com/q/51252089
tags question: http://stackoverflow.com/q/51243354
tags question: http://stackoverflow.com/q/51177166
tags question: http://stackoverflow.com/q/51196089
tags question: http://stackoverflow.com/q/51175902
tags question: http://stackoverflow.com/q/51205593

http://stackoverflow.com/comment/89578782
comment on: http://stackoverflow.com/a/51279946
type: AnswerComment
type: Comment
has text: i have updated the code for dilation like this "dilated_img = cv2.dilate(gray, np.ones((5, 5), np.uint8))" and "bg_img = cv2.medianBlur(dilated_img, 23)" now it's better but still something at the first line and also i just want to extract the name which the first line and the ID number which is the last line. this is the output i am getting now. 姓 名 费家加 __ 「`′' 性名u ′男… ' 民族汉 __ 出生 199壕年~7月童4日 住 址 上海市宝山区泗塘七村93 乙工乙道 ′ 公民身份号码 310109199107141011.. can you guide me how to target specific area to extract only the name and ID number?
score: 1

http://stackoverflow.com/comment/89570071
comment on: http://stackoverflow.com/q/51275741
type: Comment
type: QuestionComment
has text: @hpaulj The data type of the 1980 column is the same
score: 0

http://stackoverflow.com/comment/89435139
comment on: http://stackoverflow.com/q/51227582
type: Comment
type: QuestionComment
score: 0
has text: What if both Tina and Rick is in there?

http://stackoverflow.com/a/51214074
score: 0
has body: You shouldn't need regex just to see if a file with that name exists. You can just construct the name of the file you're looking for (with the appropriate path), and then test to see if it exists. import os path = "unmappedDir/unmapped_{fund}_{start}_{end}.csv".format(fund = "_".join(fundCode), start = startDate, end = endDate) if os.path.isfile(path): # Do loading.
type: Answer
answers question: http://stackoverflow.com/q/51213111

http://stackoverflow.com/q/51237636
type: UnansweredQuestion
tagged with: image-recognition
answer count: 0
downvote count: 0
score: 1
favorite count: 0
type: Question
tagged with: python
has title: CNTK Faster RCNN image prediction result boundary box size always follows the image size
tagged with: cntk
upvote count: 1
tagged with: machine-learning
has body: I am new to CNTK and all Machine Learning frameworks. I tried to do image recognition process with Faster RCNN with CNTK. I modified the "DetectionDemo.py" to refer to my own dataset (positive, negative, testImages, and finally a prediction image). The dataset are basemap areas (you can imagine something like google map). Some areas are considered category A (labeled as A), some areas are considered category B (labeled as B), some areas are category C (labeled as C), etc. So I would like to predict the areas and its category by using other set of basemap into the CNTK as the prediction image. No matter how big is my prediction image size, I always use the same zoom level, the same resolution (dpi, meters per cell). On my first prediction image (around 3200 x 3200 pixels), the system produced few prediction boundary boxes like in average around half size of my prediction image size. So I expected to have the same size of prediction boundary box size when I used a larger image size. However, when I used a larger image size (around 9000 x 9000 pixels) for prediction, the system produced few prediction boundary boxes also in average around half size of my prediction image size. And this kept going. When I put a prediction image that was multiple times larger in size (around 18000 x 18000 pixels) and ran the prediction again, the system produced few prediction boundary boxes also in average around half size of my prediction image size. During all of these, the training data were the same, did not change. It still used the same model and settings. Is this normal in CNTK? How to have a stable size of prediction boundary box result? Why the size of prediction boundary boxes result do not try to follow the average size of the labeled training data boundary? Looking forward to some suggestions...

http://stackoverflow.com/q/51273285
score: 1
has answer: http://stackoverflow.com/a/51352958
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/89524947
tagged with: python
tagged with: selenium
has title: Inconsistent results when using selenium and when manually clicking
upvote count: 1
answer count: 1
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/47487029
has body: I am trying to automate logging into my salesforce account. When I use my code: from selenium import webdriver from selenium.webdriver.common.keys import Keys browser= webdriver.Firefox() browser.get("https://xxxxx.my.salesforce.com/? SAMLRequest=&amp;startURL=%2Fidp%2Flogin%3Fapp% 3D0sp0g000000Gmhj&amp;un=xxxxx.xxxxx%40xxxxx.com") elem=browser.find_element_by_id("username") elem.send_keys("xxxxx.xxxx@xxxxx.com") elem_pass=browser.find_element_by_id("password") elem_pass.send_keys("xxxxxxx") rem_me=browser.find_element_by_id("rememberUn") rem_me.click() elem.send_keys(Keys.ENTER) As you can see, I pass the link to the url, pass the usname, password and remember me. When I run this with Selenium, it goes to a email 2FA authentication page. But when I do it manually: Copy the url mentioned above. Paste it into the address bar of firefox browser. The uname and pass show already populated. When I hit enter, it logs me in. (No 2FA). Is Salesforce somehow detecting that request is from selenium? And is there a way to get around it? Could this be related to this? Different results when using Selenium + Python
has comment: http://stackoverflow.com/comment/89538259
has comment: http://stackoverflow.com/comment/89526042
downvote count: 0

http://stackoverflow.com/comment/89408106
type: QuestionComment
comment on: http://stackoverflow.com/q/51213451
type: Comment
score: 1
has text: 126 = 63*2. Make sure that your file doesn't have spurious CR (carriage return) chars (the infamous windows CSV write bug) which makes a blank line after every line.

boxplot
tags question: http://stackoverflow.com/q/51184590
tag name: boxplot
tags question: http://stackoverflow.com/q/51267096
type: Tag

http://stackoverflow.com/a/51254525
has body: You can subclass the Retry class to add that functionality. This is the full interaction flow with the Retry instance for a given connection attempt: Retry.increment() is called with the current method, url, response object (if there is one), and exception (if one was raised) whenever an exception is raised, or a 30x redirection response was returned, or the Retry.is_retry() method returns true. .increment() will re-raise the error (if there was one) and the object was configured not to retry that specific class of errors. .increment() calls Retry.new() to create an updated instance, with any relevant counters updated and the history attribute amended with a new RequestHistory() instance (a named tuple). .increment() will raise a MaxRetryError exception if Retry.is_exhausted() called on the return value of Retry.new() is true. is_exhausted() returns true when any of the counters it tracks has dropped below 0 (counters set to None are ignored). .increment() returns the new Retry instance. the return value of Retry.increment() replaces the old Retry instance tracked. If there was a redirect, then Retry.sleep_for_retry() is called (sleeping if there was a Retry-After header), otherwise Retry.sleep() is called (which calls self.sleep_for_retry() to honor a Retry-After header, otherwise just sleeping if there is a back-off policy). Then a recursive connection call is made with the new Retry instance. This gives you 3 good callback points; at the start of .increment(), when creating the new Retry instance, and in a context manager around super().increment() to let a callback veto an exception or update the returned retry policy on exit. This is what putting a hook on the start of .increment() would look like: import logging logger = getLogger(__name__) class CallbackRetry(Retry): def __init__(self, *args, **kwargs): self._callback = kwargs.pop('callback', None) super(CallbackRetry, self).__init__(*args, **kwargs) def new(self, **kw): # pass along the subclass additional i…
score: 40
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/89546045
has comment: http://stackoverflow.com/comment/89548686
type: Answer
has comment: http://stackoverflow.com/comment/89584349
accepted answer of: http://stackoverflow.com/q/51188661
has comment: http://stackoverflow.com/comment/89548621
upvote count: 40
has comment: http://stackoverflow.com/comment/89576816
answers question: http://stackoverflow.com/q/51188661

http://stackoverflow.com/comment/90291219
has text: I'm sorry I couldn't be mach of a help. I checked with `PyCharm Community Edition 2018.2` and `PyCharm Community Edition 2017.3.3` . In my case, cv2's autocomprication worked only when installed through PyCharm.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51632205
type: Comment

http://stackoverflow.com/comment/89417095
has text: you did call `PyEval_InitThreads();`? maybe check this [Embedding python in multithreaded C application](https://stackoverflow.com/questions/10625584/embedding-python-in-multithreaded-c-application)
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51217867
score: 1

http://stackoverflow.com/q/51318155
favorite count: 0
type: UnansweredQuestion
score: 6
tagged with: python
has comment: http://stackoverflow.com/comment/89612466
has comment: http://stackoverflow.com/comment/89613074
downvote count: 0
tagged with: scrapy
type: Question
has body: I am writing the scrapy crawler to scrape the data from the e-commerce website. The website has the color variant and each variant has own price, sizes and stock for that sizes. To get the price, sizes, and the stocks for variant need to visit the link of the variant(color). And all data needes in one record. I have tried using requests but it is slow and sometimes fails to load the page. I have written the crawler using requests.get() and use the response in the scrapy.selector.Selector() and parsing data. What my question is, is there any way to use scrapy.Request() to get the response where I use it not at the callback function. I need the response at the same place as below(something like below), response = scrapy.Request(url=variantUrl) sizes = response.xpath('sizesXpath').extract() I know scrapy.Request() require parameter called callback=self.callbackparsefunction that will be called when scrapy generates the response to handle that generated response. I do not want to use callback functions I want to handle the response in the current function. Or is there any way to return the response from the callback function to function where scrapy.Request() is written as below(something like below), def parse(self, response): variants = response.xpath('variantXpath').extract() for variant in variants: res = scrapy.Request(url=variant,callback=self.parse_color) # use of the res response def parse_color(self, response): return response
upvote count: 6
has comment: http://stackoverflow.com/comment/89612229
has title: How to use Scrapy Request and get response at same place?
has answer: http://stackoverflow.com/a/51340266
answer count: 1
tagged with: callback

http://stackoverflow.com/a/79238514
score: 1
answers question: http://stackoverflow.com/q/51286116
upvote count: 1
has body: python @pytest.fixture(autouse=True) def session(db): # Begin a top-level transaction connection = db.engine.connect() transaction = connection.begin() # Bind the connection to the session db.session.bind = connection # Start a nested transaction for the test db.session.begin_nested() # Listen for the "after_transaction_end" event to reset nested transactions @event.listens_for(db.session, "after_transaction_end") def restart_savepoint(session, transaction): if transaction.nested and not transaction._parent.nested: session.begin_nested() yield db.session # Provide the session to the test # Roll back the nested transaction and close the session db.session.rollback() db.session.close() # Roll back the top-level transaction transaction.rollback() connection.close()
type: Answer
downvote count: 0

http://stackoverflow.com/comment/89556842
score: 1
comment on: http://stackoverflow.com/a/51288580
has text: If you don’t want to write it, you can also build it using `pkt = Ether(bytes(pkt))` (Supposing Ether is the lowest layer), after having set the values to None, this also recalculate the checksums
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/89399720
type: Comment
comment on: http://stackoverflow.com/a/51200184
score: 0
type: AnswerComment
has text: Excellent Hydex, it worked for me, thanks for your time bro!. I just had to convert it before, with the function that i added in your answer.

http://stackoverflow.com/comment/89598083
type: AnswerComment
type: Comment
has text: You can look up the docs for [`numpy.diff`](https://docs.scipy.org/doc/numpy/reference/generated/numpy.diff.html). You'll find the `axis` parameter specifies which differences you take. `axis=0` means row-wise. You can also calculate it manually to check.
score: 1
comment on: http://stackoverflow.com/a/51305802

http://stackoverflow.com/a/51232020
downvote count: 0
score: 1
has body: If you want send data in request body, use this approach: payload = {'data1param': data1, 'data2param': data2} r = requests.post('https://example.com/endpoint.php', data=payload) If in query params: payload = {'data1param': data1, 'data2param': data2} r = requests.post('https://example.com/endpoint.php', params=payload) # It's equal to https://example.com/endpoint.php?data1param=...&amp;data2param=...
type: Answer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/51231735
answers question: http://stackoverflow.com/q/51231735
type: AcceptedAnswer

http://stackoverflow.com/a/53471224
has body: I had this issue (exactly same error) and tried all the solutions mentioned above, and neither of them worked (at least for me), actually I was about to pull my hairs over this issue till I found the solution in a very weird, simple and stupid way!! . I did the following steps so that the problem solved and life got sweet again. First I installed MySQL Connector/C from here Second (after installation finished) I copied MySQL Connector C 6.1 folder from Program files/MySQL into Program files (x86)/MySQL note that you might have to create MySQL folder if it doesn't exist in Program files (x86) (it didn't exist for me) As simple as that, it worked for me, it seems for some (or all) 64-bit windows, pip or more probably mysqlclient setup script only searches Program files (x86) folder for some MySQL files (such as 'mysql.h') and doesn't search Program files and since doesn't find anything in Program files (x86) raises the error very dumb!!! isn't it
has comment: http://stackoverflow.com/comment/96093150
type: Answer
answers question: http://stackoverflow.com/q/51294268
score: 7
upvote count: 7
downvote count: 0
has comment: http://stackoverflow.com/comment/96118754

http://stackoverflow.com/comment/89392245
type: Comment
has text: Ok, it works! Is it possible to have also the blenders GUI?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51203611

http://stackoverflow.com/a/51300280
accepted answer of: http://stackoverflow.com/q/51300181
answers question: http://stackoverflow.com/q/51300181
has body: The file objects in the io module (the ones you get from open) and everywhere else you'd expect in the stdlib always flush when they close, or rely on platform APIs that are guaranteed to do so. Even third-party libraries are required to "close and flush the stream" on their close methods if they want their objects to be file objects.1 The main reason to call flush is when you're not closing the file yet, but some other program might want to see the contents. For example, a lot of people write code like this: with open('dump.txt', 'w') as f: while True: buf = read_off_some_thingy() f.write(buf.decode()) time.sleep(5) … and then they wonder why when they cat dump.txt or open it in Notepad or whatever, it's empty, or missing the last 3 lines, or cuts off in the middle of a line. That's the problem flush solves: with open('dump.txt', 'w') as f: while True: buf = read_off_some_thingy() f.write(buf.decode()) f.flush() time.sleep(5) Or, alternatively, they're running the same code, but the problem is that someone might pull the plug on the computer (or, more likely nowadays, kill your container), and then after restart they'll have a corrupt file that cuts off in mid-line and now the perl script that scans the output won't run and nobody wants to debug perl code. Different problem, same solution. But if you know for a fact that the file is going to be closed by some point (say, because there's a with statement that ends before there), and you don't need the file to be done before that point, you don't need to call flush. You didn't mention fsync, which is a whole other issue—and a whole lot more complicated than most people thing—so I won't get into it. But the question you linked already covers the basics. 1. There's always the chance that you're using some third-party library with a file-like object that duck-types close enough to a file object for your needs, but isn't one. And such a type might have a close that doesn't flush. But I honestly don't think I've ever seen…
has comment: http://stackoverflow.com/comment/89577640
has comment: http://stackoverflow.com/comment/89577665
has comment: http://stackoverflow.com/comment/89577571
has comment: http://stackoverflow.com/comment/89577503
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/89577717
score: 4
has comment: http://stackoverflow.com/comment/89577878
type: Answer
upvote count: 4

http://stackoverflow.com/q/51249178
has title: Django: create object when server starts and use it in views
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/51251729
accepted answer: http://stackoverflow.com/a/51251729
type: AnsweredQuestion
score: 3
downvote count: 0
linked to: http://stackoverflow.com/q/51081783
type: Question
has body: I have an image detector module, that takes about one minute to load. I would like to instantiate it once when the server starts, and use it in views. I know that i can run code when the server starts at urls.py, so, i tried the following: urls.py from django.contrib import admin from django.urls import include, path from module import Module urlpatterns = [ path('module/', include('project.urls')), path('admin/', admin.site.urls), ] module = Module() views.py from django.http import HttpResponse from project.urls import module def end_point(request): module.do_stuff() return HttpResponse("It works!") This approach did not work, because i can not import any variables from this file. Besides that, if urls.py die, i would get NameError: name 'module' is not defined. I do not use data base, i only want a REST API to my module. I would like to use Djongo, because i will use it in other services in my project. Summing up: i want a place to instantiate an object once when server starts, and be able to use my object in views. Thanks!
has comment: http://stackoverflow.com/comment/89479031
upvote count: 3
has comment: http://stackoverflow.com/comment/89477427
answer count: 1
favorite count: 0

http://stackoverflow.com/a/51306467
has comment: http://stackoverflow.com/comment/89732665
has comment: http://stackoverflow.com/comment/89590908
type: Answer
downvote count: 1
upvote count: 0
has comment: http://stackoverflow.com/comment/89679026
score: -1
answers question: http://stackoverflow.com/q/51306340
has body: Goto directory level like C:/,d:/ : in directory level for loop go through all files and folders then in each folders go through each files and folders. You can use LinkedList/Array for folders to be scanned and one by one scan them

http://stackoverflow.com/comment/89748134
type: QuestionComment
score: 0
has text: Ok, then at first you would have to create the list of bones, that is: a 20-element list of the corresponding line numbers of the joints which build a bone.
comment on: http://stackoverflow.com/q/51285630
type: Comment

http://stackoverflow.com/comment/89544573
has text: Use `argparse`…?
score: 2
comment on: http://stackoverflow.com/q/51283614
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89604477
comment on: http://stackoverflow.com/q/51313688
has text: Sorry @Lemayzeur updated the question for clarity.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89634818
comment on: http://stackoverflow.com/a/51326244
type: AnswerComment
has text: @stucash I expanded the answer.
type: Comment
score: 0

http://stackoverflow.com/comment/89414118
comment on: http://stackoverflow.com/a/51214237
type: AnswerComment
has text: Shouldn't that last line be `imported_shapes = cmds.ls(imported_objects, type='shape')` ?
score: 0
type: Comment

http://stackoverflow.com/q/51175117
tagged with: tensorflow
upvote count: 3
has body: The following line creates a layer of size three with the sigmoid activation function on each neuron: out = layers.dense(inputs=inp, units=3, activation=sigmoid) What I would like to do is something like this: out = layers.dense(inputs=inp, units=3, activation=[sigmoid sigmoid relu]) In essence, the first two neurons contain the sigmoid activation function and the third neuron contains the relu activation function. My question is: How do I implement this? I would appreciate it if someone could answer this question.
downvote count: 0
type: UnansweredQuestion
score: 3
has answer: http://stackoverflow.com/a/51176080
tagged with: python
favorite count: 0
type: Question
has title: How to implement different activation functions in a layer of a neural network in Tensorflow?
answer count: 1

http://stackoverflow.com/comment/89321039
comment on: http://stackoverflow.com/q/51167870
score: 0
type: Comment
type: QuestionComment
has text: Can you tell us what exactly is going worng? I tried the cmds.setKeyframe() exactly as you suggested and it works fine. So what's the problem exactly?

http://stackoverflow.com/comment/89575658
has text: If you dont specify `key=` to sorted method, it will complain `TypeError: must use keyword argument for key function` as it expects only keyword arguments
score: 0
comment on: http://stackoverflow.com/a/51298628
type: Comment
type: AnswerComment

http://stackoverflow.com/q/51171428
downvote count: 0
tagged with: pytest
has comment: http://stackoverflow.com/comment/89325751
has body: I am new in mock and tests for python code(whatever code). I'm trying to test my function main.py def get_channel_list(): sc = SlackClient(get_token()) channels_list_json = sc.api_call("channels.list") if channels_list_json['ok'] == True: return channels_list_json that is function that I'm trying to test I need to mock patch sc.api_call("channels.list") to return JSON object but I can't find any examples like this that would help me to figure out how to do it. Evrething I found was like this example Mocking a class method... I think it would look like this: @patch.object(SlackClient, 'api_call') def test_get_channel_list(): assert get_channel_list() != "" I don't have to to test lib I need to test the rest of my code in the function that I mentioned before. Thanks for any help, I'm realy stack with this test.
type: Question
has comment: http://stackoverflow.com/comment/89325632
tagged with: mocking
has comment: http://stackoverflow.com/comment/89325672
score: 4
answer count: 1
upvote count: 4
has comment: http://stackoverflow.com/comment/89325558
favorite count: 0
has title: How to mock library class for Pytest
linked to: http://stackoverflow.com/q/34406848
tagged with: python
has answer: http://stackoverflow.com/a/51172007
accepted answer: http://stackoverflow.com/a/51172007
type: AnsweredQuestion

http://stackoverflow.com/q/51205044
has body: For e.g., if the string is really2, I want to replace it as really-really. I want the duplicated words hyphenated as well. Can I avoid using RegEx? Thanks so much!
tagged with: regex
has answer: http://stackoverflow.com/a/51205261
favorite count: 0
has answer: http://stackoverflow.com/a/51205090
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89391078
tagged with: duplicates
type: Question
answer count: 2
possible better answer: http://stackoverflow.com/a/51205090
score: -2
has title: What is a python code for duplicating words that have the number 2 behind it?
accepted answer: http://stackoverflow.com/a/51205261
has comment: http://stackoverflow.com/comment/89391646
downvote count: 3
upvote count: 1

http://stackoverflow.com/q/51183430
answer count: 1
tagged with: github
favorite count: 0
has title: GitHub : API name/identity inside webhook payload?
tagged with: webhooks
tagged with: python
tagged with: python-3.x
score: 2
downvote count: 0
type: UnansweredQuestion
type: Question
has answer: http://stackoverflow.com/a/51185003
upvote count: 2
has body: I'm writing a Github API client and a webhook. Is there any way to distinguish if an event (i.e assignment, issue open, etc etc) is trigered by API or by user directly (i.e via git's web ui) ? I read what payload github will send on it's webhook call, but could not find one. sincerely -bino-

http://stackoverflow.com/comment/89579334
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51300497
score: 1
has text: You aren't encrypting a Word file with that code. You are only encrypting *some* of the context you read from it. The file remains unprotected. Word files already support cryptographic encryption using AES and cryptographic signing.

http://stackoverflow.com/comment/89608806
has text: I added the comma, thanks.
comment on: http://stackoverflow.com/q/51316220
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51276893
has comment: http://stackoverflow.com/comment/89886638
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89866254
tagged with: selenium
tagged with: python
score: 14
tagged with: selenium-webdriver
has comment: http://stackoverflow.com/comment/89844598
linked to: http://stackoverflow.com/q/18719980
has body: I'm just wondering how you would go about setting a specific proxy for each request?! The following block quote is the only thing the documentation says about this. Also, the documentation only provides an example for Java... Firefox version 48 and newer - GeckoDriver Firefox maintains its proxy configuration in a profile. You can preset the proxy in a profile and use that Firefox Profile or you can set it on profile that is created on the fly as is shown in the following example. With GeckoDriver the proxy has to be passed through the required capabilities. Any advice would be appreciated!
has title: Using and Randomizing Proxies
linked to: http://stackoverflow.com/q/51562067
has comment: http://stackoverflow.com/comment/90168074
type: Question
has comment: http://stackoverflow.com/comment/89818812
has comment: http://stackoverflow.com/comment/90160032
tagged with: proxies
has answer: http://stackoverflow.com/a/59304253
has comment: http://stackoverflow.com/comment/89829888
has comment: http://stackoverflow.com/comment/89844492
tagged with: random
answer count: 3
has answer: http://stackoverflow.com/a/57653719
has comment: http://stackoverflow.com/comment/89818856
has answer: http://stackoverflow.com/a/51430280
downvote count: 1
upvote count: 15
favorite count: 0
has comment: http://stackoverflow.com/comment/89910541

http://stackoverflow.com/comment/89418264
type: QuestionComment
comment on: http://stackoverflow.com/q/51215295
has text: it is very huge data for python iterators( foreach and while). solution would be with map-reduce i think or with spark !
score: 0
type: Comment

http://stackoverflow.com/q/51252887
tagged with: pyqtgraph
type: AnsweredQuestion
has title: run pyqtgraph from function
type: Question
has body: I have created the following graph in pyqtgraph. It runs fine and displays as it should. import numpy as np import pyqtgraph as pg import pyqtgraph.exporters from pyqtgraph.Qt import QtCore, QtGui import csv import itertools from datetime import datetime as dt app = QtGui.QApplication([]) class TimeAxisItem(pg.AxisItem): def tickStrings(self, values, scale, spacing): return [dt.fromtimestamp(value) for value in values] x_vals = [dt(2018, 7, 1, 13, 6, 38), dt(2018, 7, 1, 12, 46, 38), dt(2018, 7, 1, 12, 36, 38), dt(2018, 7, 1, 12, 26, 38), dt(2018, 7, 1, 12, 16, 38), dt(2018, 7, 1, 12, 6, 38), dt(2018, 7, 1, 11, 56, 38), dt(2018, 7, 1, 11, 46, 38), dt(2018, 7, 1, 11, 36, 38), dt(2018, 7, 1, 11, 26, 38), dt(2018, 7, 1, 10, 56, 38), dt(2018, 7, 1, 10, 46, 38), dt(2018, 7, 1, 10, 36, 38)] y_vals = [23.5, 20.8, 28.0, 28.1, 28.0, 27.8, 27.3, 27.2, 25.7, 24.7, 25.0, 25.0, 24.9] date_axis = TimeAxisItem(orientation='bottom') plt = pg.PlotWidget(axisItems = {'bottom': date_axis}) # set properties plt.setLabel('left', 'Temperature', units='C') plt.setWindowTitle('Temperature over time') plt.plot(x=[x.timestamp() for x in x_vals], y=y_vals, symbol=None, pen='r', symbolPen='r') plt.show() if __name__ == '__main__': import sys if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'): QtGui.QApplication.instance().exec_() However when I attempt to run it from a function, it flashes then disappears yet pyqt is still running.. import numpy as np import pyqtgraph as pg import pyqtgraph.exporters from pyqtgraph.Qt import QtCore, QtGui import csv import itertools from datetime import datetime as dt app = QtGui.QApplication([]) class TimeAxisItem(pg.AxisItem): def tickStrings(self, values, scale, spacing): return [dt.fromtimestamp(value) for value in values] def Gshow(): # app = QtGui.QApplication([]) x_vals = [dt(2018, 7, 1, 13, 6, 38), dt(2018, 7, 1, 12, 46, 38), dt(2018, 7, 1, 12, 36, 38), dt(2018, 7, 1, 12, 26, 38), dt(2018, 7, 1, 12, 16, 38), dt(2018, 7, 1, 12, 6, 38)…
has answer: http://stackoverflow.com/a/51252952
answer count: 2
possible better answer: http://stackoverflow.com/a/51252952
has answer: http://stackoverflow.com/a/51253559
score: 0
tagged with: python
accepted answer: http://stackoverflow.com/a/51253559
tagged with: pyqt5

http://stackoverflow.com/comment/89459899
type: Comment
has text: well you first need to remove the migration file, make new migrations, and then run them. Since now you are still stuck at *this* migration./
score: 0
comment on: http://stackoverflow.com/q/51239428
type: QuestionComment

http://stackoverflow.com/q/51198109
has comment: http://stackoverflow.com/comment/89378207
accepted answer: http://stackoverflow.com/a/51198155
has comment: http://stackoverflow.com/comment/89378195
downvote count: 0
answer count: 1
favorite count: 0
tagged with: radix
has comment: http://stackoverflow.com/comment/89378276
linked to: http://stackoverflow.com/q/464864
linked to: http://stackoverflow.com/q/31961442
linked to: http://stackoverflow.com/q/27757973
has title: How to generate all possible combinations of N slots with V possible values?
linked to: http://stackoverflow.com/q/329886
tagged with: python
has comment: http://stackoverflow.com/comment/89378173
has comment: http://stackoverflow.com/comment/89378064
has comment: http://stackoverflow.com/comment/89377995
duplicate of: http://stackoverflow.com/q/31961442
duplicate of: http://stackoverflow.com/q/27757973
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89378062
duplicate of: http://stackoverflow.com/q/329886
upvote count: 2
has answer: http://stackoverflow.com/a/51198155
type: Question
has body: I have N ordered slots. Each slot has a value within V possible values N = 4 # number of objects (e.g. slots) possible_values = ['A','B'] V = len(possible_values ) How would it be possible to generate the list of all possible combinations in Python? For instance, when V=2 and N=4, I would like to get the following list of the 2**4 different combinations: combinations = [ [ 'A', 'A', 'A', 'A' ], # combination 0 [ 'A', 'A', 'A', 'B' ], # combination 1 [ 'A', 'A', 'B', 'A' ], # combination 2 [ 'A', 'A', 'B', 'B' ], # combination 3 [ 'A', 'B', 'A', 'A' ], # combination 4 [ 'A', 'B', 'A', 'B' ], # combination 5 [ 'A', 'B', 'B', 'A' ], # combination 6 [ 'A', 'B', 'B', 'B' ], # combination 7 [ 'B', 'A', 'A', 'A' ], # combination 8 [ 'B', 'A', 'A', 'B' ], # combination 9 [ 'B', 'A', 'B', 'A' ], # combination 10 [ 'B', 'A', 'B', 'B' ], # combination 11 [ 'B', 'B', 'A', 'A' ], # combination 12 [ 'B', 'B', 'A', 'B' ], # combination 13 [ 'B', 'B', 'B', 'A' ], # combination 14 [ 'B', 'B', 'B', 'B' ], # combination 15 ] I would like the code to work when N and V vary. For example, when N=9 slots and V=4 possible values, I expect the list of the 4**9=262144 possible combinations.
has comment: http://stackoverflow.com/comment/89377982
linked to: http://stackoverflow.com/q/1764464
has comment: http://stackoverflow.com/comment/89378281
has comment: http://stackoverflow.com/comment/89378016
has comment: http://stackoverflow.com/comment/89378322
has comment: http://stackoverflow.com/comment/89378152
duplicate of: http://stackoverflow.com/q/1764464
has comment: http://stackoverflow.com/comment/89377962
linked to: http://stackoverflow.com/q/11144513
has comment: http://stackoverflow.com/comment/89377985

http://stackoverflow.com/comment/89357386
type: AnswerComment
score: 0
type: Comment
has text: @SumitGupta Please note that I added some brackets to your json file content to make it work.
comment on: http://stackoverflow.com/a/51185956

http://stackoverflow.com/q/51227185
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51227216
tagged with: list
downvote count: 3
has comment: http://stackoverflow.com/comment/89437297
has body: I have created lists by extracting lines from files, and I am trying to add '.flac' to the end of the numbers in each lines of the list. Example of a line: 26-496-0000 IT WAS NOW MID JULY AND THE PLAGUE WHICH HAD CHIEFLY RAGED AT THE OTHER END OF THE TOWN AND AS I SAID BEFORE IN THE PARISHES OF SAINT GILES SAINT ANDREW'S HOLBORN and I hope to change all the lines like this one in my list to: 26-496-0000.flac IT WAS NOW MID JULY AND THE PLAGUE WHICH HAD CHIEFLY RAGED AT THE OTHER END OF THE TOWN AND AS I SAID BEFORE IN THE PARISHES OF SAINT GILES SAINT ANDREW'S HOLBORN Any ideas on how I can add .flac to the end of the numbers for each of these lines in my list? Thanks in advance!
type: Question
has answer: http://stackoverflow.com/a/51227216
has title: Adding text to the end of numbers in a line
upvote count: 0
answer count: 1
favorite count: 0
tagged with: python-3.x
score: -3

http://stackoverflow.com/q/51227947
has comment: http://stackoverflow.com/comment/89435936
type: UnansweredQuestion
tagged with: code-generation
tagged with: python
has comment: http://stackoverflow.com/comment/89436036
has answer: http://stackoverflow.com/a/51227976
tagged with: generator
tagged with: combinations
has comment: http://stackoverflow.com/comment/89435864
has body: I want to write a code which gives me all the possible combinations of n elements in a k length k>n.The issue with this code is that i run out of memory quite fast.I was wondering if someone knew how to fix this with generators.I don't want to get all the possible combinations of a list elements. I want to get all the combinations of the elements in a certain length. Thanks. def allstrings(alphabet, length): """Find the list of all strings of 'alphabet' of length 'length'""" if length == 0: return [] c = [[a] for a in alphabet[:]] if length == 1: return c c = [[x,y] for x in alphabet for y in alphabet] if length == 2: return c for l in range(2, length): c = [[x]+y for x in alphabet for y in c] return c if __name__ == "__main__": for p in allstrings(['a','b','c'],4): print (p)
type: Question
has title: Generator of combinations
duplicate of: http://stackoverflow.com/q/27974126
answer count: 1
score: 0
tagged with: python-3.x
linked to: http://stackoverflow.com/q/464864

http://stackoverflow.com/comment/89609365
comment on: http://stackoverflow.com/q/51316310
score: 0
type: Comment
type: QuestionComment
has text: @juanpa.arrivillaga is right. There are many ways this could be done - some better than others. I'd perfer his method, but if you need something simpler, iterate over `L` and check if the current element is 'truthy' (e.g. `if l:`). If the element is truthy, then add it's values to some variable which stores the total sum of all non-empty list.

http://stackoverflow.com/q/51181603
answer count: 2
has body: Just started learning python a couple days ago and have been trying to use what code I know to practice a basic code of asking for a user name and password from a list. I know there are far better/cleaner/matching user to password inputs but I'm just playing with what I know at this point. users = ['Jon','Joe', 'Jole'] user_input = input('Username: ') while user_input != users: user_redo = input("I'm sorry but we dont recognize you. Please try another username: ") this is where my problem is. Is there a simple way of breaking the loop if the user enters a matching username from the list? passwords = ['donkey808','Hanna5006'] password = input('Password: ') I guess the same question would apply to the password entry as well while password != passwords: pw_redo = input(f'Please enter correct password for user {user_input}: ') else: print(f'Access Granted {user_input}')
possible better answer: http://stackoverflow.com/a/51181664
has answer: http://stackoverflow.com/a/51181889
accepted answer: http://stackoverflow.com/a/51181889
favorite count: 0
tagged with: python-3.x
tagged with: python
linked to: http://stackoverflow.com/q/10406130
has answer: http://stackoverflow.com/a/51181664
has title: basic user log in/pw code
score: 2
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/89345529
has comment: http://stackoverflow.com/comment/89345518
type: Question
upvote count: 2

http://stackoverflow.com/q/51270091
favorite count: 0
has body: Hi I am working with a pandas.Dataframe like below: Name Quality Carrot 50 Potato 34 Raddish 43 Ginger 50 Tomato 43 Cabbage 12 I want to associate a rank to the dataframe. I have successfully been able to sort the dataframe based on the field Quality like below: Name Quality Carrot 50 Ginger 50 Raddish 43 Tomato 43 Potato 34 Cabbage 12 Now what I want to do is, add a new column called Position and have the rank at which they exist. The point is, the same rank can be given to two different elements if their quality is the same. Sample Output Dataframe: Name Quality Position Carrot 50 1 Ginger 50 1 Raddish 43 2 Tomato 43 2 Potato 34 3 Cabbage 12 4 Notice how two elements with same quality have the same position while the below elements have +1 position. Also, the dataframe has avg 10 million records How can I do this in Pandas.Dataframe? I Sort my Dataframe like below: df_sort = dataframe.sort_values(by=attribute, ascending=order) df_sort.reset_index(drop=True)
possible better answer: http://stackoverflow.com/a/51270301
tagged with: python
accepted answer: http://stackoverflow.com/a/51270174
type: AnsweredQuestion
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/51270174
type: Question
has answer: http://stackoverflow.com/a/51270301
tagged with: dataframe
tagged with: sorting
has title: Rank the elements in a pandas dataframe
answer count: 2
tagged with: pandas
upvote count: 1

http://stackoverflow.com/a/51259588
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/89519262
answers question: http://stackoverflow.com/q/51223407
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/89519296
has body: I got it working by. removing requests, urllib manually from /usr/local/lib/python2.7/dist-packages and reinstalling requests with sudo easy_install requests then sudo easy_install pip==9.0.1

http://stackoverflow.com/q/51234114
answer count: 1
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89448181
tagged with: python
has comment: http://stackoverflow.com/comment/89448026
tagged with: pose-estimation
tagged with: euler-angles
has answer: http://stackoverflow.com/a/51235278
has body: I am trying to find out the angle of rotation of an object using opencv python. For this purpose I have detected the target then I am able to find out the rotation vector and I am converting it to rotation matrix and from this matrix I am calculating the euler angle. But when I rotate the object in the video then all three angles (x, y, z) changes as well as when I move the the target in the plane even though it shows variation in angles. Kindly suggest me some way to get accurate result. This is the image of target: while True: ret, img = cap.read() gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) ret, corners=cv2.findCirclesGrid(gray,(5,5),None) if ret== True: corners2 = cv2.cornerSubPix(gray,corners,(11,11),(-1,-1),criteria) # Find the rotation and translation vectors. _,_, rvecs, tvecs= cv2.solvePnPRansac(objp, corners2, mtx, dist) dst,_ = cv2.Rodrigues(rvecs) r = dst x = math.atan2(r[2][1],r[2][2]) y = math.atan2(-r[2][0],math.sqrt((r[0][0])*r[0][0])+(r[1][0]*r[1][0])) z= math.atan2(r[1][0],r[0][0]) print("x = ",math.degrees(x)) print("y = "math.degrees(y)) print("z = "math.degrees(z)) Desired Output: x = 5, y = 0, z = 0 Current Output: x = 6.1 , y = 4.7, z = -2.0
type: Question
tagged with: opencv
linked to: http://stackoverflow.com/q/15956124
tagged with: opencv-solvepnp
has title: Getting wrong angle of rotation of target using opencv python
score: 0
has comment: http://stackoverflow.com/comment/89447953

http://stackoverflow.com/a/51214326
upvote count: 10
has comment: http://stackoverflow.com/comment/89410906
downvote count: 0
answers question: http://stackoverflow.com/q/51211055
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/100472548
has body: The minimization methods of SciPy work with real arguments only. But minimization on the complex space Cn amounts to minimization on R2n, the algebra of complex numbers never enters the consideration. Thus, adding two wrappers for conversion from Cn to R2n and back, you can optimize over complex numbers. def real_to_complex(z): # real vector of length 2n -&gt; complex of length n return z[:len(z)//2] + 1j * z[len(z)//2:] def complex_to_real(z): # complex vector of length n -&gt; real of length 2n return np.concatenate((np.real(z), np.imag(z))) sol = minimize(lambda z: fun(real_to_complex(z)), x0=complex_to_real(np.ones(2) + 0j)) print(real_to_complex(sol.x)) # [-7.40376620e-09+1.j -8.77719406e-09+1.j] You mention Jacobian and Hessian... but minimization only makes sense for real-valued functions, and those are never differentiable with respect to complex variables. The Jacobian and Hessian would have to be computed over R2n anyway, treating the real and imaginary parts as separate variables.
score: 10
accepted answer of: http://stackoverflow.com/q/51211055
type: Answer
has comment: http://stackoverflow.com/comment/89409940

http://stackoverflow.com/a/51170408
type: Answer
has comment: http://stackoverflow.com/comment/89323619
score: 2
answers question: http://stackoverflow.com/q/51170279
has comment: http://stackoverflow.com/comment/89325954
has comment: http://stackoverflow.com/comment/89323661
has comment: http://stackoverflow.com/comment/89325845
accepted answer of: http://stackoverflow.com/q/51170279
has body: Here is one solution that matches both ~~...~~ words: (?&lt;=\[TAG\])( \w*)? ~~\w*~~ Look for [TAG] before match. Match one or less words with no ~ Match th ~ word. If there is a word in between it will be matched as well, so you can either group the second word or split the result and use the last index. Here is the example. To encompass also the CONNECT examples just or the same thing: (?&lt;=\[TAG\])( \w*)? ~~\w*~~|(?&lt;=\[CONNECT\])( \w*)? ~~\w*~~ It's the exact the regular expression, but the look-behind needs constant width. If you do not mind matching the TAG you can shorten this to: \[(TAG|CONNECT)\]( \w*)? ~~\w*~~ This is really only needed if you expect there to be more ~~LettersAndDigits~~ words. If not, you can search for that exactly ~~\w*~~ without anything fancy. Final addition Two ensure both TAG and CONNECT appear (CONNECT optionally): \[TAG\]( \w*)?( \[CONNECT\]( \w*)?)? ~~[\w]*~~ Here is the fiddle. To only get the word in this case I would definitly using grouping (), as the match length is variable.
type: AcceptedAnswer
downvote count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/89324540

http://stackoverflow.com/comment/89463201
type: Comment
comment on: http://stackoverflow.com/a/51242007
type: AnswerComment
has text: @RoryDaulton i would preferably like to solve this using string indexing but i don't know how I would go about this. in my code i compare to the previous char
score: 0

http://stackoverflow.com/q/51308478
answer count: 1
has comment: http://stackoverflow.com/comment/89661207
has title: Flask wtforms not passing form - UndefinedError: 'form' is undefined
tagged with: python
has answer: http://stackoverflow.com/a/51343999
type: AnsweredQuestion
tagged with: flask-wtforms
type: Question
accepted answer: http://stackoverflow.com/a/51343999
has comment: http://stackoverflow.com/comment/89658685
score: 0
has body: Ok my first post so I will attempt to be thorough. I believe based on a few other posts that I have this correct, but I continue to receive the undefined error. I want to load how a SelectMultipleField that I fill with values i've pulled from a DB. The user should be able to select the fields they want to include in the result and pass that back to the system. I've included the definition of the class, the route, the .html, and my helper. Entered in __init__.py with fields attribute defined globally class renderselect(Form): elements = SelectMultipleField('Elements', choices = fields) @app.route('//', methods=['GET', 'POST']) def xmlsrcfields(): try: # render the template form = renderselect(request.form) if request.method == 'POST': form.elements.choices = fields form.elements.process(request.form) else: #action to be completed for other cases gc.collect() except Exception as e: return(str(e)) code here The .html is Convertable Elements {% from "_formhelpers.html" import render_field %} {{ render_field(form.elements) }} {% if error %} Error:{{ error }} {% endif %} The helper is {% macro render_field(field) %} {{ field.label }} {% if field.errors %} {% for error in field.errors %} {{ error }} {% endfor %} {% endif %} {% endmacro %} Full traceback as requested: [Thu Jul 12 10:45:14.887982 2018] [core:notice] [pid 11376:tid 1996320768] AH00094: Command line: '/usr/sbin/apache2' [Thu Jul 12 10:45:35.357777 2018] [wsgi:error] [pid 11378:tid 1955591216] [client 192.168.1.75:53613] ERROR:flask.app:Exception on /dashboard/ [GET], referer: http://192.168.1.115/login/ [Thu Jul 12 10:45:35.357894 2018] [wsgi:error] [pid 11378:tid 1955591216] [client 192.168.1.75:53613] Traceback (most recent call last):, referer: http://192.168.1.115/login/ [Thu Jul 12 10:45:35.357917 2018] [wsgi:error] [pid 11378:tid 1955591216] [client 192.168.1.75:53613] File "/usr/local/lib/python3.5/dist-packages/flask/app.py", line 2292, in wsgi_app, referer: http://192.168.1…

http://stackoverflow.com/q/51249525
score: 0
tagged with: linux
has answer: http://stackoverflow.com/a/51249805
tagged with: python
favorite count: 0
type: UnansweredQuestion
upvote count: 1
has body: here's my question: I coded an Application which saves and reads data from an XML-File. This Application is for 5 other people, they can create "Tasks". -> These Tasks will be stored into an XML-File and the other people should be able with their application to get this data. So my idea was to create a Raspberry Server on which the XML-Files will be written on, like a shared Network Drive. So is there a way to create something like this save &amp; privat, so only my friend's application can have access to the Raspberry? Or is this the wrong way to store information? You can also give me just some keywords to look in the internet for it, answers would help me alot :)
downvote count: 1
has title: Private (Raspberry) Data-Server for friends
tagged with: network-programming
type: Question
answer count: 2
tagged with: raspberry-pi
has answer: http://stackoverflow.com/a/51249872

http://stackoverflow.com/comment/89730208
type: AnswerComment
score: 0
type: Comment
has text: You're right, I can't find any answer from internet, I think I need to use raw pymongo queries, anyway thanks.
comment on: http://stackoverflow.com/a/51313548

http://stackoverflow.com/comment/89565980
has text: How do you run the python script? Are you using the command line? Or are you double clicking its icon on the desktop?
comment on: http://stackoverflow.com/q/51293852
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/89599426
type: QuestionComment
comment on: http://stackoverflow.com/q/51310197
has text: pdb seems great, but how can I attach it to a running process? I've tried using the `py-locals` command to no avail, which might mean my python was installed without debug flags.
score: 0
type: Comment

vscode-debugger
type: Tag
tag name: vscode-debugger
tags question: http://stackoverflow.com/q/51244223

http://stackoverflow.com/comment/89431461
has text: https://www.mongodb.com/blog/post/schema-design-for-time-series-data-in-mongodb. Check this out. Try to redesign your schema to something like this if possible.
comment on: http://stackoverflow.com/q/51210367
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89559068
type: QuestionComment
comment on: http://stackoverflow.com/q/51290658
score: 0
type: Comment
has text: `bike.merge(weather)` ?

http://stackoverflow.com/q/51230017
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/51260384
tagged with: http://stackoverflow.com/tag/xlsx
tagged with: python
has body: i'm pretty new to programming so please bear with me if my code is not nice and the answer is too obvious. :) I want to parse an excel file into a directory so i can later access them via key. I won't know how the excel file will be structured before parsing it. So I can't just code it that way to skip a certain empty row since they will be random. For this, i am using Python 3 and OpenPyXl (Read Only). This is my code: from openpyxl import load_workbook import pprint # path to file c = "test.xlsx" wb = load_workbook(filename=c, read_only=True, data_only=True) # key for directory data = {} # list of worksheet names wsname = [] # values in rows per worksheet valuename = [] # took this odd numbers since pprint organizes the numbers weird when 1s and 10s are involved # counter for row k = 9 # counter for column i = 10 # splits name of xlsx - file from .xlsx workbook = c.split(".")[0] data[workbook] = {} for ws in wb.worksheets: # takes worksheet name and parses it into the wsname list wsname.append(ws.title) wsrealname = wsname.pop() worksheet = wsrealname data[workbook][worksheet] = {} for row in ws.rows: k += 1 for cell in row: # reads value per row and column data[workbook][worksheet]["Row: " + str(k) + " Column: " + str(i)] = cell.value i += 1 i = 10 k = 9 pprint.pprint(data) And with this i get output like this: {'test': {'Worksheet1': {'Row: 10 Column: 10': None, 'Row: 10 Column: 11': None, 'Row: 10 Column: 12': None, 'Row: 10 Column: 13': None, 'Row: 11 Column: 10': None, 'Row: 11 Column: 11': 'Test1', 'Row: 11 Column: 12': None, 'Row: 11 Column: 13': None}}} Which is the Output i want, despite the fact they i want to skip in this example the whole Row 10, since all values are None and therefore empty. As mentioned, I don't know when empty rows will occur so I can't just hardcode a certain row to be skipped. In Read Only Mode, if you print(row) there will be just 'EmptyCell' in the row like this: (&lt;EmptyCell&gt;, &lt;EmptyCell&gt;, &lt;EmptyCell&gt;, &lt;Empt…
type: UnansweredQuestion
tagged with: openpyxl
has title: OpenPyXL - ReadOnly: How to skip empty rows without knowing when they occur?
upvote count: 1
has answer: http://stackoverflow.com/a/73335602
type: Question
score: 1
answer count: 2

http://stackoverflow.com/q/51318092
score: 0
answer count: 3
has answer: http://stackoverflow.com/a/72865864
tagged with: multidimensional-array
has body: I am trying to cast my data into an ndarray. Although I get what I want but while testing I am not able to figure out why it gives me this output. I get the output: np.ndarray(shape = (2,1),buffer = np.array([1,2,3,4])) array([[4.24399158e-314], [8.48798317e-314]]) However for this block I am able to cast my random numbers the way I want. def x_mat(n,m): np.random.seed(0) randoms = np.random.normal(size=n*m) print(randoms) rand_mat = np.ndarray(shape = (n,m),buffer = randoms) return(rand_mat) x_mat(5,2) to give: [ 1.76405235 0.40015721 0.97873798 2.2408932 1.86755799 -0.97727788 0.95008842 -0.15135721 -0.10321885 0.4105985 ] array([[ 1.76405235, 0.40015721], [ 0.97873798, 2.2408932 ], [ 1.86755799, -0.97727788], [ 0.95008842, -0.15135721], [-0.10321885, 0.4105985 ]]) If someone can help me understand this behavior. It does the correct thing in the second case but I find the first case as something that is not straight forward. Why is the first case the way it is?
has comment: http://stackoverflow.com/comment/89613082
has comment: http://stackoverflow.com/comment/89674687
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89613556
has comment: http://stackoverflow.com/comment/89675018
type: Question
has title: How to create an n-dimensional array using given data using numpy ndarray
tagged with: numpy
has answer: http://stackoverflow.com/a/51318867
has answer: http://stackoverflow.com/a/51318225
accepted answer: http://stackoverflow.com/a/51318867
possible better answer: http://stackoverflow.com/a/51318225

http://stackoverflow.com/comment/89322596
type: Comment
has text: This doesn't seem to be an issue in my case, same results for tf.div and tf.divide. But I assume this might result in similar issues. As I'm currently struggeling to reproduce the error in a minimal case I assume that's the best I can hope for
type: AnswerComment
comment on: http://stackoverflow.com/a/51169331
score: 0

http://stackoverflow.com/comment/89555372
type: Comment
type: QuestionComment
has text: Please show the code that you used to generate the final output. Presumably you're `print`ing the individual floats?
comment on: http://stackoverflow.com/q/51283194
score: 0

http://stackoverflow.com/comment/89571684
type: Comment
has text: Also, no need to use `float` in py 3. If you do use it, apply to each argument before doing division in py2, or integer truncation will occur before the conversion.
comment on: http://stackoverflow.com/a/51297221
type: AnswerComment
score: 0

http://stackoverflow.com/q/51238905
has comment: http://stackoverflow.com/comment/89457090
has comment: http://stackoverflow.com/comment/89457681
answer count: 1
has comment: http://stackoverflow.com/comment/89457016
has title: Why flask flash is not working?
favorite count: 0
type: UnansweredQuestion
has body: This is my python view code. I have a flash in it. But it wont show any kind of flash front end. @auth.route('/admin/project/add',methods = ['POST', 'GET']) def addproject(): if request.method == 'POST': projectname = request.form['projectname'] c, conn = connection() query = "SELECT Count(id) from projects WHERE project='{}'".format(projectname) c.execute(query) values = c.fetchall conn.close() if (values == 0): flash("success") return render_template('addproject.html') else: flash("Project already exists. Please goto projects page and confirm. If it is and error, please contact devloper.") return render_template('addproject.html') else: return render_template('addproject.html') In template, I have added this : {% with messages = get_flashed_messages() %} {% if messages %} &lt;ul&gt; {% for message in messages %} &lt;li&gt;&lt;{{ message }}&lt;/li&gt; {% endfor %} &lt;/ul&gt; {% endif %} {% endwith %} Can someone help me with the issue? This is also done: from flask import flash, redirect, render_template, url_for, request
score: -3
has comment: http://stackoverflow.com/comment/89456943
tagged with: python
tagged with: python-requests
has comment: http://stackoverflow.com/comment/89457063
has comment: http://stackoverflow.com/comment/89456816
downvote count: 3
has comment: http://stackoverflow.com/comment/89457159
type: Question
has comment: http://stackoverflow.com/comment/89458565
has comment: http://stackoverflow.com/comment/89457335
upvote count: 0
has answer: http://stackoverflow.com/a/51239264
tagged with: flask

http://stackoverflow.com/comment/89523727
type: QuestionComment
type: Comment
score: 1
has text: But you assign the styler to `df`.
comment on: http://stackoverflow.com/q/51272815

http://stackoverflow.com/comment/89544300
has text: I have installed python 2.7.15 and I am running pip through it. Can we have further suggestion?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51277895

http://stackoverflow.com/a/51275507
answers question: http://stackoverflow.com/q/51275114
upvote count: 2
has body: JSONField is a PostgreSQL specific field. It cannot be used with SQLite: https://docs.djangoproject.com/en/2.0/ref/contrib/postgres/fields/#jsonfield There is also support for MySQL via django-mysql package.
downvote count: 1
type: Answer
score: 1

http://stackoverflow.com/comment/89370865
type: QuestionComment
has text: ok. I will learn. I have patched something together with ord() for now. final['is_paid_lead'].map(lambda x:x if x!=x else(ord(x) if x=='\x01' else float(x))).value_counts()
comment on: http://stackoverflow.com/q/51193908
score: 0
type: Comment

http://stackoverflow.com/comment/89504614
type: Comment
comment on: http://stackoverflow.com/q/51260212
has text: The website of PyEphem refers to Stackoverflow, so that's why I ended up here. When I use PyEphem, moon_phase does not seem to work, that's why I asked it in general terms.
score: 0
type: QuestionComment

http://stackoverflow.com/q/51226947
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51226987
accepted answer: http://stackoverflow.com/a/51226987
linked to: http://stackoverflow.com/q/51226423
type: Question
tagged with: dataframe
has title: Copy column from dataframe after matching
score: 0
tagged with: pandas
answer count: 1
has body: I have 2 dataframes and I found common matches based on a column (tld), once match has been found (between a column in source and destination) I to need to copy the value of column in destination dataframe? Dataframe 1: source uuid website company_name tld 0 11 www.facebook.com facebook facebook.com 1 22 www.yahoo.com yahoo inc yahoo.com 2 33 www.google.com Google google.com 3 44 www.cisco.com Cisco cisco.com Dataframe 2: destination id website company_name tld match uuid 0 a www.facebook.com facebook facebook.com False NaN 1 b www.y.com Yahoo Inc y.com False NaN 2 c www.g.com Google g.com False NaN 3 d www.g.com Google Inc g.com False NaN 4 e www.facebook.com Facebook Inc facebook.com False NaN Find matches: destination.loc[destination.tld.isin(source.tld),'match'] = True I need to copy the UUID column from source into the UUID column in the destination dataframe. id website company_name tld match uuid 0 a www.facebook.com facebook facebook.com True 11 1 b www.y.com YahooInc y.com False NaN 2 c www.g.com Google g.com False NaN 3 d www.g.com GoogleInc g.com False NaN 4 e www.facebook.com FacebookInc facebook.com True 11

http://stackoverflow.com/a/51265755
has comment: http://stackoverflow.com/comment/89509641
has comment: http://stackoverflow.com/comment/89509626
score: 20
has comment: http://stackoverflow.com/comment/89509559
accepted answer of: http://stackoverflow.com/q/51265716
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/89511326
has comment: http://stackoverflow.com/comment/89509658
upvote count: 21
downvote count: 1
answers question: http://stackoverflow.com/q/51265716
has body: There is actually, inside string module string.ascii_lowercase string.ascii_uppercase string.digits as well as a few others Each is given as a single string. If you want to convert them to a list, you can simply use list(string.ascii_lowercase + string.ascii_uppercase + string.digits)

http://stackoverflow.com/q/51253078
upvote count: 2
has answer: http://stackoverflow.com/a/51261747
type: Question
accepted answer: http://stackoverflow.com/a/51261747
downvote count: 0
has comment: http://stackoverflow.com/comment/89485170
answer count: 1
linked to: http://stackoverflow.com/q/29158220
has body: I was running this code and it is supposed to be creating a window but it doesn't create any window in Pycharm. I am using Pycharm Community edition with Python 3.6. When I am running this code in IDLE, the window is generated. import tkinter from datetime import date, datetime root = tkinter.Tk() c = tkinter.Canvas(root,width =800, height =768, bg = 'black') c.pack() c.create_text(100,50, anchor = 'w', fill = 'orange', \ font = 'Arial 28 bold underline', text = 'My Countdown calendar')
has comment: http://stackoverflow.com/comment/103130673
favorite count: 0
has title: Tkinter isn't working with Pycharm
duplicate of: http://stackoverflow.com/q/29158220
tagged with: python
score: 2
type: AnsweredQuestion
tagged with: tkinter
tagged with: pycharm
has comment: http://stackoverflow.com/comment/89485883

http://stackoverflow.com/comment/89469925
type: Comment
has text: I'm trying in this function to get the paid users and sort them in a list so I can deal with all notifications functions (many many functions). I'm having the issue of a type that I can't deal with. Thanks a lot for the help man. I think I got something to convert `NoneType` into `Dict`.
comment on: http://stackoverflow.com/a/51244367
type: AnswerComment
score: 0

http://stackoverflow.com/comment/89324432
type: Comment
comment on: http://stackoverflow.com/q/51170549
score: 0
type: QuestionComment
has text: that's not a difference. the logic behind is exactly the same. there are lots of questions in SO regarding the count word problem, it looks very weird to me that not one of them could help you one way or another

http://stackoverflow.com/comment/89402355
has text: The size limit is 16MB. Is this data larger than 16MB? Probably not
score: 1
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51210616

http://stackoverflow.com/comment/89597144
has text: No libraries, those are date functions built into pandas. Follow the link in the post.
comment on: http://stackoverflow.com/a/51310112
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/51209026
downvote count: 0
score: 4
has body: You can stay in Pandas and use its DateOffset objects: &gt;&gt;&gt; from pandas.tseries.offsets import Week &gt;&gt;&gt; df.Date.where(df.Date.dt.weekday == 0, df.Date - Week(weekday=0)) 0 2018-07-30 1 2018-08-20 Name: Date, dtype: datetime64[ns] The trick being that you need to not do the subtraction where the weekday is already Monday (weekday == 0). This says, "in cases where weekday is already zero, do nothing; else, return Monday of that week."
type: Answer
upvote count: 4
answers question: http://stackoverflow.com/q/51208570

http://stackoverflow.com/a/51213116
has comment: http://stackoverflow.com/comment/89410050
type: Answer
score: 1
accepted answer of: http://stackoverflow.com/q/51199698
has body: This works def search_links(driver,link): driver.get(link) items = [item for item in wait.until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, "#main table tr a"))) if "#" not in item.get_attribute("href")] for i in range(0, len(items)): items = driver.find_elements_by_css_selector("#main table tr a") items[i].click() driver.find_element_by_link_text("back to directory").click() i = i+1;
upvote count: 1
answers question: http://stackoverflow.com/q/51199698
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/51270199
accepted answer: http://stackoverflow.com/a/51270721
score: 0
answer count: 2
has title: How to modify last element of a generator in python?
tagged with: python
has answer: http://stackoverflow.com/a/51270721
tagged with: generator
type: AnsweredQuestion
tagged with: conv-neural-network
tagged with: imperative-programming
tagged with: machine-learning
type: Question
has body: I have a generator and I want to modify the last element of the generator. I want to replace the last element with another element. I know how to retrieve the last element, but not how to modify it. What would be the best way to approach this? For more context, this is what I want to do: for child in alexnet.children(): for children_of_child in child.children(): print(children_of_child); My generator object is: children_of_child and for the second child all its children are: Dropout(p=0.5) Linear(in_features=9216, out_features=4096, bias=True) ReLU(inplace) Dropout(p=0.5) Linear(in_features=4096, out_features=4096, bias=True) ReLU(inplace) Linear(in_features=4096, out_features=1000, bias=True) I want to replace the last layer Linear(in_features=4096, out_features=1000, bias=True) with my own regression net. `
possible better answer: http://stackoverflow.com/a/51296170
has answer: http://stackoverflow.com/a/51296170

http://stackoverflow.com/a/51308143
answers question: http://stackoverflow.com/q/51304684
upvote count: 1
type: AcceptedAnswer
type: Answer
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/51304684
has body: If the bin_diffs are all the same, you can do this in constant time by: def get_bin_index2(value, bins): return numpy.rint((value - bins[0])/(bins[1]-bins[0]))

http://stackoverflow.com/q/51251934
accepted answer: http://stackoverflow.com/a/51251988
downvote count: 0
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51252074
has title: Attempting to Convert Time Into an Integer in Python 3
tagged with: datetime
tagged with: python
has answer: http://stackoverflow.com/a/51252079
answer count: 4
has body: I'm extremely new to Python and programming in general, and I've been working at this particular issue for about four hours now. I am trying to convert a time (ex. 12:30) to something usable in an "if" statement. Here's what I've tried so far: time = input("Enter the time the call starts in 24-hour notation:\n").split(":") if time &gt;= 8:30 and time &lt;= 18:00: print("YES") When attempting to perform that, I get an invalid syntax error. When I attempt to convert the time to an integer [callTime = int(time)], I get an error stating that the int() argument must be a string This is just a piece of the entire problem I am working on, but I think I can figure out the rest if I can just get a jumping off point with this issue. Although I don't believe I'm allowed to use datetime on this particular problem; anything would help. EDIT: Corrected int(time)
type: AnsweredQuestion
score: 2
has answer: http://stackoverflow.com/a/51252033
upvote count: 2
type: Question
has comment: http://stackoverflow.com/comment/89482855
possible better answer: http://stackoverflow.com/a/51252079
has answer: http://stackoverflow.com/a/51251988

http://stackoverflow.com/comment/89435658
has text: You should create it in separate page class. See the Page class in my example for how getting it done.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51227840
type: Comment

http://stackoverflow.com/comment/89412544
score: 0
comment on: http://stackoverflow.com/q/51214599
type: Comment
type: QuestionComment
has text: Any help is GREATLY APPREACIATED!

http://stackoverflow.com/q/51308001
has comment: http://stackoverflow.com/comment/89592790
accepted answer: http://stackoverflow.com/a/51308131
tagged with: python
answer count: 1
score: 0
has body: I'm assessing if the project I'm working on is affected by a list of CVEs, including CVE-2016-6580. The vulnerability is, that... A HTTP/2 implementation built using any version of the Python priority library prior to version 1.2.0 could be targeted by a malicious peer by having that peer assign priority information for every possible HTTP/2 stream ID. The priority tree would happily continue to store the priority information for each stream, and would therefore allocate unbounded amounts of memory. Attempting to actually use a tree like this would also cause extremely high CPU usage to maintain the tree. What is the "Python Priority Library"? I duckduckgo'd it, but that project seems to be completely unknown except for being mentioned in that specific CVE. Has anyone some more information on this?
has answer: http://stackoverflow.com/a/51308131
type: AnsweredQuestion
has title: What is the "python priority library"?
type: Question

http://stackoverflow.com/comment/89469418
comment on: http://stackoverflow.com/q/51245394
has text: @jezrael Only files retrieves the list without the file path, just the names. All_files also include the path, for example: //DGMS/Desktop/uploaded\iteration5_tes3_Jun.xlsx
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89491378
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51255951
has text: You haven't fixed the indenting in your code so it's impossible to tell what is part of `thefunction()`. In addition, I can't see anywhere in your code where you actually call that function, or a stack trace showing which line in your code is throwing the error. Please create a [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve) and include a full stack trace of the error.

http://stackoverflow.com/comment/89492131
type: QuestionComment
comment on: http://stackoverflow.com/q/51238079
has text: Agreed. My question is _predicated_ on the assumption that Khronos can be trusted to act on their (very scantily expressed) promise. If they can, then the issue of wrappers and compute strategies is worth raising, yes? If not, the fight moves to figuring out what the hell to do with no OpenCL support on a key platform.
score: 0
type: Comment

feature-extraction
tags question: http://stackoverflow.com/q/51302903
tags question: http://stackoverflow.com/q/51191665
tags question: http://stackoverflow.com/q/51307275
tag name: feature-extraction
tags question: http://stackoverflow.com/q/51173801
tags question: http://stackoverflow.com/q/51181170
type: Tag

http://stackoverflow.com/q/51229804
upvote count: 1
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51229894
score: 0
downvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/51229894
has comment: http://stackoverflow.com/comment/89439199
answer count: 2
tagged with: infinite-loop
has body: List item # To put values in list till user want #comparing value entered with the ascii value ofenter # key , if enter then come out of infinite loop # why break is not breaking out on enter press #if value is not enter_key thn put this value in list x=1 lis=[] while x == 1 : var = str(input()) if var == chr(10): break lis.append(var) print("i m free now from infinite loop") print(lis)
has title: why Break is not Breaking out of loop for this small piece of code?
has comment: http://stackoverflow.com/comment/89439144
tagged with: break
has comment: http://stackoverflow.com/comment/89439571
possible better answer: http://stackoverflow.com/a/51229880
favorite count: 0
has answer: http://stackoverflow.com/a/51229880
tagged with: python-3.x

http://stackoverflow.com/q/51211174
score: 1
tagged with: http://stackoverflow.com/tag/json
type: Question
tagged with: aws-api-gateway
tagged with: amazon-web-services
upvote count: 1
has title: JSONObject[\"body\"] not found at AWS ApiGateway
answer count: 1
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/51368565
accepted answer: http://stackoverflow.com/a/51368565
type: AnsweredQuestion
has body: I'm developing an API Gateway to get data (image) from a sensor and send to DynamoDB at AWS. I already have the endpoint and API key. However, I get the following error when testing the API: Request: /?image=12345 Status: Latency: ms Response Body { "cause": "JSONObject[\"body\"] not found.", "logref": "12345-11d8-888888", "message": "" } IAM roles and policies are ok. The Python code posts via requests the following payload payload={"image": [1,2,3,4,5]} Given that: requests.posts(API_URL,files=payload,headers={'api-key':'12345abcd'}) My Body Mapping Template is: {"body" : $input.json('$')} But this Body Mapping is generating an alert in Request Body of GET (inappropriate request validator). As you can see in the following image, I'm getting 4xx errors for all API Requests. DynamoDB is not receiving the payload. Can someone give me a slight idea of the possible causes for this?
downvote count: 0

http://stackoverflow.com/q/51275627
has comment: http://stackoverflow.com/comment/89561702
tagged with: matplotlib
linked to: http://stackoverflow.com/q/3151524
has comment: http://stackoverflow.com/comment/89535969
has comment: http://stackoverflow.com/comment/89561402
type: Question
tagged with: numpy
linked to: http://stackoverflow.com/q/33466231
downvote count: 0
linked to: http://stackoverflow.com/q/7821518
has comment: http://stackoverflow.com/comment/89529251
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/89562623
score: 2
answer count: 0
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89566590
has comment: http://stackoverflow.com/comment/89561320
has title: Matplotlib: save 3D volume plot to numpy array
has body: Someone posted how to convert 2D Matplotlib images to a np.array. I'd like to do the same for a 3D Matplotlib plot. To be clear, I am not asking to save a 2D "screenshot" of fig.canvas as an array, but rather a raster of the 3D lines as an array. Why? My raw data is a list of node id's, their (x,y,z) coordinates, the node id's they are connected to, and the radius of those connections. I used mplot3d to connect these dots with lines, and now I want to use these 3D structures for machine vision research. For that, the data needs to be in a numpy array. I want to avoid writing a function to connect the nodes when a tool already exists.
tagged with: mplot3d
tagged with: conv-neural-network

http://stackoverflow.com/a/51201338
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/51190271
score: 1
has body: For Python 2 your code has a race condition that can leak the inheritable write end of the pipe that's created by the T1 thread into the ping.exe process that's created by the T2 thread. readline on a pipe won't return until the pipe closes, which requires all handles for the write end to be closed. In this case, you can avoid the race condition by passing close_fds=True to Popen when creating the ping.exe process. This prevents it from inheriting inheritable handles, including the pipe handle from the overlapping call in the T1 thread. In general, prior to Python 3.7, if you need to support concurrent Popen calls with overridden standard handles, then you'll need to wrap Popen with a function that synchronizes the call by acquiring a lock beforehand. Unfortunately this makes the Popen call a bottleneck in a multi-threaded process, but there's no simple alternative. Background In Unix, the close_fds parameter of Popen applies in the child process after fork. If it's true, then all non-standard file descriptors will be closed before calling exec, even those without the FD_CLOEXEC flag set. It does not, however, close the standard file descriptors -- stdin (0), stdout (1), and stderr (2). In Windows, a handle can be flagged as inheritable (i.e. HANDLE_FLAG_INHERIT). By default, handles are not inheritable. If CreateProcess is called with bInheritHandles as true, then all inheritable handles are inherited by the child. Popen passes this as not close_fds, i.e. not closing file descriptors means to inherit handles [*]. In Windows, the stdin, stdout, and stderr parameters of Popen are used to explicitly set the child's standard handles in STARTUPINFO (i.e. hStdInput, hStdOutput, hStdError). If the standard handles aren't overridden explicitly, the parent's standard handles are implicitly inherited by console applications (e.g. python.exe), but not GUI applications (e.g. pythonw.exe). If set explicitly, the handles must be made inheritable, and bInheritHandles (i.e. not cl…
answers question: http://stackoverflow.com/q/51190271
upvote count: 1
type: AcceptedAnswer

http://stackoverflow.com/q/51272894
tagged with: max
favorite count: 0
has answer: http://stackoverflow.com/a/51272949
tagged with: python
type: AnsweredQuestion
score: 3
has body: Given a numpy array such as a = [0, 3, 2, 4, 0, 2, 3, 1, 1, 6, 2], is there a simple way to record the maximum value for every 3 values? The length of the array may not be a multiple of 3. In this case, the result should be b = [3, 4, 3, 6]. I thought of something along the lines of b = [max(a[k:k+3]) for k in range(0, len(a), 3) but it doesn't take into account the values after the last multiple of 3 (which it should). I've also thought of rearranging the numpy array such that it has 3*n rows, and taking the maxima along the proper axis using the numpy module, but, again, I'm not sure how to deal with the values after the last multiple of 3.
has answer: http://stackoverflow.com/a/51273178
type: Question
tagged with: numpy
possible better answer: http://stackoverflow.com/a/51272949
tagged with: arrays
downvote count: 0
has answer: http://stackoverflow.com/a/51273114
accepted answer: http://stackoverflow.com/a/51273114
has title: Finding (and recording) the maximum values of slices of a numpy array
upvote count: 3
answer count: 3

http://stackoverflow.com/comment/89675018
comment on: http://stackoverflow.com/q/51318092
score: 0
has text: `np.matrix` doesn't add any computational power; never did. Its `*` multiply is matrix multiplication, but so is `np.dot` and `matmul` (and the `@` operator). It's just as easy to make 2d `ndarray` - just use the `np.array([[1,2,3],[4,5,6]])` syntax or `reshape`. You rarely need `ndarray`.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51230654
has answer: http://stackoverflow.com/a/51231773
tagged with: machine-learning
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51231773
has body: I am very new in machine learning using python and would appreciate any help with the following problem. I am trying to run MLPRegressor for list of different hidden neuron numbers (6 values) and for each selected neuron number I want the training data to be shuffled three times, i.e. three scores for each neuron number. The following code works fine and returns 18 scores (6*3). However I feel it is not the efficient way of solving the problem, since it is running almost an hour. I have tried using GridSearchCV(), but I don't know how to control shuffling of the training data (3 times for each hidden neuron numbers). Can anybody suggest a better (faster) way of solving this? from sklearn.neural_network import MLPRegressor from sklearn.model_selection import cross_val_score from sklearn.utils import shuffle n=3 # how many times to shuffle the training data nhn_range=[8,10,12,14,16,18] # number of hidden neurons nhn_scores = [] for nhn in nhn_range: mlp = MLPRegressor(hidden_layer_sizes=(nhn,), activation='tanh', solver='adam', shuffle=False, random_state=42, max_iter=20000, momentum=0.7, early_stopping=True, validation_fraction=0.15) for _ in range(n): df_train = shuffle(df_train) score = np.sqrt(-cross_val_score(mlp, df_train[feature_cols], df_train[response_cols], cv=5, scoring='neg_mean_squared_error')).mean() nhn_scores.append(score) The code returns a list of scores. How can I get a simple data frame with 3 rows (for each shuffling) and 6 columns (for each hidden neuron number). Thanks in advance
type: Question
upvote count: 4
downvote count: 0
tagged with: scikit-learn
score: 4
has title: Hyperparameter optimization of MLPRegressor in scikit-learn
answer count: 1
tagged with: python
favorite count: 0

http://stackoverflow.com/comment/89475178
score: 0
has text: Are you sure you need multiplication, I answered with `np.dot` but your result is not what you get with dot product.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51247958

http://stackoverflow.com/comment/89520516
score: 0
type: Comment
has text: you think there will be more effective way to reformat it?? I updated more text data in my actual post above, which would fail these checks. I am thinking of maybe breaking at ! mark but not successful yet.
comment on: http://stackoverflow.com/a/51251289
type: AnswerComment

http://stackoverflow.com/q/51290313
score: 0
has comment: http://stackoverflow.com/comment/89564546
has comment: http://stackoverflow.com/comment/89558862
has title: Return YouTube-DL Error As Python Error
linked to: http://stackoverflow.com/q/1319615
has comment: http://stackoverflow.com/comment/89558835
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89558378
tagged with: python
answer count: 0
type: Question
has comment: http://stackoverflow.com/comment/89558346
tagged with: youtube-dl
has body: I am trying to download video using YouTube-dl in python, But sometime the video i am trying to download is copyrighted or deleted, So i get an error message from YouTube-dl: [Example] Example: Downloading embed webpage [Example] Example: Downloading f webpage ERROR: Example: File not found is there anyway i can make the error stop my python program ?

http://stackoverflow.com/comment/89603002
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51225118
type: AnswerComment
has text: not as far as I know... I installed per the instructions.

http://stackoverflow.com/q/51273509
has body: I have a Profile class, which extends the User class, and I would like to allow every profile to be able to bookmark other user profiles. I've set up the following: class Profile(models.Model): # some fields e.g. name, email bookmarked_profiles = models.ManyToManyField("self") Now, I'm a bit confused, for example, how would I 'bookmark' new profiles for a given profile instance? E.g. something like # add new bookmark for profile instance p = Profile.objects.get(pk=1) profiles_to_bookmark = Profile.objects.all() p.bookmarked_profiles = profiles_to_bookmark I would also like to know the number of bookmarked profiles e.g. p.bookmarked_profiles.count()
has title: ManyToMany on Self Model: How to add new instances to this relation
possible better answer: http://stackoverflow.com/a/51273652
accepted answer: http://stackoverflow.com/a/51273541
tagged with: python
has answer: http://stackoverflow.com/a/51273652
type: AnsweredQuestion
tagged with: django
type: Question
tagged with: django-models
has answer: http://stackoverflow.com/a/51273541
score: 0
answer count: 2

http://stackoverflow.com/q/51248973
has body: I've been trying to write binary search recursively. When I do this using the list[:] syntax I don't get the intended results with several errors coming up or not getting the correct values. def binary_search(arr, val): left = 0 right = len(arr)-1 mid = (left + right)//2 #Go through the array if (val == arr[mid]): return mid #Check right side of arr if (val &gt; arr[mid]): return binary_search(arr[mid+1:], val) #Check left side of arr return binary_search(arr[:mid], val) EDIT: Example inputs and outputs arr1 =[] for i in range(10): arr1.append(i) for i in range(10): print(binary_search(arr1,i)) I expect to get something like '0,1,2,3,4,5,6,7,8,9' but get '0,1,0,0,4,None ,None,2,0,0'
has comment: http://stackoverflow.com/comment/89477216
possible better answer: http://stackoverflow.com/a/51249336
has answer: http://stackoverflow.com/a/51249345
has comment: http://stackoverflow.com/comment/89476993
tagged with: python
has answer: http://stackoverflow.com/a/51249336
has title: Recursive binary search python
has comment: http://stackoverflow.com/comment/89476826
has comment: http://stackoverflow.com/comment/89477244
type: AnsweredQuestion
upvote count: 1
downvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/51249345
has comment: http://stackoverflow.com/comment/89476862
tagged with: binary-search
score: 0
answer count: 3
has answer: http://stackoverflow.com/a/74061660
favorite count: 0

http://stackoverflow.com/comment/89553821
comment on: http://stackoverflow.com/q/51287361
score: 0
type: Comment
type: QuestionComment
has text: And everything works fine when I'm subscribed to 1 order book + 2 tickers for example. But when I subscribe to more channels, I receive updates with huge delays(I know that by checking order books on website and comparing them to my order books). And my in-memory data is outdated

http://stackoverflow.com/comment/89483492
comment on: http://stackoverflow.com/q/51252214
type: QuestionComment
type: Comment
has text: @abarnert I poorly described the lines at the top of the file where the imports occur as headers
score: 0

http://stackoverflow.com/comment/89567036
type: QuestionComment
type: Comment
has text: If you don't know how to answer the last part, if you're on Python 3, try this: `with open(filename,'rb') as f: print(f.read())` and then show us the `b'…whatever…'` that gets printed out.
comment on: http://stackoverflow.com/q/51294678
score: 0

http://stackoverflow.com/q/51298834
upvote count: 2
tagged with: vectorization
type: Question
tagged with: performance
accepted answer: http://stackoverflow.com/a/51298884
has body: Say I have a numpy array: my_array = np.random.rand(100). and another array of indices: ind_array = ([35, 58, 77]) What would be the fastest way to calculate the standard deviation of the 10 values around each ind_array index in my_array? (i.e. np.std(my_array[30:40]), np.std(my_array[53:63]), np.std(my_array[72:82]) ) It is obviously possible to do using a for-loop, but I'm afraid it will be too slow. Thanks
tagged with: numpy
answer count: 1
downvote count: 0
favorite count: 0
has title: Multiple calculations of standard deviation on array subsets by index
tagged with: python
score: 2
has answer: http://stackoverflow.com/a/51298884
type: AnsweredQuestion

http://stackoverflow.com/comment/89586611
type: Comment
has text: Yes, that will give you the global maximum.
score: 0
comment on: http://stackoverflow.com/a/51299546
type: AnswerComment

http://stackoverflow.com/comment/89464847
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/51242622
has text: That looks like your machine doesn't have a proper Internet connection, as it can't resolve the name.
type: Comment

http://stackoverflow.com/q/51251703
score: 0
answer count: 1
linked to: http://stackoverflow.com/q/3635131
has comment: http://stackoverflow.com/comment/89482340
type: UnansweredQuestion
has body: I'm trying to connect through Paramiko to an external SFTP and passing an encrypted config file for the credentials. When attempting to connect with the following, I get an error for the exception client.close that states AttributeError: 'Nonetype' object has not attribute 'close': client = None try: client = paramiko.Transport(hostname, port) client.connect(username=username, password=password) except Exception as e: client.close() return 'Cannot connect to SFTP server: ' + str(e.args[-1]), [] # Go sftp = paramiko.SFTPClient.from_transport(client)
tagged with: ssh
tagged with: python
has answer: http://stackoverflow.com/a/51251732
type: Question
has title: Python Paramiko, Attribute Error 'Nonetype' on close when trying to connect
has comment: http://stackoverflow.com/comment/89482450
tagged with: paramiko

http://stackoverflow.com/q/51170939
accepted answer: http://stackoverflow.com/a/51171175
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/89325029
type: Question
score: 3
possible better answer: http://stackoverflow.com/a/51171034
tagged with: dataframe
has body: I have multiple rows in my dataframe and a column called 'name'. I want to groupby 'name' and remove every item in the group, if any row has an empty column (either, nan, none or an empty string). How can I achieve this? Input name c0 c1 c2 193556 INFO 1 273142 OMN 1 1 1 256278 OMN 1 1 1 41165 INFO 1 1 1 339649 INFO 1 1 1 Output name c0 c1 c2 273142 OMN 1 1 1 256278 OMN 1 1 1
has comment: http://stackoverflow.com/comment/89324623
has answer: http://stackoverflow.com/a/51171034
upvote count: 3
answer count: 2
tagged with: pandas-groupby
tagged with: pandas
has comment: http://stackoverflow.com/comment/89324794
favorite count: 0
has title: Remove rows if group contains an empty column
tagged with: python
has answer: http://stackoverflow.com/a/51171175

http://stackoverflow.com/comment/89462009
type: Comment
type: QuestionComment
score: 0
has text: Why don't you create a function in the second script and call it in the first script?
comment on: http://stackoverflow.com/q/51241635

http://stackoverflow.com/comment/89570299
type: QuestionComment
comment on: http://stackoverflow.com/q/51296430
score: 0
has text: Use `thread.isAlive()` to check if a thread is still running or not by yourself. https://docs.python.org/3/library/threading.html#threading.Thread.is_alive
type: Comment

http://stackoverflow.com/comment/89520619
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51268991
score: 0
has text: @Parfait, I think its relevant because that table did not previously exist in the database

http://stackoverflow.com/a/51242667
score: 0
type: Answer
has body: If you do not want to use the csv module, you can reproduce the behavious of DictReader like this: &gt;&gt;&gt; data = """name,phone,monthlysalary,age ... Peter,1234567,100000,28 ... John,22345,200000,30 ... Mary,32345,300000,40""" ... &gt;&gt;&gt; lines = iter(data.splitlines()) &gt;&gt;&gt; head = next(lines).split(",") &gt;&gt;&gt; [dict(zip(head, line.split(","))) for line in lines] [{'age': '28', 'monthlysalary': '100000', 'name': 'Peter', 'phone': '1234567'}, {'age': '30', 'monthlysalary': '200000', 'name': 'John', 'phone': '22345'}, {'age': '40', 'monthlysalary': '300000', 'name': 'Mary', 'phone': '32345'}] If instead you want a one-liner for the result format from your update, try this: &gt;&gt;&gt; {x[0]: x[1:] for x in (line.split(",") for line in data.splitlines()[1:])} {'John': ['22345', '200000', '30'], 'Mary': ['32345', '300000', '40'], 'Peter': ['1234567', '100000', '28']} However, both the memory consumption of importing the csv module and the benefits of one-liners are probably overrated.
answers question: http://stackoverflow.com/q/51208937

http://stackoverflow.com/q/51304941
has title: sniffing http packets using scapy
answer count: 1
has answer: http://stackoverflow.com/a/51305626
has body: Im using python 2.7.15, scapy and scapy-http on windows. I want to sniff all the http packets and extract the html pages that were sent. This is the code Im using: from scapy.all import * import scapy_http.http def printPacket(packet): if packet.haslayer('HTTP'): print '='*50 print packet.show() sniff(prn=printPacket) but from some reason it only captures some of the http packets(when I use the browser I dont see any packets) and I dont see any html code in the ones that it does print.
type: UnansweredQuestion
tagged with: python
score: 0
tagged with: scapy
tagged with: http
type: Question

http://stackoverflow.com/comment/89526168
type: Comment
has text: Are you sure objects with this valu exists. Kindly doblecheck in shell or in admin because that should return the object
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51273481

http://stackoverflow.com/comment/89612126
type: Comment
comment on: http://stackoverflow.com/q/51317313
score: 1
has text: If you could tell what module are they part of? Are they part of scikit?
type: QuestionComment

http://stackoverflow.com/a/51195679
downvote count: 0
has comment: http://stackoverflow.com/comment/89374345
answers question: http://stackoverflow.com/q/51191533
has comment: http://stackoverflow.com/comment/89374160
has comment: http://stackoverflow.com/comment/89374280
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/89374068
score: 1
has body: user_id=1 count = Blog.objects.filter(author_id=user_id).count() You will get the count of Blog instances related to User with id=1 Update aggregation = Blog.objects.values('blog').annotate(count=Count('author'))
has comment: http://stackoverflow.com/comment/89373342
has comment: http://stackoverflow.com/comment/89373875

http://stackoverflow.com/comment/89538939
type: AnswerComment
score: 0
type: Comment
has text: I don't think that'll work with 3.7 since it's not yet in the main repositories.
comment on: http://stackoverflow.com/a/51280444

http://stackoverflow.com/q/51214952
type: Question
has title: python (boolean type) and (integer) will become a integer type
score: 0
answer count: 1
linked to: http://stackoverflow.com/q/37888620
linked to: http://stackoverflow.com/q/18195322
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89411135
duplicate of: http://stackoverflow.com/q/18195322
has comment: http://stackoverflow.com/comment/89411001
has comment: http://stackoverflow.com/comment/89411345
has answer: http://stackoverflow.com/a/51215010
has body: I find (boolean type) and (integer) will become a integer in Python3. What conversion happens in this line of code? flag=True print(flag and 2) Output:2

http://stackoverflow.com/comment/89578086
has text: So it's probably just doing `your_function(**params)`, which means `def your_function(**kwargs)` should work just fine. Also, why can't you simply write those function signatures accordingly by hand? Presumably each of these functions is unique anyway, so why the need to generate them?
comment on: http://stackoverflow.com/q/51299787
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/comment/89566495
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51293578
has text: Awesome, bless your soul.
type: AnswerComment

http://stackoverflow.com/a/51268026
upvote count: 5
score: 5
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/51253661
answers question: http://stackoverflow.com/q/51253661
has body: You could use the Axes.set_title method: import matplotlib.pyplot as plt import numpy as np number = 100 number_ticks = 9 x_input = np.array([np.linspace(-1.,3.,100),]*number) y_input = np.array([np.arange(0.,100.,1.),]*number).transpose() output = np.array([np.linspace(0.,1.0,100),]*number) bounds=np.linspace(0.0,1.0,number_ticks) cntr1 = plt.contourf(x_input, y_input, output, vmin = 0.0, vmax = 1.0, levels = bounds) cbar1 = plt.colorbar() cbar1.ax.set_title(r"$\bf{title}$") cbar1.ax.set_ylabel(r"$\bf{y_label}$", labelpad=20, rotation=270) plt.show() I think ColorbarBase.set_label is equivalent to cbar1.ax.set_ylabel. And Axes.set_label is to specify a legend entry. image

http://stackoverflow.com/comment/89385886
has text: I don’t understand why. In the Selenium-controlled browser, if I open developer tools, I can find the element. Why can’t Selenium?
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51200800
type: Comment

http://stackoverflow.com/a/51248482
answers question: http://stackoverflow.com/q/51248360
accepted answer of: http://stackoverflow.com/q/51248360
has body: if you want a fast solution, use a list comprehension. q_set = set(question_words) df['ques_word'] = [ 1 if w.split(None, 1)[0] in q_set else 0 for w in df.sentence ] df sentence label ques_word 0 you will not forget this movie 0 0 1 will the novel ever die 1 1 2 why we drink alcohol 1 1 3 did trump win the election 1 1 4 ambiance is perfect 0 0
score: 2
type: AcceptedAnswer
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/89476875
upvote count: 2

http://stackoverflow.com/comment/89402894
has text: Also, please, write a descriptive title for your post! What the heck does "Tensorflow Eager FP etc rate" mean?
type: Comment
comment on: http://stackoverflow.com/q/51210536
type: QuestionComment
score: 0

http://stackoverflow.com/comment/89559743
comment on: http://stackoverflow.com/a/51290948
score: 0
type: AnswerComment
type: Comment
has text: What is the reason for a constant bias? Why does it make sense to have a constant bias if performance is not important?

http://stackoverflow.com/q/51315494
has comment: http://stackoverflow.com/comment/89607804
type: Question
has title: how return value from def __del__
has comment: http://stackoverflow.com/comment/89614827
has comment: http://stackoverflow.com/comment/89607555
has body: I am learning to program with Python and while doing so I thought of how the def __del__ would return a value, so I created a class Test that just have a str method and tried to return it with __del__. At first the script was fine but I don't know how to store it while working in IDLE: &gt;&gt;&gt; class Test: def __init__(self,name): self.name=name def __del__(self): ma=self.name print ("works ??") return ma def __repr__(self): return "name:({})".format(self.name)
accepted answer: http://stackoverflow.com/a/51315779
score: 0
upvote count: 1
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/89607483
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51315779
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/89643627
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51295472
has text: I have been trying to fix the code for click function but nothing is working. I have tried puting a root.after(100, click) after pyautogui.hotkey("ctrlleft"), I don't get any error but code in general doesn't execute. Any more suggestion?
type: AnswerComment

http://stackoverflow.com/comment/89571790
type: AnswerComment
type: Comment
has text: No problem. If this helped then please accept the answer
comment on: http://stackoverflow.com/a/51297293
score: 0

http://stackoverflow.com/a/51214741
has comment: http://stackoverflow.com/comment/89410652
type: Answer
downvote count: 0
has body: Simply use regex to grab the integer after 'Pages: '. import re print(re.findall(r'^Pages:\s+(\d+)', info.stdout.read().decode('utf-8'), flags=re.MULTILINE)[0])
accepted answer of: http://stackoverflow.com/q/51214677
answers question: http://stackoverflow.com/q/51214677
has comment: http://stackoverflow.com/comment/89410567
score: 1
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89410621

http://stackoverflow.com/q/51247716
has body: I'm working on creating the mean per distinct date for the column "avgPrice". The data is a panel that contains the below columns for different "typeID's". Where only typeID 18 is shown, there are 59 typeID's in the entire dataset. A sample of the data looks like the following: typeID date lowPrice highPrice avgPrice volume orders 0 18 2003-10-01 14.0 14.0 14.0 284846 84 1 18 2003-10-02 14.0 16.0 15.0 533151 64 2 18 2003-10-03 15.0 15.0 15.0 247490 85 3 18 2003-10-04 15.0 15.0 15.0 367424 117 4 18 2003-10-05 14.0 14.0 14.0 923101 112 The length of the dataframe is 24574045 and is thus quite large. What I'm trying to do is create an aggregated avgPrice column that takes the unweighted mean of the avgPrice for every typeID per date. The following code works but is extremely slow in its execution time: dfm = pd.DataFrame() total = len(set(df["date"])) # check execution time for i, j in enumerate(set(df["date"])): if i % 10 == 0: print(i / total * 100) # check execution time dfm["date"] = j dfm["avgPrice"] = df.loc[df["date"] == j]["avgPrice"].mean() This will return a new dataframe with the unweighted mean of the avgPrice over all typeID's with corresponding date. However, considering the length of the data at hand this takes a very long time to execute. Is there any way I could speed up this process, e.g. vectorize the for-loop?
answer count: 0
has comment: http://stackoverflow.com/comment/89475015
has title: Vectorize Mean over a Column by Date within a DataFrame
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89474580
has comment: http://stackoverflow.com/comment/89475277
has comment: http://stackoverflow.com/comment/89474819
type: Question
has comment: http://stackoverflow.com/comment/89475133
has comment: http://stackoverflow.com/comment/89474702
has comment: http://stackoverflow.com/comment/89475216
score: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/89475082

http://stackoverflow.com/comment/89635583
score: 0
has text: Hey @juniorcl ! I've updated my answer to explain a bit more and provided a full example link. You can manipulate each channel separately with this technique as you desire. If this is correct then let me know and mark it so!
type: AnswerComment
comment on: http://stackoverflow.com/a/51308418
type: Comment

http://stackoverflow.com/a/51307406
upvote count: 2
type: Answer
has body: This is already answered by Daniel Salinas (imsplitbit) on lunchpad at bug in jenkins lib Close this bug, it appears pip was installing jenkins 1.0.2 not python-jenkins 0.2 which is actually used. These two modules use the same module namespace so it may be valuable to change that some how or even just add python-jenkins to the pip-requires so that this isn't an issue to begin with.
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/51306869

http://stackoverflow.com/q/51291906
tagged with: pyinstaller
type: UnansweredQuestion
tagged with: windows
tagged with: python
answer count: 0
type: Question
score: 1
has title: Pick up directory with pyinstaller
upvote count: 1
has body: I have made a small programm with Python 3 and Qt-Designer using Pyqt5. the programm should open a pdf file which is located on a directory on my pc and another exe file, which is also on my pc. I'm using in the code: os.startfile("D:\Python_files\MA\Programm\K_file\dist\K_D\K_D.exe") os.startfile("D:\Python_files\MA\Programm\Help.pdf") then I used pyinstaller to make it standalone app. The problem is that pyinstaller does not pick up those two file (pdf and exe). So when somebodyelse download the app on thier pc, it wont work because the pdf and the exe are missing. How to fix this? I'm using this command in pyinstaller pyinstaller --onefile --icon="if_icon_64682.ico" --clean ProgV_1_6_Final.py
downvote count: 0
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/comment/89371743
comment on: http://stackoverflow.com/a/51194532
type: AnswerComment
type: Comment
score: 1
has text: @lenik You are benchmarking the creation of a massive NumPy array from a list. This is not _at all_ productive. I agree it is unclear from their question whether they are really using NumPy or not, but benchmarking the creation of NumPy arrays doesn't have any significance.

http://stackoverflow.com/a/51316300
accepted answer of: http://stackoverflow.com/q/51311709
score: 1
has body: Inspired by John Morris's commentary, i found the answer to my question in Numpy Array to base64 and back to Numpy Array post. If anyone has the same doubt, here is the solution: Client code: # client.py import base64 from urllib.parse import urlencode from urllib.request import Request, urlopen import cv2 img = cv2.imread(image_file) img_b64 = base64.b64encode(img) data = {'image': img_b64, 'shape': img.shape} data = urlencode(data).encode("utf-8") req = Request(service_url, data) response = urlopen(req) print(response.read().decode('utf-8')) Views code: # service/app/views.py import ast import base64 import numpy as np from django.http import HttpResponse, JsonResponse from django.views.decorators.csrf import csrf_exempt @csrf_exempt def process_image(request): if request.method == 'POST': shape = ast.literal_eval(request.POST.get('shape')) buffer = base64.b64decode(request.POST.get('image')) # Reconstruct the image img = np.frombuffer(buffer, dtype=np.uint8).reshape(shape) # Process image return JsonResponse({'result': 'Hello'}) Thank you all!
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51311709
type: Answer
upvote count: 1

http://stackoverflow.com/comment/89401089
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51209909
type: AnswerComment
has text: Can you explain why yours worked great while the other's didn't ?For simple application both work but since the code got complicated only this way worked out.

http://stackoverflow.com/a/51284189
downvote count: 2
type: Answer
upvote count: 3
has comment: http://stackoverflow.com/comment/89547521
has comment: http://stackoverflow.com/comment/89546177
has comment: http://stackoverflow.com/comment/89571568
answers question: http://stackoverflow.com/q/51284059
has comment: http://stackoverflow.com/comment/89546970
has body: You have either the option to use locals as Marco pointed out or use eval like - for i in range(1, 11): print eval("v{}".format(i)) But a better solution to this problem is to use list or dictionary
score: 1

http://stackoverflow.com/a/51303224
has comment: http://stackoverflow.com/comment/89584329
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51302477
type: Answer
answers question: http://stackoverflow.com/q/51302477
has comment: http://stackoverflow.com/comment/89584438
has comment: http://stackoverflow.com/comment/89584083
score: 1
has comment: http://stackoverflow.com/comment/89583963
upvote count: 1
has body: You need aggregate all necessary columns, e.g. by first: Data_aggr = Data.groupby('Customer_ID').agg({'SalesAmount':[min,sum], 'ProductCost':['mean',max],'Product_ID':'first' }) Data_aggr.columns = ["_".join(x) for x in Data_aggr.columns.ravel()] Data_aggr = Data_aggr.rename(columns={'Product_ID_first':'Product_ID'}).reset_index() print (Data_aggr) Customer_ID SalesAmount_min SalesAmount_sum ProductCost_mean \ 0 1 12.34 24.68 12.34 1 2 13.55 27.10 13.55 2 3 34.00 68.00 34.00 3 4 19.15 38.30 19.15 4 5 13.22 26.44 13.22 ProductCost_max Product_ID 0 12.34 A 1 13.55 D 2 34.00 C 3 19.15 A 4 13.22 E Or grouping by multiple columns, but output is different: Data_aggr = Data.groupby(['Customer_ID','Product_ID']).agg({'SalesAmount':[min,sum], 'ProductCost':['mean',max]}) Data_aggr.columns = ["_".join(x) for x in Data_aggr.columns.ravel()] Data_aggr = Data_aggr.reset_index() print (Data_aggr) Customer_ID Product_ID SalesAmount_min SalesAmount_sum ProductCost_mean \ 0 1 A 12.34 12.34 12.34 1 1 B 12.34 12.34 12.34 2 2 D 13.55 27.10 13.55 3 3 C 34.00 68.00 34.00 4 4 A 19.15 19.15 19.15 5 4 B 19.15 19.15 19.15 6 5 E 13.22 26.44 13.22 ProductCost_max 0 12.34 1 12.34 2 13.55 3 34.00 4 19.15 5 19.15 6 13.22
has comment: http://stackoverflow.com/comment/89584010

http://stackoverflow.com/comment/89390013
comment on: http://stackoverflow.com/a/51204285
type: Comment
has text: I would argue that appending a zero is misleading and incorrect. It will cause negative values in inputlist to be disregarded, and will always have a zero regardless of whether inputlist contains zero.
score: 0
type: AnswerComment

http://stackoverflow.com/q/51206564
linked to: http://stackoverflow.com/q/15455048
linked to: http://stackoverflow.com/q/14546178
has comment: http://stackoverflow.com/comment/89397437
has comment: http://stackoverflow.com/comment/89394870
score: 0
has comment: http://stackoverflow.com/comment/89394434
has comment: http://stackoverflow.com/comment/89395531
duplicate of: http://stackoverflow.com/q/14546178
tagged with: memory-management
answer count: 0
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/19473185
tagged with: python
has comment: http://stackoverflow.com/comment/89398594
has comment: http://stackoverflow.com/comment/89397157
has comment: http://stackoverflow.com/comment/89394786
has comment: http://stackoverflow.com/comment/89394084
has body: I am just curious to know about that in python if we set any variable equals to None. Will it free up the space allocated for it? Also if we use del function Will it free up the space allocated to the variable? Is it just like free function in C++?
has title: Python: Freeing up the allocated memory
has comment: http://stackoverflow.com/comment/89398489
has comment: http://stackoverflow.com/comment/89394156
tagged with: memory
type: Question
has comment: http://stackoverflow.com/comment/89396816

concurrency
tag name: concurrency
tags question: http://stackoverflow.com/q/51239251
tags question: http://stackoverflow.com/q/51243539
tags question: http://stackoverflow.com/q/51254050
type: Tag
tags question: http://stackoverflow.com/q/51251824

http://stackoverflow.com/a/51229384
answers question: http://stackoverflow.com/q/51229170
has comment: http://stackoverflow.com/comment/89438976
score: 0
has comment: http://stackoverflow.com/comment/89438938
has comment: http://stackoverflow.com/comment/89439184
type: Answer
has comment: http://stackoverflow.com/comment/89438735
has comment: http://stackoverflow.com/comment/89438832
has comment: http://stackoverflow.com/comment/89438461
has comment: http://stackoverflow.com/comment/89439032
has comment: http://stackoverflow.com/comment/89439300
has comment: http://stackoverflow.com/comment/89438373
has body: You are converting your image to a string object. How do you expect to crop a string? Just avoid using image_to_string. from PIL import Image from PIL import ImageOps img = Image.open(filename) crop = ImageOps.crop(img, (10, 50, 35, 55)) This should work
has comment: http://stackoverflow.com/comment/89438588
has comment: http://stackoverflow.com/comment/89438509

http://stackoverflow.com/comment/89491954
has text: @patwie I believe I do need a wrapper. I started this with base TF but was having a mountain of issues that I just could not get resolved for the life of me, even though I knew exactly what the issues were. I switched to tflearn on a whim and, without changing anything about the model, it worked the first time. It's good to know they do require a session, but does it need to be explicitly created or does tflearn start one itself in the background?
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51251640

http://stackoverflow.com/a/51354832
has comment: http://stackoverflow.com/comment/89764803
has body: Celery tasks should have proper names. When running from django, the task name is MyApp.celery_tasks.add which is why celery worker not able to run it. But from terminal when your imported using from celery_tasks import *, task name is celery_tasks.add which is why it is working correctly. You can change config based on environment variable. kombu.transport.django Adding this not necessary. This is related to Python 2/3. See this docs for more info. If you want task results after the task is completed, it should be stored somewhere. So backend is needed for this. If you don't want to retrieve results, you don't need this.
has comment: http://stackoverflow.com/comment/89748850
answers question: http://stackoverflow.com/q/51322207
score: 0
type: Answer

http://stackoverflow.com/comment/89384759
type: QuestionComment
score: 0
has text: Well, similarly to this yes. Because the path is retrieved dynamically, I had to use `'"{}"'.format(path)`, or alternatively, `'"'+path+'"'`. This lead me to believe this could be a VLC path configuration problem, but I don't want to rule out that it could be solved if my code was revised.
comment on: http://stackoverflow.com/q/51201534
type: Comment

multiprocessing
tags question: http://stackoverflow.com/q/51291460
tags question: http://stackoverflow.com/q/51244960
tags question: http://stackoverflow.com/q/51211869
tags question: http://stackoverflow.com/q/51199599
tags question: http://stackoverflow.com/q/51281612
tags question: http://stackoverflow.com/q/51205868
tags question: http://stackoverflow.com/q/51301596
tags question: http://stackoverflow.com/q/51174146
tags question: http://stackoverflow.com/q/51243539
tags question: http://stackoverflow.com/q/51287943
tags question: http://stackoverflow.com/q/51210305
tags question: http://stackoverflow.com/q/51200019
tags question: http://stackoverflow.com/q/51186167
tags question: http://stackoverflow.com/q/51256738
tags question: http://stackoverflow.com/q/51289862
tags question: http://stackoverflow.com/q/51178100
tags question: http://stackoverflow.com/q/51171145
tags question: http://stackoverflow.com/q/51295229
tags question: http://stackoverflow.com/q/51262274
tags question: http://stackoverflow.com/q/51305831
tags question: http://stackoverflow.com/q/51301474
tags question: http://stackoverflow.com/q/51228679
tags question: http://stackoverflow.com/q/51168462
tags question: http://stackoverflow.com/q/51272951
type: Tag
tags question: http://stackoverflow.com/q/51237129
tags question: http://stackoverflow.com/q/51278519
tags question: http://stackoverflow.com/q/51200824
tags question: http://stackoverflow.com/q/51194214
tags question: http://stackoverflow.com/q/51239214
tag name: multiprocessing
tags question: http://stackoverflow.com/q/51322818

http://stackoverflow.com/a/51263864
type: Answer
score: 1
upvote count: 1
has body: Well yes of course that's what functions are for: def get_input(prompt, validate=validate) while True: res = raw_input(prompt) try: res = validate(res): return res except ValidationError as e: print("invalid value: {}".format(e)) Note that I changed the validate API so that it's now supposed to raise a ValidationError instead of returning a boolean. This allow to have an error message explaining what's wrong... Also it returns the validated value, which allows to typecast it if needed (if for example you want an int or float) or to actually return whatever you want as the final result.
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51263436
downvote count: 0
answers question: http://stackoverflow.com/q/51263436

http://stackoverflow.com/comment/102002045
has text: it work for me i upgrade my django project to 1.11 and i try to makemigrations and it give this errors and i try to change the code in to the one above and i try to migrate again and it work for so try it.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/57783953
type: Comment

http://stackoverflow.com/comment/89402031
type: AnswerComment
has text: Thanks for your answer. This is a step further, but still gives wrong results in some cases. With your answer: `reversed_slice(numpy.s_[20:10:-2],len(a))` gives `slice(8, 21, 2)` which corresponds to `array([ 8, 10, 12, 14, 16, 18, 20])`.
type: Comment
comment on: http://stackoverflow.com/a/51210193
score: 0

http://stackoverflow.com/comment/89545485
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/51283927
score: 0
has text: For some strange reason even if I run it as you suggested with if value== "True" it always comes back false...or skips to the else statement

http://stackoverflow.com/comment/89380537
score: 0
comment on: http://stackoverflow.com/q/51199331
type: QuestionComment
type: Comment
has text: The questions are different. The other question is describing a slightly different sorting.

http://stackoverflow.com/a/75515031
has body: pip install -U scikit-learn This works for me.
answers question: http://stackoverflow.com/q/51314845
score: 0
type: Answer

http://stackoverflow.com/q/51272280
upvote count: 1
has answer: http://stackoverflow.com/a/51272328
has comment: http://stackoverflow.com/comment/89522977
answer count: 1
has title: Share the list of lists in multiprocessing
tagged with: python
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89523059
downvote count: 0
score: 1
tagged with: python-multiprocessing
type: Question
has body: I want to increase the efficiency of my code. One intensive part of my code is to append elements to a list of lists. Basically, I want to do something as follows, import multiprocessing import time def update_val(L, i): L.append(i**2) return L if __name__ == "__main__": N = 1000000 x_reg = [list(range(10)) for i in range(N)] y_reg = [list(range(10)) for i in range(N)] z_reg = [list(range(10)) for i in range(N)] "Regular Call" start = time.time() [x_reg[i].append(i**2) for i in range(N)] stat_reg =time.time() - start "Multiprocessing" num_cores = multiprocessing.cpu_count() # equals 4 in my case pool = multiprocessing.Pool(num_cores) start = time.time() y_reg = pool.starmap(update_val,[(y_reg[i],i) for i in range(N)]) pool.close() pool.join() stat_val =time.time() - start print("Regular: %g "%(stat_reg)) print("Mult.: %g "%(stat_val)) The output is: Regular: 0.387984 Mult.: 2.54244 I believe the reason is related to how multiprocessing works; It needs to make a copy of the original list, do staff and return it. This should be the main reason why multiprocessing is very slow in my case. Here is my question: 1- How should I perform the same function to z_reg while sharing it between processes? 2- Does it enhance the performance. 3- Any other idea how to attach something to every sub-list in z_reg?

http://stackoverflow.com/comment/89344634
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51180903
has text: Have you tried using the ttk combobox?

http://stackoverflow.com/comment/89524784
has text: @delsim It doesn't print anything when I try that
comment on: http://stackoverflow.com/q/51273206
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/89365956
has text: Thankyou, this was helpful. I'm not familiar with virtual machines but it sounds exactly like what I need.
type: AnswerComment
comment on: http://stackoverflow.com/a/51192075
score: 0
type: Comment

http://stackoverflow.com/a/51230419
downvote count: 1
type: Answer
has body: I think its happen because of Unicode Transformation. 1.Adding the following line to the top of your .py file: # -*- coding: utf-8 -*- OR 2.use str.encode('utf8') function ex : `site = site.encode('utf8')`
score: 1
answers question: http://stackoverflow.com/q/51230307
upvote count: 2

http://stackoverflow.com/comment/89556352
has text: What are you asking? It's not clear. Please see [mcve]
score: 1
comment on: http://stackoverflow.com/q/51289229
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/89337659
type: QuestionComment
has text: Also, note that I rolled back your question; as I said, chaning the code in your question invalidates all the answers. If you want to provide updated, do so _below_ your original code.
comment on: http://stackoverflow.com/q/51174983
score: 0
type: Comment

http://stackoverflow.com/q/51174275
has body: I am beginner in programming/scripting and stuck with the following problem. I searched a lot on stack overflow and the net but could not resolve the issue. The detailed situation I face is described below in case somebody has a completely different approach to solve the problem. Is there a way to use an alias (that I call go_to) with multiple commands but where I can pass an argument to only the first command1? I want to execute goto argument from something like alias go_to='command1 ; command2'. command1 should evaluate a path based on the argument and command2 should cd to there. Situation in detail I'm executing calculations on a computer facility that uses the slurm batch system to queue and start jobs. Using the command squeue slurm shows all running and pending jobs including their Job_ID. Using sjobs <Job_ID> a bunch of information are displayed, including the path where the calculation was started. My goal is to go to that directory. Of course I can do that: squeue to see all jobs and their Job_ID, Pick one of the Job_IDs, sjobs <Job_ID> to display information, Search with my eyes for the line that includes the path, copy the path and cd path to arrive where I want to go. That is a lengthy procedure if you want to check multiple calculations. Therefore, I want to use a alias and/or a bash or python script (let's call it go_to) so that I simply need to type go_to <Job_ID> to arrive at the directory. So far, using a python script I achieved to do python script.py <Job_ID> to call sjobs and extract the path from it (but piping sjobs to grep and sed would also be possible). I've already read Why doesn't "cd" work in a shell script? and Location of cd executable and understood that os.chdir(path) or subprocess.call(['cd',path]) will only change directories inside the python subshell and that as soon as the script is finished I will end up in the same directory where I started the script. From what I understand only an alias can bring me to path. Therefore, my id…
has comment: http://stackoverflow.com/comment/89331417
type: Question
has answer: http://stackoverflow.com/a/51175997
linked to: http://stackoverflow.com/q/255414
has comment: http://stackoverflow.com/comment/89333574
linked to: http://stackoverflow.com/q/3741148
has comment: http://stackoverflow.com/comment/89334482
has comment: http://stackoverflow.com/comment/89333344
tagged with: bash
downvote count: 0
answer count: 1
tagged with: alias
favorite count: 0
tagged with: slurm
accepted answer: http://stackoverflow.com/a/51175997
upvote count: 2
has comment: http://stackoverflow.com/comment/89333451
tagged with: python
has title: Having an alias with multiple commands, is it possible to pass an argument to the first command?
score: 2
type: AnsweredQuestion

http://stackoverflow.com/comment/89434300
comment on: http://stackoverflow.com/q/51227148
type: Comment
type: QuestionComment
has text: What have you tried ? Use str.split() then use `import re` to find if it's a link or no.
score: 0

http://stackoverflow.com/comment/89510061
comment on: http://stackoverflow.com/q/51265595
type: Comment
has text: `error: <class 'socket.error'>, [Errno 13] Permission denied: file: /usr/lib64/python2.7/socket.py line: 228`
type: QuestionComment
score: 0

http://stackoverflow.com/q/51302668
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89582552
tagged with: pandas-groupby
tagged with: pandas
has body: how can I create a data frame containing all the combinations a column(eg. Usage) value for a specific group (eg. userid) in a data frame using pandas python? for example: if this is the data frame I have, user-id serial-number value day 1 2 10 1 1 2 20 2 1 2 30 3 1 2 40 4 1 2 50 5 1 2 60 6 1 2 70 7 1 2 80 8 1 2 90 9 1 2 100 10 1 2 200 11 1 2 300 12 1 2 400 13 2 3 11 1 2 3 12 2 2 3 13 3 2 3 14 4 2 3 15 5 2 3 16 6 2 3 17 7 2 3 18 8 I need the resultant dataframe to be: (combinations for the first value in the "value" column) user-id serial-number value value1 day 1 2 10 10 1 1 2 10 20 1 1 2 10 30 1 1 2 10 40 1 1 2 10 50 1 1 2 10 60 1 1 2 10 70 1 1 2 10 80 1 1 2 10 90 1 1 2 10 100 1 1 2 10 200 1 1 2 10 300 1 1 2 10 400 1 . . . 2 3 11 11 1 2 3 11 12 1 2 3 11 13 1 2 3 11 14 1 2 3 11 15 1 2 3 11 16 1 2 3 11 17 1 2 3 11 18 1 similarly i want to do it for all the values in the "value" column. Any Suggestions?
favorite count: 0
score: -1
has comment: http://stackoverflow.com/comment/89615355
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/89582194
has comment: http://stackoverflow.com/comment/89598082
has comment: http://stackoverflow.com/comment/89584368
answer count: 1
downvote count: 1
has title: how can I create a data frame containing all the combinations of a column?pandas python?
upvote count: 0
has answer: http://stackoverflow.com/a/51324461

http://stackoverflow.com/comment/89501874
score: 0
type: Comment
type: QuestionComment
has text: Share HTML sample for the same. Also check if `table` located inside an `iframe` (`... ... ... ... ...`)
comment on: http://stackoverflow.com/q/51261145

http://stackoverflow.com/comment/89342387
score: 0
type: Comment
type: QuestionComment
has text: What have you attempted?
comment on: http://stackoverflow.com/q/51179796

http://stackoverflow.com/comment/89449068
type: QuestionComment
comment on: http://stackoverflow.com/q/51235094
has text: If you're looking to just have the message box you can simply create your own message box with the TK window
score: 0
type: Comment

http://stackoverflow.com/q/51273441
has answer: http://stackoverflow.com/a/51273528
type: Question
upvote count: 1
has title: Write a function that takes a dict as its input and returns the number of vowels
downvote count: 7
answer count: 1
score: -6
favorite count: 0
has body: I have been trying to solve this question a bit now and I am currently stumped. Can someone show me a step by step solution or a way to go about this question? Write a function that takes a dict as its input and returns the number of vowels contained within the dict's string keys. For this exercise, you can consider a vowel to be the letters "a", "e", "i", "o", or "u". I suppose an example would be count_dict_vowels({"Here": "Now", "When": "Python"}) == 3
tagged with: python-3.x
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89525717
tagged with: python
has comment: http://stackoverflow.com/comment/89525922
has comment: http://stackoverflow.com/comment/89525185

http://stackoverflow.com/comment/89564170
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51293188
has text: Remember that multiplying a list multiplies the object pointer.

http://stackoverflow.com/comment/89499467
has text: I'm not able to import anything from the package itself. Please check included image if it helps.
type: QuestionComment
comment on: http://stackoverflow.com/q/51260177
type: Comment
score: 0

http://stackoverflow.com/q/51223869
has answer: http://stackoverflow.com/a/51223892
type: Question
has comment: http://stackoverflow.com/comment/89428103
score: -1
has title: What is the difference between these two List in Python?
downvote count: 4
answer count: 1
has body: I have two Lists in my program list1 and list2 which looks like the following: list1 = ['ABC', 'ABD', 'ABE', 'ABF', 'ABG', 'ABH', 'ABI', ...] list2 = [('A', 'B', 'C'), ('A', 'B', 'D'), ('A', 'B', 'E'), ('A', 'B', 'F'), ('A', 'B', 'G'), ('A', 'B', 'I'), ...] Both the Lists are 2D because they return the same result on the same operation. list1[0][1] returns 'B' list2[0][1] also returns 'B' What is the difference between list1 and list2 if they return the same result? How do I convert list2 in the format of list1? Thank you.
accepted answer: http://stackoverflow.com/a/51223892
favorite count: 0
has comment: http://stackoverflow.com/comment/89428084
has comment: http://stackoverflow.com/comment/89428706
tagged with: python
type: AnsweredQuestion
upvote count: 3

http://stackoverflow.com/q/51294143
tagged with: google-oauth
has title: How to use JSON string as credentials instead of filepath for Python with Google API
answer count: 1
has answer: http://stackoverflow.com/a/51308280
has body: I'm looking for a way to build a Google Credentials object and access my Google Sheets spreadsheet without having to reference another file containing my client_secret.json data. This feels like it should be quite easy to do, I just want to be able to copy the JSON into my python script and access it that way, but I haven't been able to find a way to do it. According to https://oauth2client.readthedocs.io/en/latest/source/oauth2client.file.html it seems like the only way to use the current method is with a filepath, but again if the file literally only contains JSON, it seems like there should be a way of just putting the JSON in my python script and using it from there. Listed below is how I currently get the values from my json file. SCOPES = 'https://www.googleapis.com/auth/spreadsheets.readonly' store = file.Storage('credentials.json') creds = store.get() if not creds or creds.invalid: flow = client.flow_from_clientsecrets('client_secret.json', SCOPES) creds = tools.run_flow(flow, store) service = build('sheets', 'v4', http=creds.authorize(Http())) SPREADSHEET_ID = ID RANGE_NAME = sheetName + '!A2:D' result = service.spreadsheets().values().get(spreadsheetId=SPREADSHEET_ID, range=RANGE_NAME).execute()
score: 0
tagged with: oauth2client
tagged with: google-api-python-client
tagged with: python
tagged with: google-api
type: UnansweredQuestion
type: Question
has comment: http://stackoverflow.com/comment/89566283
has comment: http://stackoverflow.com/comment/89565823

http://stackoverflow.com/q/51182051
has answer: http://stackoverflow.com/a/52541929
type: UnansweredQuestion
score: 1
has body: I am running something like this def searchCassanadra(self): # Iterate over every pokemon for x in self.pokemon_list: # Query query = session.execute("SELECT pokemon_id FROM ds_pokedex.pokemon where pokemon_id=" + repr(x)) The above code is returning me &lt;class 'cassandra.cluster.ResultSet'&gt; How can I check if this ResultSet is empty or filled from the Cassandra? I am coding in the python. Sorry for the newbie question. If I try to do the if query.current_rows: print 'y' else: print 'n' I am getting this error ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). Thanks for your help.
upvote count: 1
has comment: http://stackoverflow.com/comment/89349111
type: Question
tagged with: pandas
tagged with: datastax
answer count: 1
downvote count: 0
linked to: http://stackoverflow.com/q/37946458
linked to: http://stackoverflow.com/q/41247345
favorite count: 0
tagged with: cassandra
has title: Check if Cassandra's resultSet is empty or not (Python)
tagged with: python
has comment: http://stackoverflow.com/comment/89349151

http://stackoverflow.com/a/51195297
has comment: http://stackoverflow.com/comment/89372368
type: Answer
answers question: http://stackoverflow.com/q/51194328
has comment: http://stackoverflow.com/comment/89375817
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/89372231
has body: I am not sure that you are aware or not but you just load fixtures as below: from django.test import TestCase from myapp.models import Animal class AnimalTestCase(TestCase): fixtures = ['mammals.json', 'birds'] def setUp(self): # Test definitions as before. call_setup_methods() def test_fluffy_animals(self): # A test that uses the fixtures. call_some_test_code() example from the docs So you don't need to write GlobalSetup with call_command as you did in your current example which is leading to load the fixtures twice. because the method is already called in setUpClass(refer this link)
downvote count: 0

http://stackoverflow.com/comment/89515390
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51268204
has text: Thanks for your comment. Do have a suggestion as to how better present the matter in the form of a question? I think that tkinter behavior in this case is counter intuitive. Why give a weight to non existent columns? I think a more sensible behavior would be to check which rows or columns have any widgets in them and only assign weights to those rows/columns.
score: 0

http://stackoverflow.com/comment/89403203
score: 0
type: Comment
has text: After using np.array I get another error but is seems to have solved the original error.--->`self.z2_error = self.o_delta.dot(self.W2) # z2 error: how much our hidden layer weights contributed to output error ValueError: shapes (1,) and (2,) not aligned: 1 (dim 0) != 2 (dim 0)`
comment on: http://stackoverflow.com/a/51210738
type: AnswerComment

http://stackoverflow.com/comment/89540119
has text: Good idea, but the same script works perfectly fine on another Windows machine. The problem must be in the Outlook configuration. Interesting: every time I create a new Outlook profile the script manages to update with the latest email.
comment on: http://stackoverflow.com/a/51277226
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/51203427
score: 0
has body: Just use apply function for DataFrame df['Com'] = df.apply(lambda x: x['A']+' '+x['B'], axis=1) df Out[25]: A B Com 0 Foo A Foo A 1 Bar B Bar B 2 Foo C Foo C
type: Answer
answers question: http://stackoverflow.com/q/51203351

http://stackoverflow.com/a/51219063
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/51219008
answers question: http://stackoverflow.com/q/51219008
has body: If you read the docs for open, that second parameter that you're passing a "w" to is the mode: mode is an optional string that specifies the mode in which the file is opened. It defaults to 'r' which means open for reading in text mode. Other common values are 'w' for writing (truncating the file if it already exists), 'x' for exclusive creation and 'a' for appending… And then there's a handy chart of all of the mode characters, which reiterates the same information: 'w': open for writing, truncating the file first ... 'a': open for writing, appending to the end of the file if it exists So, just use "a" instead of "w", and Python will add your new line to the end of the file, instead of truncating the file to nothing and then adding your new line to that now-empty file. It's probably worth knowing that this is very closely based on the behavior of the fopen function from C and POSIX—which many other languages have also copied. So, in almost any language you run into, if there's a w mode for writing that overwrites the file, there's probably also an a mode for appending.
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/a/51235028
has body: Don't ever use this construction: for i in range(nrows): do_stuff(df[column][i]) It is inefficient. You almost never want to use a for-loop over a data-frame, but if you must, use pd.Dataframe.itertuples: &gt;&gt;&gt; df = pd.DataFrame({'a':[1,2,3],'b':[3,4,5]}) &gt;&gt;&gt; for row in df.itertuples(): ... print("the index", row.Index) ... print("sum of row", row.a + row.b) ... the index 0 sum of row 4 the index 1 sum of row 6 the index 2 sum of row 8 Note, it now doesn't matter if the index changes: &gt;&gt;&gt; df = df.iloc[[2,0,1]] &gt;&gt;&gt; df a b 2 3 5 0 1 3 1 2 4 &gt;&gt;&gt; for row in df.itertuples(): ... print("the index", row.Index) ... print("sum of row", row.a + row.b) ... the index 2 sum of row 8 the index 0 sum of row 4 the index 1 sum of row 6 Finally, you could have always just reset your index, suppose: &gt;&gt;&gt; df.drop(0, axis=0, inplace=True) &gt;&gt;&gt; df a b 2 3 5 1 2 4 Now, just use: &gt;&gt;&gt; df.reset_index() index a b 0 2 3 5 1 1 2 4 And use the drop parameter to not include the old index as a column: &gt;&gt;&gt; df.reset_index(drop=True) a b 0 3 5 1 2 4
score: 1
upvote count: 1
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51234988
answers question: http://stackoverflow.com/q/51234988
type: Answer

http://stackoverflow.com/a/51272243
has body: why not use multiprocessing from multiprocessing import Pool pool = Pool(processes=1) result = pool.apply_async(model.save) to spawn a new process to save your model. you can pass whatever parameters like a path using other arguments in apply_async aswell.
answers question: http://stackoverflow.com/q/51272154
score: 0
type: Answer

http://stackoverflow.com/comment/89598872
type: Comment
type: QuestionComment
has text: @iDrwish Read Documentation for sets that would help to build up basics here: https://docs.python.org/2/library/sets.html
score: 0
comment on: http://stackoverflow.com/q/51310599

http://stackoverflow.com/q/51273579
has body: I have a simple query that runs perfectly using python on windows. import pandas as pd ... # database connection omitted pd.read_sql("select * from table where time_stamp &gt;= '2018-6-11'", conn) But on my Linux machine, it gives an error Traceback (most recent call last): File "extract_data.py", line 16, in &lt;module&gt; df = pd.read_sql(extract, conn) File "/home/jm/anaconda3/envs/s1/lib/python3.6/site-packages/pandas/io/sql.py", line 381, in read_sql chunksize=chunksize) File "/home/jm/anaconda3/envs/s1/lib/python3.6/site-packages/pandas/io/sql.py", line 1422, in read_query data = self._fetchall_as_list(cursor) File "/home/jm/anaconda3/envs/s1/lib/python3.6/site-packages/pandas/io/sql.py", line 1431, in _fetchall_as_list result = cur.fetchall() ValueError: month must be in 1..12 Any idea what could cause this? I've updated anaconda and pandas and pyodbc which is what I'm using to make the connection on both machines. I've also made sure the connection to the database is working great on both machines. It only has problems on that date string, which it converts easily to a timestamp when running on windows (I assume that's how it works, either way it works flawlessly). Does linux somehow do handle sql differently? maybe pyodbc is different for linux? I've even tried converting it to a timestamp first and it still doesn't work. Maybe its complaining about something being returned in my query? But the query takes a while to run and this fails immediately. It is pointed to the save exact DB2 Server on both machines. Everything I can think of is the same between the machines.
tagged with: timestamp
answer count: 0
has comment: http://stackoverflow.com/comment/89525422
has comment: http://stackoverflow.com/comment/89525385
has comment: http://stackoverflow.com/comment/89525714
type: Question
has comment: http://stackoverflow.com/comment/89526035
has comment: http://stackoverflow.com/comment/89525501
tagged with: db2
score: 0
tagged with: linux
has comment: http://stackoverflow.com/comment/89525712
has comment: http://stackoverflow.com/comment/89527858
has comment: http://stackoverflow.com/comment/89525969
has comment: http://stackoverflow.com/comment/89525990
type: UnansweredQuestion
has title: python on linux can't understand sql timestamps
tagged with: python
tagged with: pyodbc
has comment: http://stackoverflow.com/comment/89525544

http://stackoverflow.com/comment/137302462
comment on: http://stackoverflow.com/a/51249569
score: 0
type: AnswerComment
type: Comment
has text: @JuanR: That shouldn't be happening, inheritance (and `super`) should work the same regardless of where each type is defined. I'd guess there's something more complicated going on, that's throwing off the `super()` mechanics. Maybe your imported class uses a weird metaclass or something.

http://stackoverflow.com/comment/89327551
comment on: http://stackoverflow.com/q/51171827
has text: I tried with the scipy to find lag and it worked thank you but on comparing the size of z(correlation value ) and lag value, doesn't match.lag showing 82 and length of z showing 119
score: 0
type: Comment
type: QuestionComment

mapreduce
tags question: http://stackoverflow.com/q/51215295
type: Tag
tag name: mapreduce

http://stackoverflow.com/comment/89598770
comment on: http://stackoverflow.com/a/51275729
score: 0
type: AnswerComment
has text: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/174900/discussion-between-dietrich-epp-and-abarnert).
type: Comment

http://stackoverflow.com/q/51201263
has comment: http://stackoverflow.com/comment/89383904
answer count: 0
type: Question
linked to: http://stackoverflow.com/q/1251692
has body: I'm tasked with making a function which looks at all of its children and aggregates all class variables of its children into one dictionary. Basically: BaseClass(object): #implementation classA(BaseClass): self.var1 = 4 self.var2 = "hi" classB (BaseClass): self.var1 = [23,32] self.var2 = ("Hello","World") I'd like for a function in BaseClass to basically aggregate all class variables of its children, and make it into a dictionary that looks somewhat like this: {"classA":{"var1":4,"var2":"hi"},"classB":{"var1":[23,32],"var2":("Hello","World")}} This is being used for data storage at the exit of a program -- Python 2.7 Thanks so much for your help
score: 0
has title: how can a parent class aggregate all variables from its children?
has comment: http://stackoverflow.com/comment/89384133
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89384207

http://stackoverflow.com/comment/89380042
type: QuestionComment
type: Comment
has text: @Harv Ipan this works. Thanks. I added `reset_index()` and even nicer. `[df[i].reset_index(drop=True) for i in df.columns.unique()]`
score: 1
comment on: http://stackoverflow.com/q/51199056

http://stackoverflow.com/comment/89547853
comment on: http://stackoverflow.com/q/51273784
has text: Thanks @AlexandrTatarinov . You're right, I think I'm just misunderstanding a lot of the key concepts. From what I understand, my views are where any additional functionality to my api should be placed (filtering the query and writing additional functions). When I say "user posts something" I mean that they will fill in an EmailField in the browsable api, and the address typed in there is the address the message will send to. The data the user will send is the message specified in the function. I used `detail=True` and `action` in an attempt to follow a setup I saw on the DRF documentation.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51315794
has comment: http://stackoverflow.com/comment/89676575
has answer: http://stackoverflow.com/a/51324435
accepted answer: http://stackoverflow.com/a/51324435
answer count: 1
has comment: http://stackoverflow.com/comment/89608343
has body: I have the following data inputs that I am reading via pandas. I want to take the cell 'Month Ending .....' and drop into a newly formed 'Date' Column and append the two input files together into one dataframe. This is what I have tried so far... import pandas as pd import glob import os ### List Source Files That I need to Import### path = os.getcwd() files = os.listdir(path) ### Loading Files by Variable ### data = pd.DataFrame() for files in glob.glob('../Sales_Master_Data/Sales_Data/* customer *.xls'): #searches for customer .xls files in the folder data = pd.read_excel(files,'sheet1',skiprows=0).fillna(method='ffill')#reads all files in df date = data.columns[4] # This is where the date value is located data['Date'] = date # Assigns date value to new ['Date'] column df = df.append(data) # all files are appended together df.to_csv('Output.csv') Unfortunately it produces the output below. All cols beginning with 'Month' need to be merged into 1 column and called ['Sales Qty'] and I'm also having trouble tiding up the column headers so that they are uniform Ideal output would look like this.....
linked to: http://stackoverflow.com/q/27420263
has comment: http://stackoverflow.com/comment/89608163
score: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/89608312
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89609978
has title: How to assign column variable 'Date' with Date value from a column header in Pandas
type: Question
duplicate of: http://stackoverflow.com/q/27420263

http://stackoverflow.com/q/51241104
has comment: http://stackoverflow.com/comment/89470410
has title: python script to list EBS snapshots created based on select date
has body: I have searched through StackOverflow and found most examples were using Boto, which is almost deprecated. I am trying to list EBS snapshots created in the last 24 hours (eg. yesterday) using Boto 3. import boto3 import json import dateutil from datetime import date, timedelta import collections def lambda_handler(event, context): source_region = 'ap-southeast-1' snapshot_client = boto3.client('ec2', source_region) semalam = (date.today() - timedelta(1), '%Y-%m-%d') ebsAllSnapshots = snapshot_client.describe_snapshots(OwnerIds=['self']) for snaplist in ebsAllSnapshots['Snapshots']: strdate = snaplist['StartTime'].date() if (strdate &lt;= semalam): print snaplist['SnapshotId'] The error I got is TypeError: can't compare datetime.date to tuple the variable strdate did return list of snapshot creation dates, for example: 2018-06-10 2018-06-10 2018-06-10
type: Question
answer count: 1
tagged with: boto3
tagged with: amazon-web-services
score: 0
has answer: http://stackoverflow.com/a/51246022
tagged with: snapshot
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/a/52069746
has body: The second term in the equation should be x_{n-1} . As you know floating point errors propagate and lead to errors. One quick solution is to use higher precision arithmetic like so: from decimal import * getcontext().prec = 100 def diff(n): c = Decimal(1) b = Decimal(-1)/Decimal(5) a = Decimal(0) coeff1 = Decimal(14) / Decimal(5) coeff2 = Decimal(3) / Decimal(5) for i in range(n): a = coeff1 * b + coeff2 * c b, c = a, b return a Which should be good for the first 100 values. This doesn't solve the issue of how to do this with floating point precision. Most likely some transformation of the problem (such as taking the exponent of both sides) might allow you to do this. However finding the right transformation is tricky.
answers question: http://stackoverflow.com/q/51241103
score: 0
type: Answer

http://stackoverflow.com/comment/89530749
score: 0
has text: @lukayl My apologies, I see what you mean. Please see my recent edit, as I fixed this, and also provided a way to write the data to a `csv` file.
comment on: http://stackoverflow.com/a/51273056
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/134000286
comment on: http://stackoverflow.com/q/51282423
has text: Are you using the same `y_pred` array in both cases?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51216194
has answer: http://stackoverflow.com/a/51217429
linked to: http://stackoverflow.com/q/4616061
tagged with: error-suppression
accepted answer: http://stackoverflow.com/a/51217429
duplicate of: http://stackoverflow.com/q/4616061
has comment: http://stackoverflow.com/comment/89418732
tagged with: ubuntu
has body: I have a very old program (from the late 80s) written in C++ and I somehow managed to get it running on Ubuntu 16.04 64Bit. Even if it produces an error at the end, the results are okay. Since it seems to be impossible to compile that program nowadays (it makes use of a very old version of the proprietary library NAG) I cant fix the problem in the source code and have to live with the error. I need to run this program in a loop and the error message completely clutters my screen and prevents me from seeing relevant messages. I tried to suppress the message by using calls like ./hubbard.exc 2&gt;/dev/null and variants of it like &amp;&gt;/dev/null, but the error message is still printed to screen. So I conclude, that this error message is neither printed to stdout nor to stderr. I would be grateful for any help to suppress this error message or for an advise on how to suppres all output of the shell! In case that it would not be possible to suppress this error message in the shell it would also help me to find a way to run the program from a Python3 script (using subprocess or os.system) without that the error is printed to screen. The error message Im talking about looks as follows: *** Error in `./hubbard.exc': corrupted size vs. prev_size: 0x0a350a98 *** ======= Backtrace: ========= /lib/i386-linux-gnu/libc.so.6(+0x67377)[0xf7d5e377] /lib/i386-linux-gnu/libc.so.6(+0x6d2f7)[0xf7d642f7] /lib/i386-linux-gnu/libc.so.6(+0x6e48a)[0xf7d6548a] ./libstdc++-libc6.2-2.so.3(__builtin_vec_delete+0x24)[0xf7f5ea44] ./hubbard.exc[0x80b4ad4] ./hubbard.exc[0x808e141] ./hubbard.exc[0x805352d] ./hubbard.exc[0x805257f] ./hubbard.exc[0x80527c5] ./hubbard.exc(fwrite+0xc7)[0x8049623] ./hubbard.exc[0x80b7779] /lib/ld-linux.so.2(+0xfa87)[0xf7f89a87] /lib/i386-linux-gnu/libc.so.6(+0x2e993)[0xf7d25993] ======= Memory map: ======== 08048000-080bd000 r-xp 00000000 08:16 15208152 /mnt/data/Downloads/Ausfuehrbar/hubbard.exc 080bd000-080cb000 rwxp 00074000 08:16 15208152 /mnt/data/Downloads/Ausfu…
has comment: http://stackoverflow.com/comment/89416518
tagged with: bash
type: AnsweredQuestion
score: 3
has title: How to suppress the error message: "Error in `./hubbard.exc': corrupted size vs. prev_size"?
downvote count: 0
favorite count: 0
type: Question
answer count: 2
tagged with: python
possible better answer: http://stackoverflow.com/a/51216238
has comment: http://stackoverflow.com/comment/89416713
has answer: http://stackoverflow.com/a/51216238
has comment: http://stackoverflow.com/comment/89420118
upvote count: 3

http://stackoverflow.com/q/51313171
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89636082
has answer: http://stackoverflow.com/a/72508547
has body: For the life of me I can't figure out how to remove the duplicate index items created when writing a multiindex dataframe to CSV. While there is this answer out there, it doesn't apply to me per se because my second level has all different values. This is a chunk of the dataframe I have, it just goes on for each month Month Measure JAN KWH Max KW Day/Hour Peak End Use Peak Pct FEB KWH Max KW Day/Hour Peak End Use Peak Pct But in CSV it looks something like JAN KWH JAN Max KW JAN Day/Hour JAN Peak End Use JAN Peak Pct FEB KWH FEB Max KW FEB Day/Hour FEB Peak End Use FEB Peak Pct I hope for it to look exactly just like the dataframe so that means in CSV it would look like Jan,KWH ,Max KW ,Day/Hour and so on I have tried df.index.to_series().duplicates() but it doesn't work because each of my index pairs are not duplicates. I've also tried using index.tolist() then looping through to change with no luck. What's the right approach here? Thanks in advance!
type: Question
tagged with: export-to-csv
has title: Pandas Multiindex to CSV without duplicate Index
has answer: http://stackoverflow.com/a/54138861
possible better answer: http://stackoverflow.com/a/72508547
has comment: http://stackoverflow.com/comment/89629738
has comment: http://stackoverflow.com/comment/89638341
has comment: http://stackoverflow.com/comment/89632895
score: 6
linked to: http://stackoverflow.com/q/17349574
answer count: 2
linked to: http://stackoverflow.com/q/64381413
tagged with: pandas
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/89606589
accepted answer: http://stackoverflow.com/a/54138861
tagged with: python
upvote count: 6

http://stackoverflow.com/comment/115268628
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/55654268
has text: And it may be slow to show on Jupyter Notebook since svg is hard to handle.
score: 0

http://stackoverflow.com/comment/89480399
type: Comment
type: QuestionComment
score: 0
has text: Poor man solution: ssh port redirection with Socks support (see `-D` option)
comment on: http://stackoverflow.com/q/51249535

http://stackoverflow.com/a/51307256
score: 0
has body: You can find the rows of df1, that are present in df2 with a left merge and then change the Desc to Done. mer = df1.merge(df2, on=['No', 'Type'], how='left') mer.loc[mer['Desc_y'].notnull(), 'Desc_x'] = 'Done' df1['Desc'] = mer['Desc_x'] Output: No Type Desc 0 123 A Done 1 123 B Bla 2 123 D Bla 3 342 A Done 4 342 C Done 5 543 B Bla 6 543 C Bla
answers question: http://stackoverflow.com/q/51307061
type: Answer

http://stackoverflow.com/comment/89559714
type: Comment
type: AnswerComment
has text: Thank you! This was very helpful.
score: 0
comment on: http://stackoverflow.com/a/51289828

http://stackoverflow.com/comment/89597628
type: QuestionComment
has text: Speed may be still same or more in my experience. Have you noticed any improvement in the accuracy etc..
comment on: http://stackoverflow.com/q/51296140
score: 0
type: Comment

http://stackoverflow.com/a/51180594
type: Answer
has comment: http://stackoverflow.com/comment/89344085
score: 1
upvote count: 1
downvote count: 0
answers question: http://stackoverflow.com/q/51180363
has body: Lets say you have 5 buttons with tag &lt;button&gt;. Then you can locate this buttons like this: answers = browser.find_elements_by_xpath('xpath') # gives a list with 5 elements (buttons) PS if you provide HTML block with all 5 buttons I can find a xPath to them. Then you want to peak randomly one of this buttons. You can do like this: import random list = [20, 16, 10, 5]; random.shuffle(list) print ("Reshuffled list : ", list) random.shuffle(list) print ("Reshuffled list : ", list) Output: Reshuffled list : [16, 5, 10, 20] reshuffled list : [20, 5, 10, 16] In your case it would be like this: import random answers = browser.find_elements_by_xpath('xpath') random_list = list(range(len(answers))) # creates a list with ascending numbers 0 ... len(answers) random.shuffle(random_list) answers[random_list[0]].click() # click randomly on one of the buttons

http://stackoverflow.com/comment/89606363
score: 0
type: AnswerComment
has text: I see, it's complicated...I want to grab memoryview only when I'm ready to draw the buffer, so that shouldn't be a problem. Thanks for clarifying me the typed memory view.
type: Comment
comment on: http://stackoverflow.com/a/51314456

http://stackoverflow.com/q/51221607
type: AnsweredQuestion
tagged with: web-scraping
has body: For a project at university I need to extract data such as posts and reviews from same Facebook pages. Everything was fine couple of months ago but now to get data from pages you need the Public Page Content Access. In order to get my app reviewed I need to add: A platform where I'd use the app A screencast that shows "how a person sees this feature used in your app" An explanation of how I'd be using Page Public Content Access to enhance the experience of my app. Privacy Policy URL As a student who just needs to extract some data for an exam I don't have any website/platform where I'd use the app. I'm using the Facebook Graph API on Python. I looked on this website for a Privacy Policy Generator but I don't have any website nor mobile apps where I'd use the API... Is there some way for my situation to extract data by API without this requirements or it's better for me to find other solutions, such as web scraping?
type: Question
has title: How to get the Facebook Public Page Content Access just to extract data?
score: 8
has answer: http://stackoverflow.com/a/61802048
tagged with: facebook-page
downvote count: 0
answer count: 1
tagged with: facebook-graph-api
favorite count: 0
accepted answer: http://stackoverflow.com/a/61802048
upvote count: 8
tagged with: facebook
tagged with: python
has comment: http://stackoverflow.com/comment/89446827

http://stackoverflow.com/comment/89533800
type: Comment
has text: Can you show the whole code? Your snippet is at least missing the import statements. For debugging, you can put a `print(type(np), np.__file__)` into your loss function to check that `np` really is the `numpy` module.
comment on: http://stackoverflow.com/q/51277748
score: 0
type: QuestionComment

http://stackoverflow.com/comment/89404114
score: 0
has text: @AdamKG good idea, indeed it runs every 10min per cron. but it didn't fail just once, but every 10min from that on...
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51211409

http://stackoverflow.com/comment/89553784
score: 0
type: AnswerComment
type: Comment
has text: This worked exactly as needed.Works on my real data too. Thanks JH, you've really helped me out.
comment on: http://stackoverflow.com/a/51286495

http://stackoverflow.com/comment/112715763
has text: I get an error: `AttributeError: module 'discord.ext.commands.bot' has no attribute '_default_help_command'`
comment on: http://stackoverflow.com/a/51183547
type: Comment
score: 1
type: AnswerComment

http://stackoverflow.com/a/68390504
type: Answer
score: 9
upvote count: 9
downvote count: 0
has body: There are 2 reasons that this might not work: There is an error in the tests The python Testing plugin won't find your tests if there is an error in the test script. To check for a potential error, click the Show Test Output, then run the tests using Run All Tests (both buttons are located in the top left, just above where the tests should appear). If there is an error, it will appear in the OUTPUT tab. The tests aren't properly configured Check your .vscode/settings.json, and take the python.testing.unittestArgs list. You can debug the discovery of tests in the command line by adding args to the python3 -m unittest discover command in the command line. So with this config: { "python.testing.unittestArgs": [ "-v", "-s", ".", "-p", "*test*.py" ] } You would launch the command: python3 -m unittest discover -v -s . -p "*test*.py" You can play with the args unitl you discover your tests, and modify the args in .vscode/settings.json accordingly . Here are the docs for unittest Note A common reason for this is that you're trying to run tests with dependencies. If this is the case, you can select your interpreter by running ctrl + shift + p and searching Python: Select Interpreter, then selecting the correct interpreter.
answers question: http://stackoverflow.com/q/51198860

http://stackoverflow.com/comment/89413812
score: 0
type: Comment
type: QuestionComment
has text: It was the very last line, because my testvals array was a 4-D array. The problem was solved when I popped the target off test and just passed one entry of the array through predict, I didn't need to reshape it at all. As shown by @Tgsmith61591
comment on: http://stackoverflow.com/q/51216020

http://stackoverflow.com/q/51272288
has answer: http://stackoverflow.com/a/51315748
has comment: http://stackoverflow.com/comment/89522662
has comment: http://stackoverflow.com/comment/89522831
has body: I am trying to generate a vector between the origin (0,0,0) to a specific point. How do I turn the math into code? Edit: Sorry about the unclarity. Let's say that I have point o (0,0,0) and point p (3,6,8) that sit in a 3d coordinate system. How can I calculate the vector from point o in the direction of point p?
answer count: 2
favorite count: 0
accepted answer: http://stackoverflow.com/a/51315748
score: -3
tagged with: python
downvote count: 6
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51272379
upvote count: 3
has comment: http://stackoverflow.com/comment/89522735
has comment: http://stackoverflow.com/comment/89522818
possible better answer: http://stackoverflow.com/a/51272379
type: Question
has title: How to calculate the vector from two points in 3d with python
tagged with: math

http://stackoverflow.com/q/51280959
upvote count: 2
tagged with: seaborn
tagged with: python
linked to: http://stackoverflow.com/q/14885895
has comment: http://stackoverflow.com/comment/93113185
score: 2
type: AnsweredQuestion
tagged with: matplotlib
accepted answer: http://stackoverflow.com/a/53132552
linked to: http://stackoverflow.com/q/40360979
type: Question
linked to: http://stackoverflow.com/q/39075325
downvote count: 0
has comment: http://stackoverflow.com/comment/89607941
favorite count: 0
has comment: http://stackoverflow.com/comment/93158522
has title: Matplotlib pandas plot_date colors category
has body: I have some dataframe: Date_Week Game_Order Game_Mode 0 2010-04-13 124 a 1 2010-06-29 7 a 2 2009-03-17 40 b 3 2010-08-03 54 a 4 2009-09-29 20 e 5 2009-07-07 13 b 6 2009-04-07 29 a 7 2010-03-30 37 b 8 2010-04-13 118 a 9 2010-07-13 12 b 10 2011-08-23 38 c 11 2009-06-02 96 a 12 2010-03-16 48 a 13 2010-08-10 18 b 14 2010-11-09 1 c where the Date_Week column is a datetime timestamp: dft['Date_Week'][0] Out[1043]: Timestamp('2010-04-13 00:00:00') I am plotting this with the pandas plot_date() function. import matplotlib.pyplot as plt import seaborn as sns import matplotlib as mpl fig, ax = plt.subplots(figsize=(22,8)) ax.plot_date(dft['Date_Week'], dft['Game_Order'], marker='o', markersize=2, mew=2) ax.tick_params('y', colors='k') ax.set_xlabel('Date') ax.set_ylabel('Frequency') ax.set_title('Weekly Games') ax.tick_params('y', colors='k') ax.grid(b=True, which='major', color='w', linewidth=1.0) ax.grid(b=True, which='minor', color='w', linewidth=0.5) ax.yaxis.grid(True) xtick_locator = mpl.dates.MonthLocator(interval=6) xtick_formatter = mpl.dates.AutoDateFormatter(xtick_locator) ax.xaxis.set_major_locator(xtick_locator) ax.xaxis.set_major_formatter(xtick_formatter) xtick_locator = mpl.dates.MonthLocator(bymonth=[2,3,4,5,6,8,9,10,11,12], interval=1) xtick_formatter = mpl.dates.AutoDateFormatter(xtick_locator) ax.xaxis.set_minor_locator(xtick_locator) ax.xaxis.set_minor_formatter(xtick_formatter) plt.setp(ax.xaxis.get_minorticklabels(), rotation=90, size=10) plt.setp(ax.xaxis.get_majorticklabels(), rotation=90, size=15) fig.subplots_adjust(bottom=0.24) plt.legend() plt.show() This gives: I would like to colour the points based on the category in the Game_Mode column. I did some research and found this question, this question, this question andthis. Based on this I tried each of the following: Mapping a float, seaborn RGB color palette values, or specific colour to a colour column, based on the category: # Colouring categories = dft['Game_Mode'].unique() # Possible Way 1 co…
linked to: http://stackoverflow.com/q/44723327
tagged with: colors
tagged with: pandas
answer count: 1
has answer: http://stackoverflow.com/a/53132552
linked to: http://stackoverflow.com/q/17250392

http://stackoverflow.com/comment/89610815
comment on: http://stackoverflow.com/q/51317319
score: 0
type: QuestionComment
type: Comment
has text: what's an output of `manage.py showmigrations`?

http://stackoverflow.com/comment/89415927
comment on: http://stackoverflow.com/q/51217344
has text: No, you iterate over the keys, you want to iterate over the values.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51190025
tagged with: mocking
has comment: http://stackoverflow.com/comment/89367672
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89366599
tagged with: pytest
has comment: http://stackoverflow.com/comment/89372282
answer count: 0
has title: Mocking Popen fails with an exception
type: Question
has body: I need to be able to mock Popen, but none of the examples on stack overflow seem to be working for me. I tried the suggestions here but it keeps raising an exception: Traceback (most recent call last): File "/Users/me/workspace/workdir/src/mymodule/transferfile.py", line 23, in sftp p = Popen(cmd, shell=False, stdin=PIPE, stdout=PIPE, stderr=PIPE) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 710, in __init__ errread, errwrite) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 1335, in _execute_child raise child_exception E OSError: [Errno 9] Bad file descriptor File: mymodule/transfer.py: from subprocess import PIPE, Popen def sftp(cmdstr): cmd = ["sftp", "-b", "-", "stfp_server"] p = Popen(cmd, shell=False, stdin=PIPE, stdout=PIPE, stderr=PIPE) if p.returncode is None: stdout, stderr = p.communicate(cmdstr) test file: def test_sftp(mocker): # Attempt 1 mocker.patch('mymodule.Popen.communicate', autospec=True) mocker.patch('mymodule.Popen', autospec=True) mocker.patch('mymodule.PIPE', autospec=True) # Attempt 2 mocker.patch('subprocess.Popen.communicate', autospec=True) mocker.patch('subprocess.Popen', autospec=True) mocker.patch('subprocess.PIPE', autospec=True) cmdstr = "ls" mymodule.sftp(cmdstr)
linked to: http://stackoverflow.com/q/31050888
score: 0

http://stackoverflow.com/q/51237176
upvote count: 2
type: UnansweredQuestion
tagged with: datetime
tagged with: python
has body: I have flow rate data per minute of each day. I want to take average flow rates for every 30 minutes each day. Then I want to find the maximum 30 minute average flow rate for each day. Once I have the max 30 min average flow rate per day I would like to save them into an excel sheet displaying max average flow rate per day. import pandas as pd import numpy as np peakflow= pd.read_csv('P:\Waste Water\Totalizer Data\Main DAF\July_1_17_July_20_17.xls.csv') peakflow['DateTime'] = pd.to_datetime(peakflow.DateTime) Here is a sample of my data frame called peakflow: DateTime Gallons 0 NaT Average 1 NaT gpm 2 2017-07-01 00:00:00 743 3 2017-07-01 00:01:00 1273 4 2017-07-01 00:02:00 1256 5 2017-07-01 00:03:00 723 6 2017-07-01 00:04:00 0 7 2017-07-01 00:05:00 0 8 2017-07-01 00:06:00 0 9 2017-07-01 00:07:00 455 10 2017-07-01 00:08:00 1279 11 2017-07-01 00:09:00 1258 12 2017-07-01 00:10:00 1052 13 2017-07-01 00:11:00 0 14 2017-07-01 00:12:00 0 15 2017-07-01 00:13:00 0 16 2017-07-01 00:14:00 919 17 2017-07-01 00:15:00 1271 18 2017-07-01 00:16:00 1244 19 2017-07-01 00:17:00 343 20 2017-07-01 00:18:00 0 21 2017-07-01 00:19:00 0 22 2017-07-01 00:20:00 0 23 2017-07-01 00:21:00 1248 24 2017-07-01 00:22:00 1258 25 2017-07-01 00:23:00 836 26 2017-07-01 00:24:00 0 27 2017-07-01 00:25:00 0 28 2017-07-01 00:26:00 451 29 2017-07-01 00:27:00 1284 I tried using the following code: df2 = peakflow.resample(rule = '30Min').mean() To resample data frame peakflow and take an average every 30 min. then save it to a new data frame called df2 where I was going to use this code: df3 = df2.resample(rule = '1D').max() To resample df2 every day and find dayle max valvues then save it to df3. However my code did not work to create df2 and I got the following error: TypeError: Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, but got an instance of 'RangeIndex' Do you guys got any ideas on what would work for this application or what went wrong with this code? Any help will be appreciated. Than…
score: 2
has title: How to use Pandas to find 30 min average flows and then find max 30 min average flow per day?
tagged with: dataframe
type: Question
has answer: http://stackoverflow.com/a/51237236
tagged with: pandas
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/a/51248582
has body: resp is a list so, to get first element, access it as resp[0]. Same with resp[0]['attributes'] So you can access it as follows resp[0]['attributes'][0]['value'] You can restructure your for loop as follows for d in resp[0]['attributes']: if isinstance(d['value'], dict) and d['value'].get('data') == false: yo = 100 break
downvote count: 0
type: Answer
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/51248455

http://stackoverflow.com/q/51245056
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/51246164
has comment: http://stackoverflow.com/comment/89468943
score: 3
has title: Singleton is not working in Cython
has comment: http://stackoverflow.com/comment/89484867
upvote count: 3
tagged with: cython
has comment: http://stackoverflow.com/comment/89468617
linked to: http://stackoverflow.com/q/51263233
type: Question
has body: This is how i define Singleton. class Singleton(type): _instances = {} def __call__(cls, *args, **kwargs): if cls not in cls._instances: cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs) return cls._instances[cls] Then I have my classes defined as: class MyClass(object): __metaclass__ = Singleton def __init__(self): pass a = MyClass() b = MyClass() "a is b" will return True However, cdef class MyCythonClass(object): __metaclass__ = Singleton def __cinit__(self): pass c = MyCythonClass() d = MyCythonClass() "c is d" will return False I thought it is the c code (cinit) running before init and so I tried to put the cinit back to init, it doesnt work either. The problem is solved if i removed the "cdef" before "class" I am wondering why, probably I am missing something important here. Your help would be much appreciated. Win 10 / Python 2.7
tagged with: python-2.7
tagged with: cythonize
downvote count: 0
answer count: 1
favorite count: 0

http://stackoverflow.com/comment/89488954
has text: If the data is not huge, you may try INSERT into table..etc, and other option you can try out is S3 to Redshift using AWS DMS. I am adding some links for your reference you can try out. I haven't tested the INSERT into option, but it should work.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51215278

annotate
tag name: annotate
type: Tag
tags question: http://stackoverflow.com/q/51281208

http://stackoverflow.com/comment/89508120
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51265064
has text: Are you sure about the port? For SMTP using SSL I would expect 465 or 587, certainly not 443
score: 0

http://stackoverflow.com/q/51261969
type: Question
has comment: http://stackoverflow.com/comment/89502040
has comment: http://stackoverflow.com/comment/89502046
has body: I want to know weather Python lists can hold pointers to varisbles. Consider this example: regsiters = {"rax":64,"rbx":0} RAM = [0,0,0,0] RAM[1] = registers["rax"] Does RAM[1] hold the value 64 or a pointer to registers["rax"]? And if instead of the dictionary regsiters there was a variable with the same value, would the same be true? Thanks in advance. Edit: I have searched stackoverflow for answers, and although I haven't found anything my searching skills are suboptimal at best. I am sorry if this is a duplicate.
has comment: http://stackoverflow.com/comment/89502316
has comment: http://stackoverflow.com/comment/89502247
score: -1
has comment: http://stackoverflow.com/comment/89502181
upvote count: 0
accepted answer: http://stackoverflow.com/a/51262088
answer count: 1
has comment: http://stackoverflow.com/comment/89502072
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/89502243
type: AnsweredQuestion
tagged with: list
has title: Do Python lists hold pointers or always absolute values?
has answer: http://stackoverflow.com/a/51262088
downvote count: 1

http://stackoverflow.com/comment/89407203
has text: Can you demonstrate in full how your code would work? I keep running into errors. I appreciate your help!
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51212597
type: AnswerComment

http://stackoverflow.com/a/51175506
has comment: http://stackoverflow.com/comment/89370033
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/89806888
answers question: http://stackoverflow.com/q/51169224
type: Answer
accepted answer of: http://stackoverflow.com/q/51169224
has body: There is no way to achieve that. You should modify your script (.sh) to point to the proper configuration file before submission, and create as many configuration files as needed. Another option could be to convert the configuration file entries to command line parameters (if possible) before submission and submit a script with a fully configured command line (so no need to read the .yaml file).
has comment: http://stackoverflow.com/comment/89818315
score: 1
upvote count: 1

http://stackoverflow.com/comment/89594069
has text: @schwobaseggl I see, but even development, for example if I need to list all completed profiles: I would have to first get list of all `profiles` and the iterate over them checking `for p in profiles: if p.completed_setup`, which is way more computationally expensive. Unless there is a way to call a method on a group of instances?
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51307587
type: Comment

http://stackoverflow.com/q/51280026
score: 0
tagged with: windows-10
has comment: http://stackoverflow.com/comment/89538810
has comment: http://stackoverflow.com/comment/89537932
type: UnansweredQuestion
tagged with: windows
tagged with: python
has body: my user folder name is C:\Users\明天, non english words "明天" brought me so much trouble when I program with python. So I login with administrator and change the "明天" into "tomorrow". after restart and login with original account, all desktop content were gone. though I find they are still in C:\Users\明天, but environment has changed, all software installed non exist. can I restore original system?
answer count: 0
type: Question
has comment: http://stackoverflow.com/comment/89538872
has title: how to restore system after change user folder name in windows 10

http://stackoverflow.com/comment/89565771
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51293852
score: 0
has text: You can wrap it in a batch file: c:\ProgramData\Anaconda2\python.exe C:\automation\CompareHoldings\openguiformarketvalues.py

http://stackoverflow.com/comment/89409683
comment on: http://stackoverflow.com/q/51212950
has text: nope, just posted one answer, if it in fact helped you please mark as anwer and upvote, tks :D
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89396675
type: QuestionComment
comment on: http://stackoverflow.com/q/51198555
score: 1
has text: @EcirHana I added it both, but yeah basically kabanus' (and using a `defaultdict` so I could wrap my head around all the index juggling). Since kabanus' answer does a great job of explaining the issues in your original code, mine is basically just the code you asked for.
type: Comment

http://stackoverflow.com/a/51259931
upvote count: 2
has comment: http://stackoverflow.com/comment/89510662
has comment: http://stackoverflow.com/comment/89512830
has comment: http://stackoverflow.com/comment/89514814
has body: Try webbot library . Its built over selenium to handle these kinds of automated tasks . Here's a small code snippet. from webbot import Browser web = Browser() web.go_to('google.com') web.click('Sign in') web.type('mymail@gmail.com' , into='Email') web.click('NEXT' , tag='span') web.type('mypassword' , into='Password' , id='passwordFieldId') web.click('NEXT' , tag='span') # you are logged in For your Specific problem you can just mouse scroll to simulate a mouse movement like this : web.scrolly(100) ;
downvote count: 0
answers question: http://stackoverflow.com/q/51259785
has comment: http://stackoverflow.com/comment/89504578
type: Answer
has comment: http://stackoverflow.com/comment/89507159
score: 2
has comment: http://stackoverflow.com/comment/89511715

transform
tags question: http://stackoverflow.com/q/51211034
type: Tag
tags question: http://stackoverflow.com/q/51189962
tag name: transform

http://stackoverflow.com/comment/89435081
type: Comment
comment on: http://stackoverflow.com/a/51225855
has text: yeah i want to check the user input against keys in dictionary . and your new updated code is working well <3
score: 0
type: AnswerComment

http://stackoverflow.com/comment/89581910
has text: Can you use inheritance?
comment on: http://stackoverflow.com/q/51302536
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51180058
has comment: http://stackoverflow.com/comment/89343746
has comment: http://stackoverflow.com/comment/89343018
downvote count: 0
has comment: http://stackoverflow.com/comment/89342964
has comment: http://stackoverflow.com/comment/89344154
has body: From your comments, you do not want to update the painting, what you want is to reload the data that you get from the database every minute. paintEvent() is a method of widgets that allow to do the painting, and in this case it is not necessary, besides the method update() serves to call that method indirectly, in your case I stress that it is not necessary. What you should do is create a method that is responsible for filling the QTableWidget and calling it using a QTimer. class First(QtGui.QMainWindow, main3.Ui_MainWindow): def __init__(self, parent=None): super(First, self).__init__(parent) self.setupUi(self) timer = QtCore.QTimer(self) timer.timeout.connect(self.reload_data) timer.start(60*1000) self.reload_data() def reload_data(self): print("reload_data") self.tableWidget.clear() self.tableWidget.setRowCount(0) self.tableWidget.setColumnCount(7) cur.execute("SELECT * FROM clinic WHERE Extra_Notice LIKE %s",("%{}%".format('x-ray is required'),)) test_list = cur.fetchall() queue = 1 for row in test_list: c_id = row[0] p_id = row[1] cur.execute("SELECT * FROM patient WHERE id = '%s'"%(p_id)) pt = cur.fetchall()[0] print(pt) if not pt: continue pt_name = pt[1] pt_age = pt[2] pt_address = pt[4] pt_phone = pt[3] button = QtGui.QPushButton('Make Operation') button.setStyleSheet("background-color: #4f81bc; color: white;") button.clicked.connect(lambda checked, p_id=p_id : self.open_report(p_id)) rowposition = self.tableWidget.rowCount() self.tableWidget.insertRow(rowposition) for i, val in enumerate([queue, c_id, pt_name, pt_age, pt_address, pt_phone]): self.tableWidget.setItem(rowposition , i , QtGui.QTableWidgetItem(str(val))) self.tableWidget.setCellWidget(rowposition , 6, button) queue += 1 def open_report(self, p_id): self.child_win = report(p_id) self.child_win.show() sys.exit(app.exec_()) return p_id
has comment: http://stackoverflow.com/comment/89343052
score: 3
has comment: http://stackoverflow.com/comment/89343038
answers question: http://stackoverflow.com/q/51175841
has comment: http://stackoverflow.com/comment/89342987
has comment: http://stackoverflow.com/comment/89343258
accepted answer of: http://stackoverflow.com/q/51175841
has comment: http://stackoverflow.com/comment/89343512
has comment: http://stackoverflow.com/comment/89343709
has comment: http://stackoverflow.com/comment/89343658
type: AcceptedAnswer
upvote count: 3
type: Answer

http://stackoverflow.com/a/51274973
has body: Add return redirect('index') in the end of your add_to_cart.
answers question: http://stackoverflow.com/q/51274902
type: Answer
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51274902
has comment: http://stackoverflow.com/comment/89548397

http://stackoverflow.com/a/51278881
has comment: http://stackoverflow.com/comment/89552142
has comment: http://stackoverflow.com/comment/89541429
type: Answer
has comment: http://stackoverflow.com/comment/89535933
upvote count: 2
has comment: http://stackoverflow.com/comment/89541345
score: 2
answers question: http://stackoverflow.com/q/51278473
accepted answer of: http://stackoverflow.com/q/51278473
has body: One way is to use groupby with shift. df['teststat'] = df.groupby('col1')['col2'].shift(1).fillna(df['col2']) print(df'col1', 'teststat', 'col2') col1 teststat col2 0 a 32.0 32 1 a 32.0 432 2 b 433.0 433 3 c 4.0 4 4 a 432.0 56 5 c 4.0 64 6 a 56.0 4 7 b 433.0 535 8 c 64.0 643 9 c 643.0 356 10 b 535.0 32 11 b 32.0 535 12 a 4.0 34 Edit For your added question: Let's say, i want another column 'teststat2' which gives the difference between last 2 values for a particular value in 'col1'. You can just do the following. df['teststat2'] = df['col2'] - df['teststat'] df.loc[df['teststat2'] == 0, 'teststat2'] = df['col2'] print(df) col1 teststat col2 teststat2 0 a 32.0 32 32.0 1 a 32.0 432 400.0 2 b 433.0 433 433.0 3 c 4.0 4 4.0 4 a 432.0 56 -376.0 5 c 4.0 64 60.0 6 a 56.0 4 -52.0 7 b 433.0 535 102.0 8 c 64.0 643 579.0 9 c 643.0 356 -287.0 10 b 535.0 32 -503.0 11 b 32.0 535 503.0 12 a 4.0 34 30.0
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/89563690

http://stackoverflow.com/comment/89454333
score: 0
has text: If 2 is your problem you can remove the offending characters or escape them eg `popup = folium.Popup(html.escape(data.iloc[i]['organization_name']), parse_html=True)` Note: html is part of the std lib in python3
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51236715

http://stackoverflow.com/comment/89359913
comment on: http://stackoverflow.com/q/51189055
type: Comment
type: QuestionComment
score: 0
has text: you want that when the focus is on the QComboBox and the enter key is pressed, it emits a signal. I am right?

http://stackoverflow.com/comment/89458433
type: AnswerComment
comment on: http://stackoverflow.com/a/51233556
type: Comment
score: 1
has text: thank for observations and feedback , after trying the solution there was a error ------ raise ValueError("Row or column values must be at least 1") ValueError: Row or column values must be at least 1

http://stackoverflow.com/a/51209267
answers question: http://stackoverflow.com/q/51209020
has body: import datetime df.time = df.time.apply(lambda x: datetime.datetime.fromtimestamp(x / 1e9))
downvote count: 0
type: Answer
score: 2
upvote count: 2

http://stackoverflow.com/a/51215020
has comment: http://stackoverflow.com/comment/89429594
has comment: http://stackoverflow.com/comment/89411325
has comment: http://stackoverflow.com/comment/89411343
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89411281
type: Answer
has body: Aadil, i used your code and it seem there are no problem with it at my end. I think youre creating those models using python manage.py inspectdb &gt; models.py from your DB. Sometimes the datatypes get tangled up bit and we don't get what we want like in your Date model there should have DateField or DateTimeField also default should be as mentioned in code below or NONE. BTW my Models.py was: from django.db import models class Player(models.Model): pass class WeightLifting(models.Model): pass class PlayerWeightLifting(models.Model): player = models.ForeignKey(Player, on_delete=models.CASCADE) weightlifting = models.ForeignKey(WeightLifting, on_delete=models.CASCADE,default='') time = models.IntegerField(default='') medal = models.CharField(max_length=256,blank=True) def __str__(self): return str(self.weightlifting) + str(" ") + str(self.player) class Meta: ordering = ['time'] If the problem persists try to create models first and then make your db by migration. See if that works.
accepted answer of: http://stackoverflow.com/q/51214539
downvote count: 0
has comment: http://stackoverflow.com/comment/89411536
has comment: http://stackoverflow.com/comment/89429723
answers question: http://stackoverflow.com/q/51214539
has comment: http://stackoverflow.com/comment/89411397
has comment: http://stackoverflow.com/comment/89413641
score: 1
has comment: http://stackoverflow.com/comment/89411349

http://stackoverflow.com/q/51246962
has title: Selenium webdriver exception in Linux
tagged with: selenium-webdriver
linked to: http://stackoverflow.com/q/47782650
has comment: http://stackoverflow.com/comment/89472556
tagged with: selenium
answer count: 0
type: UnansweredQuestion
has body: I am using python3 in kali linux 2018.3,selenium 3.13 and firefox61,geckodriver21, i dowloaded the geckodriver and added it to my path, after running the code i get this error: raise exception_class(message, screen, stacktrace)selenium.common.exceptions.SessionNotCreatedException: Message: Unable to find a matching set of capabilities Here is my code: from selenium import webdriver def main(): try: # driver = webdriver.Chrome() driver = webdriver.Firefox() driver.get("https://www.amazon.com") element = driver.find_element_by_id("twotabsearchtextbox") usr_input = "jackets" element.send_keys(usr_input) element = driver.find_element_by_css_selector('.nav-search-submit .nav-input').click() driver.close() except TimeoutError: print("fail") if __name__ == '__main__': main() i tried the same with chrome and it worked just fine.
tagged with: linux
has comment: http://stackoverflow.com/comment/89472541
tagged with: python-3.x
type: Question
score: 0
tagged with: python
has comment: http://stackoverflow.com/comment/89486050

http://stackoverflow.com/comment/89345461
score: 2
comment on: http://stackoverflow.com/q/51181556
type: Comment
type: QuestionComment
has text: To determine this the best way is to implement all of the possible ways you can think of and measure them.

http://stackoverflow.com/q/51291901
upvote count: 0
has comment: http://stackoverflow.com/comment/89589995
has comment: http://stackoverflow.com/comment/89566088
has answer: http://stackoverflow.com/a/51367563
accepted answer: http://stackoverflow.com/a/51367563
type: AnsweredQuestion
score: -1
type: Question
tagged with: ansible
has body: I am getting the below error when deploying for the first time to a host using ansible. I've tried using the default setup (I believe this is using default python 3.6 version on the system). I ve also attempted to add in the inventory a variable to use python 2.6(ansible_python_interpreter = /usr/bin/python2.6) Same error : FAILED! =&gt; {"changed": false, "failed": true, "module_stderr": "Shared connection to myserverxx closed.\r\n", "module_stdout": "'import site' failed; use -v for traceback\r\nTraceback (most recent call last):\r\n File \"/home/myuser/.ansible/tmp/ansible-tmp-1531332066.08- 249430258979920/setup.py\", line 4, in &lt;module&gt;\r\n import os\r\nImportError: No module named os\r\n", "msg": "MODULE FAILURE", "rc": 0} On the host I can login and use python 3.6 interpreter and run import os (no error here). EDIT : example of command that fails. I have the issue with a ping, seems configuration issue (with python?). ansible -m ping dev_myserver -i ansible-hosts Content of ansible-hosts [dev_myserver] servername ansible_user=username
favorite count: 0
answer count: 1
downvote count: 1
tagged with: python
has title: ansible python error : No module named os

http://stackoverflow.com/comment/89327383
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51172346
score: 0
has text: `line.find('python')` returns `-1` when not found. You need `line.find('python') != -1`

http://stackoverflow.com/a/51225499
type: Answer
answers question: http://stackoverflow.com/q/51224764
upvote count: 12
has comment: http://stackoverflow.com/comment/89431769
has comment: http://stackoverflow.com/comment/89431696
downvote count: 0
score: 12
type: AcceptedAnswer
has body: In your CustomUserAdmin try switching form and add_form values Try: class CustomUserAdmin(BaseUserAdmin): form = UserChangeForm add_form = UserCreationForm add_form for creation of new users. form for editing I hope this will help.
accepted answer of: http://stackoverflow.com/q/51224764

http://stackoverflow.com/a/51243346
upvote count: 1
has comment: http://stackoverflow.com/comment/89465771
has body: I suggest use str indexer, if not match because value not exist it return NaN: #if need slect first tuple df['new'] = df['Match'].str[0] #if need select second tuple and first element of tuple df['new'] = df['Match'].str[1].str[0] Sample: a = [[('word1','','','')], [('word2','','',''),('word1', )], [('word2','','',''),('word1', ),('word3','','','')]] df = pd.DataFrame({'ID':[1,2,3], 'Match':a}) df['new1'] = df['Match'].str[0] df['new2'] = df['Match'].str[1].str[0] print (df) ID Match new1 new2 0 1 [(word1, , , )] (word1, , , ) NaN 1 2 [(word2, , , ), (word1,)] (word2, , , ) word1 2 3 [(word2, , , ), (word1,), (word3, , , )] (word2, , , ) word1 EDIT: If values are strings use ast.literal_eval: import ast df['Match'] = df['Match'].astype(str) df['Match'] = df['Match'].apply(ast.literal_eval) df['new2'] = df['Match'].str[0] print (df) ID Match new2 0 1 [(word1, , , )] (word1, , , ) 1 2 [(word2, , , ), (word1,)] (word2, , , ) 2 3 [(word2, , , ), (word1,), (word3, , , )] (word2, , , )
score: 1
has comment: http://stackoverflow.com/comment/89465608
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51243181
type: Answer
has comment: http://stackoverflow.com/comment/89465579
accepted answer of: http://stackoverflow.com/q/51243181

http://stackoverflow.com/comment/89342606
type: AnswerComment
has text: I tried to use cmd.exe in windows but it didn't work but i could try the other thing
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51180080

http://stackoverflow.com/a/51193291
answers question: http://stackoverflow.com/q/51193213
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89459059
has body: Files are iterators. Looping over them reads the file line by line. Until you reach the end. They then don't just go back to the start when you try to read more. A new for loop over a file object does not 'reset' the file. Either re-open the input file each time in the loop, seek back to the start explicitly, or read the file just once. You can seek back with src_f.seek(0), reopening means you need to use two with statements (one to open the output file once, the other in the for loop to handle the src_f source file). In this case, given that you build up the data to be written out to memory in one go anyway, I'd read the input file just once, keeping only the lines you need to copy. You can use multiple for loops over the same file object, the file position will change accordingly. That makes reading a series of lines from a match on one key string to another very simple. The itertools.takewhile() function makes it even easier: from itertools import takewhile # read the correct lines (from SPI_frame_0 to halt) from the source file lines = [] with open(src_file, "r") as src_f: for line in src_f: if r"SPI_frame_0" in line: lines.append(line) # read additional lines until we find 'halt' lines += takewhile(lambda l: 'halt' not in l, src_f) # transform the source lines with a new counter with open(dst_file, "a") as dst_f: for cnt, hex_num in enumerate(hex_data): copy_mid_data = [] for line in lines: if "SPI_frame_0" in line: line = line.replace('SPI_frame_0', 'SPI_frame_{}'.format(cnt)) copy_mid_data.append(line) updated_data = WriteHexData(''.join(copy_mid_data), hex_num, cnt, msb_lsb_flag) dst_f.write(updated_data) Note that I changed copy_mid_data to a list to avoid quadratic string copying; it is far more efficient to join a list of strings just once.
type: Answer
score: 0
accepted answer of: http://stackoverflow.com/q/51193213

http://stackoverflow.com/comment/89615612
has text: yes, your algorithm runs in O(n). what's best is subjective.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51319791

http://stackoverflow.com/q/51280327
tagged with: pandas
tagged with: python
has answer: http://stackoverflow.com/a/51280455
has title: Trying to create a bag of words of Panda's df
score: 1
linked to: http://stackoverflow.com/q/46360435
upvote count: 1
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51280455
type: Question
answer count: 1
downvote count: 0
tagged with: bag
has body: I am new to pandas (and somewhat new to Python) and am trying to create a bag of words for every row of a specific column. This is where I took the code from and what follows is my attempt: for index, row in df.iterrows(): cell = df.Review2.iloc[index] df['BOW'].iloc[index] = pd.Series([y for x in cell for y in x.split()]).value_counts() This is a single cell from my dataframe on which i'd like to perform the above operation (thus without the for loop for iterating on all the rows): problem price say discount 6 bottle even show reduce check changesfive star taste goodthis get best cabinet ever great crisp get best cabinet ever great crisp originally buy three bottle wind buy whole case holidaysnice california cab cab fantastic pleasantly surprise great fullbodied flavor 1 cent ship promotion decent Any help is greatly appreciated!
favorite count: 0

http://stackoverflow.com/q/51226619
score: 0
possible better answer: http://stackoverflow.com/a/51226639
tagged with: random
answer count: 3
has answer: http://stackoverflow.com/a/51226639
has title: Python: random choice of key from library for flashcard game
has answer: http://stackoverflow.com/a/51226797
has comment: http://stackoverflow.com/comment/89433561
accepted answer: http://stackoverflow.com/a/51226723
tagged with: python
tagged with: dictionary
type: AnsweredQuestion
has body: I'm fairly new to python and programming in general, and am trying to create some simple programs. I have decided to build a small flashcard program to aid in my study of русский, and have used a dictionary with english definitions as the key, and the русский equivalent as the value. The program runs but I am struggling to figure how I can randomise the word that gets called. I have tried random.choice(vocabulary) but with little success. I have also tried to turn the dictionary key/value pairs into lists but then struggle to call them using the format I have so far used. Is there a way to randomise the key that gets called using a variation on this script? Further, would a different object type be more useful for such a program? Thanks import random vocabulary = { "to study (imperfective)": "изучать", "to begin (imperfective)": "начинать", "to begin (perfective)": "начать" } n = 0 while n &lt; 1: for english, russian in vocabulary.items(): print("Translate:\n" + english + "\n") answer = input("Answer:\n" ) if answer == russian: print("Correct!\n") else: print("Incorrect! Correct answer: \n" + russian + "\n")
has answer: http://stackoverflow.com/a/51226723
type: Question
has comment: http://stackoverflow.com/comment/89433354

http://stackoverflow.com/comment/89464550
has text: @jezrael Just one question, how could I split each member of this list into a separate dataframe? (so my editing is simplified)
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51242754

http://stackoverflow.com/q/51234071
linked to: http://stackoverflow.com/q/20957134
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89447769
has answer: http://stackoverflow.com/a/51234968
has answer: http://stackoverflow.com/a/61304974
linked to: http://stackoverflow.com/q/42354064
tagged with: celery
type: Question
has comment: http://stackoverflow.com/comment/89447216
possible better answer: http://stackoverflow.com/a/61304974
has comment: http://stackoverflow.com/comment/89447843
accepted answer: http://stackoverflow.com/a/51234968
answer count: 2
has comment: http://stackoverflow.com/comment/89447558
downvote count: 0
has title: Why is Celery periodic task not working? (Django)
tagged with: periodic-task
favorite count: 0
upvote count: 2
has body: It returns no errors, however when running celery -A mysite beat -l info &amp; celery -A mysite worker -l info the task doesn't happen. When trying the same structure in another Django project it works fine. Help please! My code: mysite/settings.py (Only CELERY part) BROKER_URL = 'redis://localhost:6379' CELERY_RESULT_BACKEND = 'redis://localhost:6379' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TIMEZONE = 'Africa/Nairobi' mysite/init.py from __future__ import absolute_import from .celery import app as celery_app mysite/celery.py from __future__ import absolute_import import os from celery import Celery from django.conf import settings os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings') app = Celery('mysite') app.config_from_object('django.conf:settings') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) personal/tasks.py from celery.task.schedules import crontab from celery.decorators import periodic_task from celery.utils.log import get_task_logger logger = get_task_logger(__name__) @periodic_task( run_every=(crontab(minute='*/1')), name="task_deleteFiles", ignore_result=True ) def task_deleteFiles(): logger.info("Files Deleted") PS: If necessary I can post the outputs from Celery
has comment: http://stackoverflow.com/comment/89447462
tagged with: django
tagged with: python

http://stackoverflow.com/q/51232080
answer count: 1
score: 4
has title: Dump two dictionaries in a json file on separate lines
tagged with: dump
tagged with: python
tagged with: dictionary
upvote count: 4
favorite count: 0
downvote count: 0
accepted answer: http://stackoverflow.com/a/51232115
type: Question
type: AnsweredQuestion
tagged with: http://stackoverflow.com/tag/json
has answer: http://stackoverflow.com/a/51232115
has body: This is my code: import json data1 = {"example1":1, "example2":2} data2 = {"example21":21, "example22":22} with open("saveData.json", "w") as outfile: json.dump(data1, outfile) json.dump(data2, outfile) The output is this: {"example2": 2, "example1": 1}{"example21": 21, "example22": 22} When I want the output to be this: {"example2": 2, "example1": 1} {"example21": 21, "example22": 22} So how do I dump data1 and data2 dictionaries to the same json file on two separate lines?

http://stackoverflow.com/comment/89427274
score: 1
has text: I’m not following then. A copy-on-write mmap needs data to read to begin with. If you are filling an empty array backed by a writable mmaped file on disk, the OS expects you want to write the data to disk eventually; it’s not going to be a memory extension that way. Just use regular arrays and rely on normal memory management to swap in and out.
comment on: http://stackoverflow.com/a/51212583
type: AnswerComment
type: Comment

http://stackoverflow.com/a/51289701
has body: Firstly, sanitize your HTML before the processing! You have typo in Centre_Threhold - should be Threshold. I changed the values for minimum and maximum in HTML to see the results: s = """ &lt;tr&gt;&lt;td class='label' colspan='2' style="border-color:#000000;background-color:#FFFFFF;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;Threholds:&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt;&lt;td class='label' colspan='2' style="border-color:#000000;background-color:#FFFFFF;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;Focus_Threhold:&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt;&lt;td class='label' colspan='2' style="border-color:#000000;background-color:#FFFFFF;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;Centre_Threhold:&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt;&lt;td class='label' style="border-color:#000000;background-color:#FFFFFF;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;Minimum:&lt;/td&gt; &lt;td class='value' style="border-color:#000000;background-color:#32FFFF;"&gt;&lt;span style='white-space:nowrap;'&gt;0&lt;/span&gt;&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td class='label' style="border-color:#000000;background-color:#FFFFFF;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;Maximum:&lt;/td&gt; &lt;td class='value' style="border-color:#000000;background-color:#32FFFF;"&gt;&lt;span style='white-space:nowrap;'&gt;10&lt;/span&gt;&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td class='label' colspan='2' style="border-color:#000000;background-color:#FFFFFF;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;Corner_Threshold:&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt;&lt;td class='label' st…
answers question: http://stackoverflow.com/q/51288957
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/89559402

http://stackoverflow.com/q/51316844
accepted answer: http://stackoverflow.com/a/51319579
type: Question
tagged with: python
has body: I have three dataframes df_Male , df_female , Df_TransGender sample dataframe df_Male continent avg_count_country avg_age Asia 55 5 Africa 65 10 Europe 75 8 df_Female continent avg_count_country avg_age Asia 50 7 Africa 60 12 Europe 70 0 df_Transgender continent avg_count_country avg_age Asia 30 6 Africa 40 11 America 80 10 Now our stacked bar grap should look like X axis will contain three ticks Male , Female , Transgender Y axis will be Total_count--100 And in the Bar avg_age will be stacked Now I was trying like with pivot table pivot_df = df.pivot(index='new_Columns', columns='avg_age ', values='Values') getting confused how to plot this , can anyone please help on how to concatenate three dataframe in one , so that it create Male,Female and Transgener columns
has title: how to create a stacked bar with three dataframe with three columns & three rows
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/51319579
tagged with: matplotlib
tagged with: pandas
type: AnsweredQuestion

http://stackoverflow.com/q/51256753
has answer: http://stackoverflow.com/a/51257184
has title: how to drop predictable value (y) in python random forest model
tagged with: random-forest
answer count: 1
downvote count: 0
score: 1
tagged with: scikit-learn
has body: I run a random forest model in python to see the importance of features. However, the predictable value (y) cannot be dropped and it looks like it plays as one of the parameters that takes over 98% of importance. The code is as below: temp=pd.read_csv('temp_data.csv',sep=',',engine='python') temp['y'] = temp['temp_actual'] y = temp['y'].values temp = temp.drop(['y'],axis=1) #X = temp.loc[:,:] x= temp.values from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.3, random_state=42) Please help correct the coding. Thanks!
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/89493080
accepted answer: http://stackoverflow.com/a/51257184
upvote count: 1
tagged with: machine-learning
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89492777
has comment: http://stackoverflow.com/comment/89492813
type: Question
has comment: http://stackoverflow.com/comment/89492330

http://stackoverflow.com/q/51210305
has comment: http://stackoverflow.com/comment/89686668
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/89414250
has comment: http://stackoverflow.com/comment/111063933
has title: Python multiprocessing, using pool multiple times in a loop gets stuck after first iteration
has body: I have the following situation, where I create a pool in a for loop as follows (I know it's not very elegant, but I have to do this for pickling reasons). Assume that the pathos.multiprocessing is equivalent to python's multiprocessing library (as it is up to some details, that are not relevant for this problem). I have the following code I want to execute: self.pool = pathos.multiprocessing.ProcessingPool(number_processes) for i in range(5): all_responses = self.pool.map(wrapper_singlerun, range(self.no_of_restarts)) pool._clear() Now my problem: The loop successfully runs the first iteration. However, at the second iteration, the algorithm suddenly stops (Does not finish the pool.map operation. I suspected that zombie processes are generated, or that the process was somehow switched. Below you will find everything I have tried so far. for i in range(5): pool = pathos.multiprocessing.ProcessingPool(number_processes) all_responses = self.pool.map(wrapper_singlerun, range(self.no_of_restarts)) pool._clear() gc.collect() for p in multiprocessing.active_children(): p.terminate() gc.collect() print("We have so many active children: ", multiprocessing.active_children()) # Returns [] The above code works perfectly well on my mac. However, when I upload it on the cluster that has the following specs, I get the error that it gets stuck after the first iteration: DISTRIB_ID=Ubuntu DISTRIB_RELEASE=18.04 DISTRIB_CODENAME=bionic DISTRIB_DESCRIPTION="Ubuntu 18.04 LTS" This is the link to the pathos' multiprocessing library file is
favorite count: 0
has comment: http://stackoverflow.com/comment/89686766
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/112237059
has answer: http://stackoverflow.com/a/51210683
tagged with: pathos
has comment: http://stackoverflow.com/comment/89403825
score: 7
upvote count: 7
tagged with: python-multiprocessing
tagged with: multiprocessing
type: Question
has comment: http://stackoverflow.com/comment/89407704
has comment: http://stackoverflow.com/comment/89415782
has comment: http://stackoverflow.com/comment/89486714
has comment: http://stackoverflow.com/comment/89485973
tagged with: ubuntu
has comment: http://stackoverflow.com/comment/89415248
has comment: http://stackoverflow.com/comment/89415134
has comment: http://stackoverflow.com/comment/89415353
has comment: http://stackoverflow.com/comment/111059249

http://stackoverflow.com/q/51201287
tagged with: python-requests
type: Question
has comment: http://stackoverflow.com/comment/89385133
has title: POST requests python html response not rendering
tagged with: post
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/51202200
favorite count: 0
has comment: http://stackoverflow.com/comment/89384606
has comment: http://stackoverflow.com/comment/89384050
possible better answer: http://stackoverflow.com/a/51203753
has body: Is the html on this site scrap-able? http://www.customs.go.jp/toukei/srch/indexe.htm?M=03&P=1,2,,,,,,,,1,0,2018,0,5,0,2,271111,,,,,,,,,,1,,,,,,,,,,,,,,,,,,,,,,50 In Chrome Dev Tools Network settings, under Docs, 7 htm docs load, all of which except one are GET requests. The one POST request response contains the data which is in html format (this file is called JCWSV03) and this is the data that I want to access. Unfortunately, when I run the request, I get different html than that which is displayed in the web page. import pandas as pd from bs4 import BeautifulSoup as bs import requests as rq import urllib.request url = 'http://www.customs.go.jp/toukei/srch/indexe.htm?M=01&P=1,2,,,,,,,,1,0,2017,0,3,0,2,271111000,,,,,,,,,,1,,,,,,,,,,,,,,,,,,,,,,50' sauce = urllib.request.urlopen(url).read().decode('utf-8') soup = bs(sauce, 'lxml') r2 = rq.post(url) soup, r2.text This also does not work: url2 = 'http://www.customs.go.jp/toukei/srch/jccht00p.htm' parameters = {'Referer' : 'http://www.customs.go.jp/toukei/srch/jccht03e.htm?&P=1,2,,,,,,,,1,0,2018,0,5,0,2,271111,,,,,,,,,,1,,,,,,,,,,,,,,,,,,,,,,50', 'Upgrade-Insecure-Requests': '1', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36'} r3 = rq.post(url, params = parameters) r3.text The html that is rendered is this: ( Trade Statistics ( Search ) :Trade Statistics of Japan Ministry of Finance Unless it turns ON the Javascript function of a browser, search in a site cannot be performed. , 'ï»¿ \r\n \r\n\t \r\n\t\t \r\n\t\t \r\n\t\t \r\n\t\t \r\n\t\t \r\n\t\t Trade Statistics ( Search ) :Trade Statistics of Japan Ministry of Finance \t\t\r\n\t \r\n\t\r\n\t \r\n\t \r\n\t\r\n\t \r\n\t\tUnless it turns ON the Javascript function of a browser, search in a site cannot be performed.\r\n\t \r\n\t\r\n\t \r\n\t\t \r\n\t \r\n \r\n') Please provide guidance !! (my ultimate aim so to parse the html is bs4 and into pandas; loop over time)
tagged with: python
has answer: http://stackoverflow.com/a/51203753
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51202200
score: 1
upvote count: 1

http://stackoverflow.com/comment/91882848
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51285717
has text: You should've add link to issue that *probably you* opened: [*A field having `write_only=True` displays in response schema.*](https://github.com/axnsan12/drf-yasg/issues/165)
score: 0

http://stackoverflow.com/comment/89465992
comment on: http://stackoverflow.com/a/51242577
score: 0
type: Comment
has text: I see you create a connection named `conn`, but you do not use it to read the dataframe, you pass the engine as parameter to `read_sql_query()`. How would that help then? It seems the context manager is mananing a connection that is never used. Or am I missing something?
type: AnswerComment

http://stackoverflow.com/comment/89349920
has text: By the way, the elements of `x` are `double`, yet `a`, `b`, `c`, `d` are floats. Then in your struct you are using `float` again, then you try to initialise them to `double` values. `5.0` is a `double`, `5.0f` is a float. *Don't mix them* (if in doubt, use `double`).
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51183311

http://stackoverflow.com/comment/89535162
comment on: http://stackoverflow.com/a/51278814
type: Comment
has text: how much time it'll take to study dask library and work.
score: 0
type: AnswerComment

http://stackoverflow.com/a/51321707
score: 1
has comment: http://stackoverflow.com/comment/126004828
has body: If you want dates on the x axis of your histogram, it is the dates that need to be the argument to hist. now = datetime.datetime.now().date() x = [now, now + datetime.timedelta(days=1), now + datetime.timedelta(days=2)] axarr[1].hist(x, edgecolor="k")
answers question: http://stackoverflow.com/q/51321575
upvote count: 1
has comment: http://stackoverflow.com/comment/89619259
type: Answer
downvote count: 0

http://stackoverflow.com/a/51187831
has comment: http://stackoverflow.com/comment/89375626
has comment: http://stackoverflow.com/comment/89375938
downvote count: 0
score: 1
has body: This code runs without any problems: from xgboost import XGBRegressor clf = XGBRegressor(n_estimators = 500, learning_rate = 0.05, max_depth=6, n_jobs=1, alpha = 0.1) import numpy as np X_train = np.random.uniform(size=(100,10)) y_train = np.zeros(100) clf.fit(X_train, y_train, verbose=False) Note that I don't have am eval set in clf.fit. What is your variable validation ? It shoud be a tuple of xgboost.DMatrix and string, e.g: dval = xgb.DMatrix(X_val, label=y_val) validation = (dval, "validation")
answers question: http://stackoverflow.com/q/51187225
upvote count: 1
type: Answer

http://stackoverflow.com/comment/89449894
score: 0
type: Comment
type: QuestionComment
has text: @ValeryD. , BeautifulSoup doesn't support XPath. You can try [lxml.html](https://lxml.de/xpathxslt.html) instead
comment on: http://stackoverflow.com/q/51235304

http://stackoverflow.com/q/51304669
answer count: 1
type: UnansweredQuestion
tagged with: azure
tagged with: python
linked to: http://stackoverflow.com/q/46882424
has body: I'm getting the following error message when trying to deploy my Dash app to Azure: Error It then cleans up and says that "Command pyton setup.py egg_info failed with error code 1 in D:\home\site\wwwroot\env\build\Pandas" What am I doing wrong here? Is there an issue with Pandas?
type: Question
has answer: http://stackoverflow.com/a/51396911
has title: Pandas failing to install when deploying Dash app to Azure
score: 0
tagged with: pandas

http://stackoverflow.com/comment/89335272
type: AnswerComment
comment on: http://stackoverflow.com/a/51174751
has text: `parser.error("Wrong argument sequence")` will display the `usage`, this message, and then exit.
score: 0
type: Comment

http://stackoverflow.com/comment/89436597
type: Comment
comment on: http://stackoverflow.com/q/51228223
has text: I deleted it because I did it wrong at first, but now edited it... It should work, I think!
score: 0
type: QuestionComment

http://stackoverflow.com/comment/89597682
type: Comment
has text: Would using Excel 2016 create any problems with that pandas code?
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/51306347

http://stackoverflow.com/a/51210358
has comment: http://stackoverflow.com/comment/89402315
has body: When you call Inv_Search.hide() and MainWindow.setEnabled(True) in close_inv_search_form, you call the methods on the class itself not on the instance, which is what you actually have to. from PyQt5.QtCore import qApp class MainWindow(QMainWindow, Ui_MainWindow): def open_inv_search_form(self): self.window = QtWidgets.QWidget() self.window.ui = Ui_Inv_Search() # You have to set the attributes of the self.window.ui.setupUi(self.window) # "window" not the instance of MainWindow self.window.show() self.setEnabled(False) class Inv_Search(QWidget, Ui_Inv_Search): def __init__(self,): super(Inv_Search, self).__init__() self.btn_close_search.clicked.connect(self.close_inv_search_form) def close_inv_search_form(self): self.hide() # Use the method "hide" on the instance qApp.setEnabled(True) # Use the method "setEnabled" on the instance if __name__ == "__main__" : app = QApplication() main = MainWindow() # This is the instance that can be referred to by qApp main.exec_()
type: Answer
has comment: http://stackoverflow.com/comment/89402542
has comment: http://stackoverflow.com/comment/89402433
has comment: http://stackoverflow.com/comment/89402112
has comment: http://stackoverflow.com/comment/89402635
answers question: http://stackoverflow.com/q/51208669
has comment: http://stackoverflow.com/comment/89401794
score: 0
has comment: http://stackoverflow.com/comment/89421293

http://stackoverflow.com/a/51235767
has body: You can join the set together into a single string with no delimiter and then create another set out of the individual letters: &gt;&gt;&gt; variable = set(["car", "train", "bike", "boat", "airplaine"]) &gt;&gt;&gt; set("".join(variable)) {'r', 'b', 'o', 'i', 'a', 'k', 'p', 'n', 't', 'c', 'e', 'l'} It's worth noting the creation of your set is incorrect.
type: Answer
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/51235732
downvote count: 0

http://stackoverflow.com/q/51263299
score: 0
has body: I would like to create a condition that only gets executed if a is True for more than 3 seconds. I would like it to work like this. if a == True for more than 3 seconds: dosomething
answer count: 3
has comment: http://stackoverflow.com/comment/89504477
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89504451
has title: Python if condition true for x amount of time
has answer: http://stackoverflow.com/a/51263719
has answer: http://stackoverflow.com/a/51263364
has answer: http://stackoverflow.com/a/51263633
has comment: http://stackoverflow.com/comment/89504498
type: Question
tagged with: if-statement
has comment: http://stackoverflow.com/comment/89504750

http://stackoverflow.com/a/51255333
has body: I hope I got your question right. At least it works with the problem you described in your question. If the order of the output should stay the same as the input, change the inplace-sort. The code looks quite ugly, but should perform well and shouldn't be to hard to understand. Code import time import numba as nb import numpy as np @nb.njit(fastmath=True,parallel=True) def filter(A,B): iFilter=np.zeros(A.shape[0],dtype=nb.bool_) for i in nb.prange(A.shape[0]): break_loop=False for j in range(B.shape[0]): ind_to_B=0 for k in range(A.shape[1]): if A[i,k]==B[j,ind_to_B]: ind_to_B+=1 if ind_to_B==B.shape[1]: iFilter[i]=True break_loop=True break if break_loop==True: break return A[iFilter,:] Measuring performance ####First call has some compilation overhead#### A=np.random.randint(low=0, high=60, size=300_000*4).reshape(300_000,4) B=np.random.randint(low=0, high=60, size=30*2).reshape(30,2) t1=time.time() #At first sort the arrays A.sort() B.sort() A_filtered=filter(A,B) print(time.time()-t1) ####Let's measure the second call too#### A=np.random.randint(low=0, high=60, size=300_000*4).reshape(300_000,4) B=np.random.randint(low=0, high=60, size=30*2).reshape(30,2) t1=time.time() #At first sort the arrays A.sort() B.sort() A_filtered=filter(A,B) print(time.time()-t1) Results 46ms after the first run on a dual-core Notebook (sorting included) 32ms (sorting excluded)
accepted answer of: http://stackoverflow.com/q/51252009
downvote count: 0
type: AcceptedAnswer
score: 1
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/89532971
has comment: http://stackoverflow.com/comment/89532614
answers question: http://stackoverflow.com/q/51252009

http://stackoverflow.com/q/51196799
has body: I am trying to create a small test program that is able to login into gmail. So far the program opens up the website on chrome but then fails to actually type anything into the "Enter Email" form box. Also I am receiving an error within the shell which may provide insight into my question. Driver Version: 2.40 Chrome Version: 67.0.3396.99 Below is the code: from selenium import webdriver from selenium.webdriver.common.keys import Keys driver= webdriver.Chrome('C:\chromedriver_win32\chromedriver.exe') driver.get("http://mail.google.com") emailid=driver.find_element_by_name("identifier") emailid.send_keys("samplekeys") Below is the error: Traceback (most recent call last): File "C:\gmail.py", line 7, in &lt;module&gt; driver.get("http://mail.google.com") File "C:\Python36\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 332, in get self.execute(Command.GET, {'url': url}) File "C:\Python36\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 320, in execute self.error_handler.check_response(response) File "C:\Python36\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.WebDriverException: Message: unknown error: missing or invalid 'entry.level' (Session info: chrome=67.0.3396.99) (Driver info: chromedriver=2.27.440174 (e97a722caafc2d3a8b807ee115bfb307f7d2cfd9),platform=Windows NT 10.0.17134 x86_64) Any help would be greatly appreciated!
tagged with: selenium
type: Question
upvote count: 2
answer count: 2
has title: Selenium Python Error
favorite count: 0
has answer: http://stackoverflow.com/a/51196916
has answer: http://stackoverflow.com/a/51197213
accepted answer: http://stackoverflow.com/a/51197213
tagged with: python
possible better answer: http://stackoverflow.com/a/51196916
score: 2
type: AnsweredQuestion
downvote count: 0

pycharm
tags question: http://stackoverflow.com/q/51224674
tags question: http://stackoverflow.com/q/51307636
tags question: http://stackoverflow.com/q/51188806
tags question: http://stackoverflow.com/q/51249028
tags question: http://stackoverflow.com/q/51304831
tags question: http://stackoverflow.com/q/51308421
tags question: http://stackoverflow.com/q/51284700
tags question: http://stackoverflow.com/q/51291808
tags question: http://stackoverflow.com/q/51297102
tags question: http://stackoverflow.com/q/51253980
tag name: pycharm
tags question: http://stackoverflow.com/q/51218108
tags question: http://stackoverflow.com/q/51196405
tags question: http://stackoverflow.com/q/51239527
tags question: http://stackoverflow.com/q/51278235
tags question: http://stackoverflow.com/q/51173450
tags question: http://stackoverflow.com/q/51220670
tags question: http://stackoverflow.com/q/51214473
tags question: http://stackoverflow.com/q/51260177
tags question: http://stackoverflow.com/q/51253078
tags question: http://stackoverflow.com/q/51242709
tags question: http://stackoverflow.com/q/51244360
tags question: http://stackoverflow.com/q/51299207
tags question: http://stackoverflow.com/q/51294349
tags question: http://stackoverflow.com/q/51244600
tags question: http://stackoverflow.com/q/51201123
tags question: http://stackoverflow.com/q/51229013
type: Tag
tags question: http://stackoverflow.com/q/51225662
tags question: http://stackoverflow.com/q/51266814
tags question: http://stackoverflow.com/q/51218105
tags question: http://stackoverflow.com/q/51218705
tags question: http://stackoverflow.com/q/51292729
tags question: http://stackoverflow.com/q/51283494
tags question: http://stackoverflow.com/q/51205793
tags question: http://stackoverflow.com/q/51205382
tags question: http://stackoverflow.com/q/51260036
tags question: http://stackoverflow.com/q/51179120
tags question: http://stackoverflow.com/q/51196881
tags question: http://stackoverflow.com/q/51207625
tags question: http://stackoverflow.com/q/51315250

http://stackoverflow.com/comment/89544551
comment on: http://stackoverflow.com/q/51283207
score: 0
type: Comment
type: QuestionComment
has text: You asked adding all the necessary info, in a clear and concise way. Thumbs (vote) up! :)

http://stackoverflow.com/a/51204935
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 2
upvote count: 2
accepted answer of: http://stackoverflow.com/q/51189456
has body: You can use: df = df.groupby(df.datetime.dt.date, as_index=False).datetime.agg(['min','max'])
answers question: http://stackoverflow.com/q/51189456

http://stackoverflow.com/comment/89474282
score: 0
type: Comment
has text: Does the directory `/opt/ezadmin/media/users` exists?
type: QuestionComment
comment on: http://stackoverflow.com/q/51247772

http://stackoverflow.com/comment/89425504
type: QuestionComment
has text: @JörgWMittag actually i am from c background where a = a+b; and a+=b; are the same operation.
comment on: http://stackoverflow.com/q/51222460
score: 0
type: Comment

http://stackoverflow.com/a/51273291
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/51273008
score: 7
accepted answer of: http://stackoverflow.com/q/51273008
upvote count: 7
type: AcceptedAnswer
has body: I am assuming Your {% block content %} {% endblock %} is in html body but that CSS code should be in head. That's why it's not working. If you really need this, then you can create a block on base.html head section. Something like this &lt;head&gt; {% block mycss %} {% endblock mycss %} &lt;/head&gt; and the in inherited html {% extends 'base.html'%} {% load staticfiles %} {% block mycss %} &lt;style&gt; Your entire css &lt;/style&gt; {% endblock %} {% block content %} Body Part {% endblock %

http://stackoverflow.com/q/51320469
has body: I'm trying to call my TF Artificial Neural Network Model, deployed in Cloud Foundry environment of the SAP Cloud and transformed from Keras Model to TensorFlow SavedModel format. Therefore I have an Python2 API using TensorFlow Serving and gRPC. I'm already getting errors when trying to execute the API in a local venv. API code: import os import grpc from grpc.beta import implementations import tensorflow as tf from tensorflow_serving.apis import predict_pb2 from tensorflow_serving.apis import prediction_service_pb2 MODEL_NAME = str(os.getenv('MODEL_NAME', '')) MODEL_SERVER_HOST = str(os.getenv('MODEL_SERVER_HOST', '')) MODEL_SERVER_PORT = int(os.getenv('MODEL_SERVER_PORT', '')) ROOT_CERT = str(os.getenv('ROOT_CERT', '')).replace('\\n', '\n') def metadata_transformer(metadata): additions = [] token = 'Bearer &lt;my Access Token&gt;' additions.append(('authorization', token)) return tuple(metadata) + tuple(additions) credentials = implementations.ssl_channel_credentials(root_certificates=ROOT_CERT) channel = implementations.secure_channel(MODEL_SERVER_HOST,MODEL_SERVER_PORT, credentials) stub = prediction_service_pb2.beta_create_PredictionService_stub(channel, metadata_transformer=metadata_transformer) #grpc non beta --&gt; does not work for tf serving? --&gt;Rendezvous of RPC that terminated with (StatusCode.UNAVAILABLE, Name resolution failure #credentials = grpc.ssl_channel_credentials(root_certificates=ROOT_CERT) #server = "'" + MODEL_SERVER_HOST + ':' + str(MODEL_SERVER_PORT) + "'" #channel = grpc.secure_channel(server, credentials) #non beta --&gt; can't add metadata --&gt; adding in request below #stub = prediction_service_pb2.PredictionServiceStub(channel) # test: import numpy as np data = np.matrix([&lt;a Test matrix&gt;]) request = predict_pb2.PredictRequest() request.model_spec.name = MODEL_NAME #request.model_spec.signature_name = 'ticketCatFeature2' request.inputs['input'].CopyFrom( tf.contrib.util.make_tensor_proto(data, shape=[200], dtype=tf.float32)) …
has title: gRPC, TensorFlow Serving "Received RST_STREAM with error code 2"
upvote count: 1
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/98357016
answer count: 0
tagged with: grpc
score: 1
tagged with: tensorflow-serving
tagged with: tensorflow
type: Question

http://stackoverflow.com/comment/89535143
score: 0
type: Comment
type: QuestionComment
has text: it is jsonfield
comment on: http://stackoverflow.com/q/51274304

http://stackoverflow.com/a/51267287
has body: Using one of the psycopg2.copy_* methods is the way to go. Which one will depend on - Does the csv have a header? Does the csv structure match the table exactly (number and type of columns)? Note #1 - The form of the copy command that takes a path expects that path to exist on the database server. In Heroku, that will never be the case. Instead, you need the form of the command like this: copy table_name from stdin.... The copy_from method is a convenience method for that form. 1) Simplest case - comma-delimited file with no headers exactly matching the table structure: stmt.copy_from(request.files['data_file'], 'your_table', sep=',') (stmt is a cursor, preferably used inside a with conn.cursor() as stmt: clause) 2) No header, but csv only has a subset of the columns: stmt.copy_from(request.files['data_file'], 'some_table', sep=',', cols=['col1', 'col2', 'col3']) 3) If you have a header, you will need copy_expert - sql = """ copy some_table (col1, col2, col3) from stdin with csv header delimiter ',' """ stmt.copy_expert(sql, request.files['data_file']) Note #2 - the data will be implicitly converted to the correct type. It will also need to satisfy data constraints. A failure of either operation for a single record kills the entire transaction. As a result, you may need to get fancy and load all the data into a simple temp table, clean it, then do a select into ( Note #3 - I kinda guessed that you can use request.files directly, but did not test it. If that fails, stream the data to a temp file and use that as the argument to the copy method. See: http://initd.org/psycopg/docs/cursor.html#cursor.copy_from
score: 0
answers question: http://stackoverflow.com/q/51228118
type: Answer

psychopy
tags question: http://stackoverflow.com/q/51321595
type: Tag
tag name: psychopy

http://stackoverflow.com/a/51288339
answers question: http://stackoverflow.com/q/51287665
has comment: http://stackoverflow.com/comment/89577632
score: 0
has body: I think you are asking for a data frame containing the indices of first and last occurrences of each value. How about something like this. Example data (note -- it's better to include reproducible data in your question so I don't have to guess): import pandas as pd import numpy as np np.random.seed(123) n = 500 df = pd.DataFrame( {'date':pd.to_datetime( pd.DataFrame( { 'year': np.random.choice(range(2017,2019), size=n), 'month': np.random.choice(range(1,13), size=n), 'day': np.random.choice(range(1,28), size=n) } ) ) } ) Approach: pd.DataFrame( ( { '_month_':x,'firstIndex':y[0],'lastIndex':y[-1]} for x, y in df.index.groupby(df['date'].dt.month).items() ) ) Result: _month_ firstIndex lastIndex 0 1 0 495 1 2 21 499 2 3 1 488 3 4 5 498 4 5 14 492 5 6 12 470 6 7 15 489 7 8 2 494 8 9 18 475 9 10 3 491 10 11 10 473 11 12 7 497 If you are only going use it for indexing in a loop, you wouldn't have to wrap it in pd.DataFrame() -- you could just leave it as a generator.
has comment: http://stackoverflow.com/comment/89628336
type: Answer

jenkins-pipeline
tags question: http://stackoverflow.com/q/51271183
type: Tag
tag name: jenkins-pipeline

http://stackoverflow.com/comment/89602915
type: Comment
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/51313055
has text: Even if strings were mutable, assigning `c = "2"` still wouldn't change the string.

http://stackoverflow.com/comment/89499202
type: QuestionComment
has text: Why are you using both `iter_rows` and `cell` methods?
comment on: http://stackoverflow.com/q/51233280
score: 0
type: Comment

http://stackoverflow.com/comment/89519133
type: QuestionComment
comment on: http://stackoverflow.com/q/51270346
has text: Or at least no easy *safe* way. You can easily copy your credentials over the wire to the AWS box, but it's less easy to ensure they haven't been compromised in the transfer.
score: 0
type: Comment

http://stackoverflow.com/comment/89356729
has text: Does the error raise at `clf = XGBRegressor(...` or `clf.fit(...` ?
score: 0
comment on: http://stackoverflow.com/q/51187225
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51184223
has comment: http://stackoverflow.com/comment/89350384
tagged with: python-3.x
answer count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89350515
has comment: http://stackoverflow.com/comment/89350532
has comment: http://stackoverflow.com/comment/89350479
linked to: http://stackoverflow.com/q/4813061
has body: I creat A folder and inside that folder i create 4 more folders name 1, 2, 3, 4 (just empty). And use them i am us import os data_path='/home/nd/Desktop/directory1' data_dir_list = os.listdir(data_path) The above code show different behaviour on spyder installed on ubuntu and windows. (Python 3.6, ubuntu 16.04 , windows 10). For ubuntu data_dir_list='1', '2', '4', '3' and for windows it is '1', '2', '3', '4'.
has comment: http://stackoverflow.com/comment/89350364
type: Question
score: 0
duplicate of: http://stackoverflow.com/q/4813061
has title: Different behaviour of listdir in python installed on ubuntu and windows
tagged with: directory
has comment: http://stackoverflow.com/comment/89350287

http://stackoverflow.com/a/51298205
score: 2
upvote count: 2
has body: It sounds like you'll need to configure errbot to use a regular Slack user account, and not a Bot account: You will need to have an account at Slack for the bot to use, either a bot account (recommended) or a regular user account. See if that approach works, as Bots are indeed not allowed to create channels.
downvote count: 0
has comment: http://stackoverflow.com/comment/89600291
answers question: http://stackoverflow.com/q/51294976
has comment: http://stackoverflow.com/comment/89599779
type: Answer

http://stackoverflow.com/comment/89365288
type: Comment
has text: getting ValueError: invalid literal for int() with base 10: '1662 7399 13679 '
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51191778

boto3
tags question: http://stackoverflow.com/q/51249153
tags question: http://stackoverflow.com/q/51259595
tags question: http://stackoverflow.com/q/51303609
tags question: http://stackoverflow.com/q/51310604
tags question: http://stackoverflow.com/q/51200726
tags question: http://stackoverflow.com/q/51241104
tag name: boto3
tags question: http://stackoverflow.com/q/51241012
tags question: http://stackoverflow.com/q/51271980
tags question: http://stackoverflow.com/q/51276506
tags question: http://stackoverflow.com/q/51190656
tags question: http://stackoverflow.com/q/51198204
type: Tag
tags question: http://stackoverflow.com/q/51192145

http://stackoverflow.com/q/51181861
has comment: http://stackoverflow.com/comment/89373777
has comment: http://stackoverflow.com/comment/89346154
type: UnansweredQuestion
tagged with: python
has body: Assuming I pass a oneliner like for i in range(0,3):print "a";print "b" to python -c, how can I limit the scope (not a good word, but the best I can think of) of the for loop to the first print, i.e. make the invokation print a a a b instead of a b a b a b Placing brackets around the first print or the for loop and the first print causes SyntaxError: invalid syntax. Using identation characters fails due to &gt; python -c 'for i in range(0,3):\n print "a"\nprint "b"' File "&lt;string&gt;", line 1 for i in range(0,3):\n print "a"\nprint "b" ^ SyntaxError: unexpected character after line continuation character maybe I'm doing it wrong (the use uncommon use of ; is much more intuitive but causes the problem I try to solve with this question). The described outputs are examples, I'm not seeking for other solution to printing aaab.
has title: How to limit the scope of a for statement in a Python oneliner?
score: 2
answer count: 0
upvote count: 2
type: Question
linked to: http://stackoverflow.com/q/2043453
has comment: http://stackoverflow.com/comment/89346147
has comment: http://stackoverflow.com/comment/89404869
duplicate of: http://stackoverflow.com/q/2043453
downvote count: 0
favorite count: 0

http://stackoverflow.com/comment/89451475
type: AnswerComment
score: 0
type: Comment
has text: Sorry, haven't been using Python recently and totally forgot subscripting of strings makes way more sense. If you use those instead of append and insert though (again forgot insert is only for lists) though, surely that'd work fine right?
comment on: http://stackoverflow.com/a/51236147

http://stackoverflow.com/q/51225358
favorite count: 0
has title: read a text file which has key value pairs and convert each line as one dictionary using python pandas
type: UnansweredQuestion
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/89431142
type: Question
has body: I have a text file (one.txt) that contains an arbitrary number of key‐value pairs (where the key and value are separated by a = – e.g. 1=8). Here are some examples: 1=88|11=1438|15=KKK|45=00|45=00|21=66|86=a 4=13|11=1438|49=DDD|8=157.73|67=00|45=00|84=b|86=a 6=84|41=18|56=TTT|67=00|4=13|45=00|07=d I need to create a DataFrame with a list of dictionaries, with each row as one dictionary in the list like so: [{1:88,11:1438,15:kkk,45:7.7....},{4:13,11:1438....},{6:84,41:18,56:TTT...}] df = pd.read_csv("input.txt",names=['text'],header=None) data = df['text'].str.split("|") names=[ y.split('=') for x in data for y in x] ds=pd.DataFrame(names) print ds How can I create a dictionary for each line by splitting on the = symbol? It should be one row and multiple columns. The DataFrame should have all keys as rows and values as columns. Example: 1 11 15 45 21 86 4 49 8 67 84 6 41 56 45 07 88 1438 kkk 00 66 a na 1438 na .....
has answer: http://stackoverflow.com/a/51225609
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/89431418
has comment: http://stackoverflow.com/comment/89431711
tagged with: pandas
tagged with: python

http://stackoverflow.com/comment/89335382
comment on: http://stackoverflow.com/q/51176274
type: Comment
type: QuestionComment
has text: Also, you probably don't want make_upper to be a classmethod.
score: 3

http://stackoverflow.com/q/51248360
has title: How to check if first word of a DataFrame string column is present in a List in Python?
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/51248482
tagged with: python
tagged with: regex
type: AnsweredQuestion
score: 2
has answer: http://stackoverflow.com/a/51248437
upvote count: 2
accepted answer: http://stackoverflow.com/a/51248482
possible better answer: http://stackoverflow.com/a/51248437
type: Question
has body: I have a DataFrame df_sentences and a List question_words as follows: df_sentences: sentence label you will not forget this movie 0 will the novel ever die 1 why we drink alcohol 1 did trump win the election 1 ambiance is perfect 0 question_words = ['what', 'why', 'when', 'where', 'whose', 'which', 'whom', 'who', 'how', 'do', 'are', 'will', 'did', 'will', 'am', 'are', 'was', 'were', 'can', 'has', 'have'] I want to check whether the first word of the sentence column is present in the list question_words and return the result in a new column ques_word. Expected Output: sentence label ques_word you will not forget this movie 0 0 will the novel ever die 1 1 why we drink alcohol 1 1 did trump win the election 1 1 the ambiance is perfect 0 0 What I tried so far is using .str.contains('|'.join(question_words)).astype(int) but as expected it returns all the number of all the substrings that matches with question_words list.
tagged with: dataframe
answer count: 2

http://stackoverflow.com/comment/89619530
has text: yeah but in case of overfitting the validation accuracy should also be going down, right?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51321826

http://stackoverflow.com/a/51330254
has comment: http://stackoverflow.com/comment/89641577
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/51316688
answers question: http://stackoverflow.com/q/51316688
upvote count: 1
type: AcceptedAnswer
has body: Fun fact: when pip installs a new module it sets the permissions such that the user is able to import and use the modules as expected but "other" permissions allow the modules to be seen but not execute. Thus, mod_wsgi running under Apache was able to import the modules but calling any methods resulted in an error. Solution: double check permissions after installing or updating python modules! I set all directories to 755 and all files to 644 and that seemed to work. Or, as mentioned in the comment, ensure that your umask is set appropriately before running pip.
type: Answer

http://stackoverflow.com/comment/89359757
has text: I just want to remove them, no need to replace.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51188365
score: 0

http://stackoverflow.com/a/51236600
answers question: http://stackoverflow.com/q/51236510
has body: One approach loop through the array and make a note of the best values you've seen, then reconstruct the array at the end: import numpy as np def rows_by_unique_y(arr): best_for_y = defaultdict(lambda: float('inf')) for i, row in enumerate(arr): x,y = row[0], row[1] best_for_y[y] = min(x, best_for_y[y]) return np.array([[x,y] for y, x in best_for_y.items()]) arr = np.array([[6, 5], [6, 9], [7, 5], [7, 9], [8, 10], [9, 10], [9, 11], [10, 10]]) print(rows_by_unique_y(arr)) No need to sort, just keep track of the minimums. This outputs: [[ 6 5] [ 6 9] [ 8 10] [ 9 11]] While this answer is asymptotically faster, user3483203's answer is much better in practice. This is because it calls out to optimized C code rather than staying inside of Python's surprisingly slow interpreter. However, if your arrays are huge (several gigabytes) then the O(n log n) behavior will start to lose to this. At the same time, if your arrays are that large, you should probably be using a MapReduce framework like Spark instead. The algorithm I gave above is easily parallelized. If you don't need the minimum x values, then the following one-liner using np.unique works: arr[np.unique(arr[:,1], return_index=True)[1]] but this returns array([[ 6, 5], [ 6, 9], [10, 10], [ 9, 11]]) if you switch the 8 and the 10.
has comment: http://stackoverflow.com/comment/89452194
type: Answer
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/89452224
has comment: http://stackoverflow.com/comment/89452180
has comment: http://stackoverflow.com/comment/89452263
downvote count: 0

http://stackoverflow.com/a/51178927
score: 2
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/89420278
has comment: http://stackoverflow.com/comment/89422787
type: Answer
upvote count: 2
accepted answer of: http://stackoverflow.com/q/51172546
answers question: http://stackoverflow.com/q/51172546
has body: I think no: In both the PyArg_Parse* and Py_BuildValue functions, y# refers to a string and length, rather than a buffer, and therefore there is no underlying buffer object to be released. The documentation for Py_BuildValue says: When memory buffers are passed as parameters to supply data to build objects, as for the s and s# formats, the required data is copied. Buffers provided by the caller are never referenced by the objects created by Py_BuildValue(). The purpose of holding a lock on the buffer used by PyArg_Parse* is that you have got a reference to some data out of Python to C, and you want to process it in C without any chance of it being modified by Python. In this case you have copied some data from C into Python and so there's no need to protect the original data from modification.
has comment: http://stackoverflow.com/comment/89434580

http://stackoverflow.com/q/51240272
has answer: http://stackoverflow.com/a/51240410
tagged with: selenium-webdriver
type: AnsweredQuestion
downvote count: 0
score: 1
tagged with: selenium
has answer: http://stackoverflow.com/a/51240359
has body: With Python, Selenium and Webdriver, a need to subsequently click elements found by texts, using the find_element_by_xpath() way on a webpage. (an company internal webpage so excuse me cannot provide the url) By xpath is the best way but there are multiple texts I want to locate and click. It works when separately like: driver.find_element_by_xpath("//*[contains(text(), 'Kate')]").click() For multiple, here is what I tried: name_list = ["Kate", "David"] for name in name_list: xpath = "//*[contains(text(), '" xpath += str(name) xpath += "')]" print xpath driver.find_element_by_xpath(xpath).click() time.sleep(5) The output of the print xpath looked ok however selenium says: common.exceptions.NoSuchElementException
type: Question
has answer: http://stackoverflow.com/a/51240445
has comment: http://stackoverflow.com/comment/89460425
has comment: http://stackoverflow.com/comment/89459665
answer count: 3
upvote count: 1
has title: Loop over list of elements for find_element_by_xpath() by Selenium and Webdriver
favorite count: 0
tagged with: xpath
possible better answer: http://stackoverflow.com/a/51240410
accepted answer: http://stackoverflow.com/a/51240359
tagged with: python

http://stackoverflow.com/a/51202174
has comment: http://stackoverflow.com/comment/89415027
has comment: http://stackoverflow.com/comment/89411390
answers question: http://stackoverflow.com/q/51201733
has comment: http://stackoverflow.com/comment/89411205
score: 0
has comment: http://stackoverflow.com/comment/89411792
type: Answer
has body: I am not sure why you use panda to read a csv file and csv to write. My solution would be to read the csv file and put the data in a list then call the rg.search(coordinates,mode=1) module and write out the csv again. See my snippet below. Of course this also depends on what the output format is of rg.search(coordinates, mode=1). I have assumed result is a list or a tuple with 2 elements. import csv line_data = [] result = [0, 0] with open('input.csv') as csvfile: csvdata = csv.reader(csvfile, dialect='excel', delimiter=',') for row in csvdata: row[1] = float(row[1]) row[2] = float(row[2]) line_data.append(row) for line in line_data: coordinates = (line[1], line[2]) # now call your rg.search(coordinates, mode=1) # as I do not have this module I just make result the # same as line result[0], result[1] = line[1], line[2] print('date is {}, Lat is {}, Long is {}'. format(line[0], result[0], result[1])) with open('output.csv', 'a') as csvfile: csvdata = csv.writer(csvfile, delimiter=',') csvdata.writerow([line[0], result[0], result[1]])

http://stackoverflow.com/q/51294461
tagged with: python
has title: Python custom signal handling in processes pool
has body: I am dealing with the following problem: I've implemented a dummy 'Thing' class that sleeps for 10 seconds and logs a message ('foo'). This class is instantiated in a worker function for a Processes Pool and the 'foo' method that implements the above mentioned logic is called. What I want to achieve is a custom signal handling: as long as the processes haven't terminated, if CTRL+C (SIGINT) is sent, each process will log the signal and they will immediately terminate. Half of the logic is working: while each process is sleeping, on SIGINT, they'll be interrupted and the Pool will be closed. Problem: if ALL the process end successfully and SIGINT is sent, the message will be logged but the Pool won't be closed. Code: import logging import signal import os import time from multiprocessing import Pool, current_process logger = logging.getLogger('test') SIGNAL_NAMES = dict((k, v) for v, k in reversed(sorted(signal.__dict__.items())) if v.startswith('SIG') and not v.startswith('SIG_')) class Thing(object): def __init__(self, my_id): self.my_id = my_id self.logger = logging.getLogger(str(my_id)) def foo(self): time.sleep(10) self.logger.info('[%s] Foo after 10 secs!', self.my_id) class Daemon(object): def __init__(self, no_processes, max_count): signal.signal(signal.SIGINT, self.stop) self.done = False self.count = 0 self.max_count = max_count self.pool = Pool(no_processes, initializer=self.pool_initializer) def stop(self, signum, _): """ Stop function for Daemon """ sig = SIGNAL_NAMES.get(signum) or signum logger.info('[Daemon] Stopping (received signal %s', sig) self.done = True def _generate_ids(self): """ Generator function of the IDs for the Processes Pool """ while not self.done: if self.count &lt; self.max_count: my_id = "ID-{}".format(self.count) logger.info('[Daemon] Generated ID %s', my_id) time.sleep(3) yield my_id self.count += 1 time.sleep(1) def run(self): """ Main daemon run function """ pid = os.getpid() logger.info('[Daemon] Started running on PID %s', st…
tagged with: signal-handling
type: Question
tagged with: signals
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/51294845
type: UnansweredQuestion
tagged with: process

http://stackoverflow.com/a/51187448
has comment: http://stackoverflow.com/comment/89357105
has comment: http://stackoverflow.com/comment/89356884
has comment: http://stackoverflow.com/comment/89357150
type: Answer
has body: You can use the generic views that come bundled with Drango Rest Framework. For you use case where you want only GET and POST I think CreateAPIView [for POST], RetrieveAPIView [for GET] will be enough. http://www.django-rest-framework.org/api-guide/generic-views/#createapiview http://www.django-rest-framework.org/api-guide/generic-views/#retrieveapiview Something like this: path('articles/', views.ArticleListCreateAPIView.as_view()) class ArticleListCreateAPIView(CreateAPIView, RetrieveAPIView): model = Article serializer_class = ArticleSerializer class ArticleSerializer(serializers.ModelSerializer): images = serializers.SerializerMethodField() class Meta: model = Article fields = ('id', 'Heading', 'Article', 'images') def get_images(self, article): images = ArticleImage.objects.filter(article=article) return ArticleImageSerializer(data=images, many=True).data class ArticleImageSerializer(serializers.ModelSerializer): class Meta: model = ArticleImage fields = ('id', 'Image', 'ImageArticle')
has comment: http://stackoverflow.com/comment/89357439
has comment: http://stackoverflow.com/comment/89356683
answers question: http://stackoverflow.com/q/51186597
has comment: http://stackoverflow.com/comment/89357262
has comment: http://stackoverflow.com/comment/89356632
score: 0

http://stackoverflow.com/comment/89618250
type: QuestionComment
comment on: http://stackoverflow.com/q/51307345
has text: I can't use `cond(A, p='fro')` or any other option in cond() except p=None because it is using numpy.linalg.inv which enforce my matrix A to be square @user2699
score: 0
type: Comment

http://stackoverflow.com/q/51169951
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89322669
tagged with: python
downvote count: 0
score: 1
tagged with: http://stackoverflow.com/tag/json
type: Question
has answer: http://stackoverflow.com/a/51170186
has title: Dynamically read JSON data using Python
answer count: 1
upvote count: 1
has body: I have a URL which outputs JSON data when called. I have to check for a specific word in that JSON output. Example below - r1 = session.get(authurl, headers=headers, timeout=6) resphead = r1.headers.get('content-type') if 'application/json' in resphead: json_data = r1.json() overallstatus1 = str((json_data['status'])) overallstatus2 = str((json_data['status']['code'])) Sometimes, the output will have to be called using ['status']['code'] and sometimes the code section will not be coming up in the output, i.e. just ['status']. Similarly, i'll have many other status to check which differ in the same way. What can be done here to read the output even if the keys change. Kindly clarify.

http://stackoverflow.com/a/51173084
answers question: http://stackoverflow.com/q/51172489
accepted answer of: http://stackoverflow.com/q/51172489
upvote count: 1
has comment: http://stackoverflow.com/comment/89330294
type: AcceptedAnswer
downvote count: 0
has body: You can modify your get_nextpage as below: def get_nextpage(self,sauce): nurl = sauce.select_one("div.pager a[rel='next']") if nurl: link = urljoin(self.url,nurl.get("href")) return link and then you can use it in get_links() to get link value: def get_links(self): while True: res = requests.get(self.url) soup = BeautifulSoup(res.text,"lxml") if self.get_nextpage(soup): link = self.get_nextpage(soup) # do whatever you want with link else:break Note that if/else is used instead of try/except as method/function without explicit return returns None and try: None will never generate exception and loop break will not be executed
type: Answer
score: 1
has comment: http://stackoverflow.com/comment/89329880

http://stackoverflow.com/comment/89415937
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51216719
score: 0
has text: So that's why none of my files are being sent to the S3 bucket despite having a file uploaded to the fields. I've tried `if request.files[file] not in files`, but that sent a 400 Bad Request. `if file in files:` uploaded everything even if the field was empty so that's not it either.

http://stackoverflow.com/a/51175196
has comment: http://stackoverflow.com/comment/89333355
has comment: http://stackoverflow.com/comment/89333276
answers question: http://stackoverflow.com/q/51175154
score: 0
type: Answer
has body: my_list[1::2].mean() will give you the other element.

http://stackoverflow.com/q/51275682
has comment: http://stackoverflow.com/comment/89530576
upvote count: 3
answer count: 1
tagged with: numpy
tagged with: tiff
accepted answer: http://stackoverflow.com/a/51276487
has comment: http://stackoverflow.com/comment/89530488
has comment: http://stackoverflow.com/comment/89530532
has comment: http://stackoverflow.com/comment/89530798
has body: There are two situations when I open tif image by PIL. First one is a normal one that can open an image as RGB and display by plt well. However, the second one as shown in the codes below: from PIL import Image import numpy as np import matplotlib.pyplot as plt img = Image.open('test1.tif') a = np.array(img) a.shape # output: (2040,2040) can only open as a shape of (2040,2040), the previous one with a shape of (2040,2040,3). When I convert the (2040,2040) one into RGB mode using img = img.convert('RGB') and showing it via plt only saw a blank square. Please, somebody, tell me what is going wrong? Thanks in advance! Original Image: And numpy array: array([[7256, 6926, 7270, ..., 7368, 7457, 7555], [7174, 6945, 6878, ..., 7401, 7353, 7895], [7288, 7099, 7140, ..., 7359, 7524, 7587], ..., [6769, 6695, 6698, ..., 6599, 6788, 6898], [6780, 6683, 6857, ..., 6723, 6761, 6861], [6788, 6626, 6761, ..., 6738, 6751, 7054]], dtype=uint16) After convert to RGB mode: numpy array: array([[[255, 255, 255], [255, 255, 255], [255, 255, 255], ..., [255, 255, 255], [255, 255, 255], [255, 255, 255]]], dtype=uint8)
type: AnsweredQuestion
score: 3
downvote count: 0
has title: PIL open tif image only one channel
favorite count: 0
has comment: http://stackoverflow.com/comment/89530348
has comment: http://stackoverflow.com/comment/89530737
type: Question
has answer: http://stackoverflow.com/a/51276487
tagged with: python
has comment: http://stackoverflow.com/comment/89530811
has comment: http://stackoverflow.com/comment/89530195
tagged with: python-imaging-library
has comment: http://stackoverflow.com/comment/89530372

http://stackoverflow.com/q/51195307
has title: Python script for Blender: Get Render informations
has body: I don't know how to use blender but I need to make a script that follow a render and send alarm if something is wrong. I'm using Python 3.5 (I could use something else if it's needed), windows 10 and Blender 2.79 I've a big problem and I can't find a solution anywhere. I can't read the render info...is it possible? I can only read the current frame: bpy.context.scene.frame_current I would need to read all info contained in this image: particularly: Totale frame to render Total tiles and current tiles Thank you! EDIT: I don't know if I'm using the right language...when I talk about render I mean render of an animation. EDIT2: I would need to control if the render is going or is crashed for some reason...
type: AnsweredQuestion
tagged with: blender
tagged with: rendering
score: 1
type: Question
has answer: http://stackoverflow.com/a/51203611
accepted answer: http://stackoverflow.com/a/51203611
answer count: 1
downvote count: 0
tagged with: bpy
upvote count: 1
tagged with: python
favorite count: 0

http://stackoverflow.com/a/51281782
type: Answer
downvote count: 0
score: 1
upvote count: 1
has body: To create a structured array, you must specify the dtype beforehand. If you just use numpy.array with a list-literal of pairs then you will get an array with object dtype. So, you need to do something like: &gt;&gt;&gt; mytype = np.dtype([('b', bool), ('f',float)]) &gt;&gt;&gt; mytype dtype([('b', '?'), ('f', '&lt;f8')]) Then pass mytype to the array constructor: &gt;&gt;&gt; structured = np.array( ... [(True, 144.0), (True, 86.0), ... (True, 448.0), (True, 76.0), ... (True, 511.0), (True, 393.0), ... (False, 466.0), (False, 470.0)], dtype=mytype) &gt;&gt;&gt; &gt;&gt;&gt; structured array([( True, 144.), ( True, 86.), ( True, 448.), ( True, 76.), ( True, 511.), ( True, 393.), (False, 466.), (False, 470.)], dtype=[('b', '?'), ('f', '&lt;f8')])
answers question: http://stackoverflow.com/q/51281599

http://stackoverflow.com/q/51188221
score: 1
type: Question
accepted answer: http://stackoverflow.com/a/51188361
has comment: http://stackoverflow.com/comment/89358195
has answer: http://stackoverflow.com/a/51188324
has body: I have the following list of lists: a = [[1,0],[1],[0]] b = [[A,B],[C],[D]] I want to create a new list of list, with the elements of "b" according to the content of "a": In this case, if in the same position there is a "1", we print the letter. If it´s 0, the Position would be empty. The result that I want with respect to the previous example would be: c = [[A,_],[C],[_]] Edit: What I tried: for i in range(len(a)): for j in range(len(a[i])): if b[i][j] == 1: c.append(a[i][j]) This obviously create a list with the elements that I want, but it does not differentiate the internal lists. I really tried other things for a time, I didn´t want to give the feeling I didn´t try.
has title: Compare lists and create new one according to content of both
possible better answer: http://stackoverflow.com/a/51188311
answer count: 4
has answer: http://stackoverflow.com/a/51188311
favorite count: 0
upvote count: 2
has answer: http://stackoverflow.com/a/51188361
tagged with: python
downvote count: 1
has answer: http://stackoverflow.com/a/51188349
type: AnsweredQuestion
tagged with: list

http://stackoverflow.com/comment/89327057
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51171379
type: Comment
has text: Then why don't you use it when it's a canonical use case for it ?

http://stackoverflow.com/comment/89406533
has text: Have you tried chaining them together? `return df.rename(...).set_index(...)`
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51212813

http://stackoverflow.com/q/51315667
has comment: http://stackoverflow.com/comment/89607776
favorite count: 0
answer count: 0
upvote count: 2
type: UnansweredQuestion
has title: Cant find the source of the AttributeError I'm getting
tagged with: python
score: 2
type: Question
has body: I'm learning Python 3. I'm stuck with an exercise. I can't find the issue in the code below that gives me an AttributeError message. #child class of Users called Admin class Admin(Users): """Initilize Users parent class attributes""" def __init__(self, name, last, year, location): super().__init__(name, last, year, location) self.admin_privileges = Privileges() #attribute class to child class Admin class Privileges(): """Initilize attributes""" def __inti__(self, privileges=[]): self.privileges_list = privileges def show_privileges(self): """Displays admin privileges""" print('As an admin you can: ') if self.privileges_list: for privilege in self.privileges_list: print('-' + privilege) else: print("This account doesn't have privileges.") admin = Admin('bob', 'chef', '1883', 'usa') admin.greet_user() admin.describe_user() admin_priv = ['can add posts', 'can delete post', 'can ban user'] admin.admin_privileges.privileges = admin_priv admin.admin_privileges.show_privileges() Here's the output which shows the error: User Bob's information: First name: Bob Last name: Chef Birth year: 1883 Location: Usa Login's: 0 As an admin you can: Traceback (most recent call last): File "user_class.py", line 84, in &lt;module&gt; admin.admin_privileges.show_privileges() File "user_class.py", line 71, in show_privileges if self.privileges_list: AttributeError: 'Privileges' object has no attribute 'privileges_list' I have tried looking for the answer but can't find anything. I'm sure that I forgot something.
downvote count: 0

http://stackoverflow.com/a/53703172
answers question: http://stackoverflow.com/q/51288736
type: Answer
score: 0
has body: Before use Dense(), you should call Flatten(). the error is obvious, Dense net expect 2 dim while you fitted it with 4 dim. model = models.Sequential() model.add(Flattern(input_shape = (4, 4, 512))) model.add(layers.Dense(256, activation='relu'))

http://stackoverflow.com/q/51274122
has body: I have a tuple of data: ('dave', 23, 'm'), ('alice', 33, 'f'), ('mary', 44, 'f') I have an sqlalchemy base class: class People(Base): __tablename__='people' I want to be able to dynamically create columns/fields for this class using data from the tuple above the end result would be: class People(Base): __tablename__='people' dave = Column(String) alice = Column(String) mary = Column(String) though, i can't figure out how do use the splat operator to create the fields..
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89526639
tagged with: python
tagged with: splat
linked to: http://stackoverflow.com/q/2574105
has comment: http://stackoverflow.com/comment/89526589
downvote count: 1
tagged with: sqlalchemy
type: Question
has comment: http://stackoverflow.com/comment/89550975
has title: Dynamically create class members sqlalchemy
has answer: http://stackoverflow.com/a/51289039
has comment: http://stackoverflow.com/comment/89526519
upvote count: 0
score: -1
linked to: http://stackoverflow.com/q/2768607
answer count: 1
favorite count: 0

http://stackoverflow.com/comment/89431226
has text: Time depends on your machine, meaning your CPU, your RAM, your Hard Disk (cause no, your RAM won't be large enough I think), your OS... I don't think anyone has made a benchmark for this program ;)
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51225423
score: 1

http://stackoverflow.com/comment/89347163
comment on: http://stackoverflow.com/q/51181605
type: Comment
type: QuestionComment
has text: To be more specific, your code calls `Tk()` every time `update()` gets called. Generally this is only ever done once it a `tkinter`-based GUI, usually as part of its start-up initialization. Suggest you look more closely at any of the many `tkinter` examples available on-line.
score: 0

http://stackoverflow.com/comment/89426225
type: Comment
has text: You are right about `and` but saying that you can't write and read like this is wrong.
comment on: http://stackoverflow.com/a/51222720
type: AnswerComment
score: 0

http://stackoverflow.com/comment/89557715
comment on: http://stackoverflow.com/a/51289181
score: 0
type: AnswerComment
has text: In Python 2, you'd have to use `Class1.__dict__['class_one_method'](class_two_instance)`
type: Comment

http://stackoverflow.com/q/51216002
has comment: http://stackoverflow.com/comment/89413645
answer count: 1
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51216508
type: UnansweredQuestion
score: -3
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/89413192
has comment: http://stackoverflow.com/comment/89413225
type: Question
has title: Python equivalent for nested c++ style for loop
tagged with: iterator
downvote count: 4
has body: In c++ for (auto i = min; i &lt; sqrt_max; i++ ) { for (auto j = i; i*j &lt;= sqrt_max; j++) { I am trying to do the exact same thing in python for i in enumerate(range(min, sqrt_max + 1)): for j in enumerate(range(min, i * j &lt; sqrt_max + 1)): I get undefined name j

http://stackoverflow.com/comment/93681810
type: QuestionComment
has text: I would need a reproducible example to try helping you. There are undefined functions in your code snippets, which make it pretty hard to answer a performance question.
comment on: http://stackoverflow.com/q/51210152
score: 0
type: Comment

http://stackoverflow.com/q/51182921
tagged with: javascript
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/89371520
tagged with: mechanicalsoup
has title: Mechanicalsoup whit interactive pages (without open browser)
type: UnansweredQuestion
tagged with: web-scraping
upvote count: 1
has body: I have a problem with interactives pages with forms, because I have to select a element from the form and later render the current page and to scrape it The form is a simple radio buttons, it contains an onclick action and call a js function that write in a DOM element &lt;input id="RBLOpcionBuscar_2" type="radio" name="RBLOpcionBuscar" value="Todas" onclick="javascript:setTimeout('__doPostBack(\'RBLOpcionBuscar$2\',\'\')', 0)" /&gt; I find diferents options to get elements generated by javascript: dryscrape, requests_html, python-qt4 and selenium but I do not know how to integrate them and I do not want to use Selenium because it opens a browser Respects!
type: Question
score: 1
has answer: http://stackoverflow.com/a/52862538
linked to: http://stackoverflow.com/q/49366610
downvote count: 0
answer count: 1

http://stackoverflow.com/q/51220591
type: AnsweredQuestion
has body: I have a Pandas Dataframe with say 5 columns. Some of the columns contain a string "aa". I want to return a list containing booleans that identify the columns that contain "XX" Example cl1 cl2 cl3 cl4 cl5 1. ds fr we iu XX 2. sx XX ee ee nn 3. df vd rr we mm 4. er we gf wq hh The result should be res= [False True False False True] I tried with str.contain of str.match but this only apply to Series and I don't want to iterate over the Series
tagged with: select
upvote count: 1
tagged with: match
type: Question
score: 1
accepted answer: http://stackoverflow.com/a/51221700
downvote count: 0
answer count: 1
has title: Return Boolean mask of columns that contain a string
favorite count: 0
tagged with: pandas
has answer: http://stackoverflow.com/a/51221700
tagged with: python

http://stackoverflow.com/q/51245098
has comment: http://stackoverflow.com/comment/89468748
has answer: http://stackoverflow.com/a/51245201
downvote count: 0
has answer: http://stackoverflow.com/a/51245212
has answer: http://stackoverflow.com/a/51245344
has answer: http://stackoverflow.com/a/51245195
has body: So lets say I have a list like this: myList = ["Sprite", "Fanta", "Coke", "7up"] And I want to access only myList[0] and myList[3] which are Sprite and 7up. I tried doing it with list slicing but couldn't get it right.
accepted answer: http://stackoverflow.com/a/51245201
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89468822
possible better answer: http://stackoverflow.com/a/51245195
answer count: 5
tagged with: python
type: AnsweredQuestion
score: 1
has title: How to access only specific elements of the list
upvote count: 1
has answer: http://stackoverflow.com/a/51246383
type: Question

http://stackoverflow.com/comment/89477359
score: 0
type: Comment
type: QuestionComment
has text: Thanks for the tip, but unfortunately that doesn't work in either xlwings or openpyxl.
comment on: http://stackoverflow.com/q/51248929

wikipedia-api
tag name: wikipedia-api
tags question: http://stackoverflow.com/q/51278665
type: Tag

http://stackoverflow.com/a/51268570
answers question: http://stackoverflow.com/q/51268370
type: Answer
has body: If you consider the speed , data from Engineero list(set(df['time'].dt.year.values))
score: 4
upvote count: 4
downvote count: 0

http://stackoverflow.com/comment/89395769
score: 0
type: QuestionComment
type: Comment
has text: Is your example output for `4` digits complete? Why is `1132` not included? What about `2123`? You need to be more clear in your desired output. Also, what work have you done on this problem and just where are you stuck? Please show us some attempted code on your part.
comment on: http://stackoverflow.com/q/51205025

http://stackoverflow.com/comment/89585649
comment on: http://stackoverflow.com/a/51302920
type: AnswerComment
has text: So, which programming language do you suggest to calculate this kind of algorithm? I will try to run it on a server, and this will probably be a Heroku server.
score: 0
type: Comment

http://stackoverflow.com/comment/89389150
type: QuestionComment
has text: read [ask].....
comment on: http://stackoverflow.com/q/51203996
score: 0
type: Comment

http://stackoverflow.com/q/51215604
has body: I'm trying to create a custom class called Package that has logging capabilities. import logging logger = logging.getLogger('console') class Package(logging.Logger): def __enter__(self): return self def __exit__(self,exc_type,exc_val,exc_tb): pass def __init__(self,**kwargs): pass with Package() as p: p.error('test') For some reason I get this error message when I use any of the logging functions: Traceback (most recent call last): File "test.py", line 14, in &lt;module&gt; p.error('test') File "C:\Program Files\Python36\lib\logging\__init__.py", line 1334, in error if self.isEnabledFor(ERROR): File "C:\Program Files\Python36\lib\logging\__init__.py", line 1548, in isEnabledFor return level &gt;= self.getEffectiveLevel() File "C:\Program Files\Python36\lib\logging\__init__.py", line 1537, in getEffectiveLevel if logger.level: AttributeError: 'Package' object has no attribute 'level'
upvote count: 1
downvote count: 1
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89413157
accepted answer: http://stackoverflow.com/a/51216244
type: Question
has comment: http://stackoverflow.com/comment/89412519
answer count: 1
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89413207
tagged with: python
has answer: http://stackoverflow.com/a/51216244
score: 0
has comment: http://stackoverflow.com/comment/89412621
has title: 'Package' object has no attribute 'level' when inheriting logging.Logger

http://stackoverflow.com/a/51248725
has body: You need to create a custom header that includes your auth details and send it along with your request. Something like this: from base64 import b64encode ... headers = {'Authorization': 'Basic ' + b64encode("{0}:{1}".format(username, password))} rv = self.app.get('/i-am-not-found', headers=headers) ... import unittest from app import app class TestApp(unittest.TestCase): def setUp(self): self.app = app.test_client() def test_404(self): headers = { 'Authorization': 'Basic ' + b64encode("username:password") } rv = self.app.get('/i-am-not-found', headers=headers) self.assertEqual(rv.status_code, 404) if __name__ == '__main__': unittest.main() Your username and password is sent in the form username:password but is base64 encoded. If expanding this there are ways to make this simpler such as extracting into a function to always pass the header and externalising username/password for testing. EDIT: Additionally I think you should be returning a 401 code here. 401 is usually used when credentials are incorrect, 403 is usually used when you have successfully authenticated yourself but do not have access to a resource. A very simplified example being logged into Facebook but being restricted from accessing another person's photo that is marked as private.
accepted answer of: http://stackoverflow.com/q/51248178
type: Answer
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51248178

for-loop
tags question: http://stackoverflow.com/q/51236287
tags question: http://stackoverflow.com/q/51294769
tags question: http://stackoverflow.com/q/51309901
tags question: http://stackoverflow.com/q/51276411
tags question: http://stackoverflow.com/q/51322698
tags question: http://stackoverflow.com/q/51315185
tags question: http://stackoverflow.com/q/51256297
tag name: for-loop
tags question: http://stackoverflow.com/q/51275357
tags question: http://stackoverflow.com/q/51313214
tags question: http://stackoverflow.com/q/51207828
tags question: http://stackoverflow.com/q/51190277
tags question: http://stackoverflow.com/q/51202885
tags question: http://stackoverflow.com/q/51262226
tags question: http://stackoverflow.com/q/51202437
tags question: http://stackoverflow.com/q/51225691
type: Tag
tags question: http://stackoverflow.com/q/51217432
tags question: http://stackoverflow.com/q/51226817
tags question: http://stackoverflow.com/q/51212489
tags question: http://stackoverflow.com/q/51218054
tags question: http://stackoverflow.com/q/51250881
tags question: http://stackoverflow.com/q/51190701
tags question: http://stackoverflow.com/q/51278473
tags question: http://stackoverflow.com/q/51199436
tags question: http://stackoverflow.com/q/51324166
tags question: http://stackoverflow.com/q/51193213
tags question: http://stackoverflow.com/q/51208552
tags question: http://stackoverflow.com/q/51200060
tags question: http://stackoverflow.com/q/51216114
tags question: http://stackoverflow.com/q/51221851

http://stackoverflow.com/comment/96139078
comment on: http://stackoverflow.com/a/54610751
score: 0
type: AnswerComment
type: Comment
has text: As I mentioned this is only to get the code working. I am not expecting it to solve the problem, although keras does a decent job with only these two layers. Also, as stated in the edit, I have tried to lower the LR with no luck. The entire purpose of this net is just to get the same results I am getting in keras but using tensorflow.

http://stackoverflow.com/q/51295067
has title: Load Configuration File with Juniper PyEZ
tagged with: juniper
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51297252
score: 0
type: Question
answer count: 2
possible better answer: http://stackoverflow.com/a/51295318
has answer: http://stackoverflow.com/a/51295318
tagged with: pyez
accepted answer: http://stackoverflow.com/a/51297252
has body: I am trying to load override a config stored on the juniper device (vSRX) with PyEZ. The code looks like this from jnpr.junos import Device from jnpr.junos.utils.config import Config dev = Device(host="x.x.x.x", user='user', password='pass').open() with Config(dev, mode='private') as cu: cu.load('load override minimal.conf', format='set') cu.pdiff() if cu.commit_check(): cu.commit() When I run the script I get below error: Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/usr/local/lib/python2.7/dist-packages/jnpr/junos/utils/config.py", line 534, in load ignore_warning=ignore_warning) File "/usr/local/lib/python2.7/dist-packages/jnpr/junos/utils/config.py", line 455, in try_load raise ConfigLoadError(cmd=err.cmd, rsp=err.rsp, errs=err.errs) jnpr.junos.exception.ConfigLoadError: ConfigLoadError(severity: error, bad_element: load, message: error: unknown command) Can't find a solution to my problem. Any help is greatly appreciated!

http://stackoverflow.com/q/51302045
has body: I am currently making the Switch from R to python and wonder weither I can speed up the following dataframe operations. I have a sales dataset consisting of 500k rows and 17 columns on which I need to do some calculations before I put them into a dashboard. My data looks like this: location time product sales store1 2017 brandA 10 store1 2017 brandB 17 store1 2017 brandC 15 store1 2017 brandD 19 store1 2017 catTot 86 store2 2017 brandA 8 store2 2017 brandB 23 store2 2017 brandC 5 store2 2017 brandD 12 store2 2017 catTot 76 . . . . . . . . . . . . . . . . catTot is a pre aggregate I get from the raw data set which shows the total sales for a given store in a given time period. As you can see, the other products are just a fraction of the total and never add up to the total, however they are included in the total. Since I want to reflect how the total sales in a given location is without showing all products (due to performance issues in the dashboard) I need to replace the catTotvalues with an aggregate that is actually the current value minus the sum of the other products. Currently, I iterate through nested for loops to make the changes. The code looks like this: df['location'] = df.location.astype('category') df['time'] = df.time.astype('category') var_geo = [] var_time = [] for var_time in df.time.cat.categories: for var_geo in df.location.cat.categories: df_tmp = [] fct_eur = [] df_tmp = df[(df['location'] == var_geo) &amp; (df['time'] == var_time)] fct_eur = df_tmp.iloc[len(df_tmp)-1,3] df_tmp.iloc[0:len(df_tmp)-2,3].sum() df.loc[(df['location'] == var_geo) &amp; (df['time'] == var_time) &amp; (df['product'] == 'catTot'), ['sales']] = fct_eur As you can see, catTot is always the last row in the masked dataframe. This operation now takes around 9min every time, since I have 23 store locations, around 880 products, 30 time periods and 5 different measures, which results in about 500k rows. Is there a more elegant or atleast faster way to make this kind of operati…
accepted answer: http://stackoverflow.com/a/51302615
tagged with: python-3.x
tagged with: python
has answer: http://stackoverflow.com/a/51401473
score: 0
tagged with: etl
possible better answer: http://stackoverflow.com/a/51401473
has answer: http://stackoverflow.com/a/51302615
type: Question
type: AnsweredQuestion
tagged with: dataframe
answer count: 2
tagged with: pandas
has title: Speed up dataframe operations in pandas

http://stackoverflow.com/comment/92043914
type: QuestionComment
comment on: http://stackoverflow.com/q/51197550
has text: 'scale', [i*1.75 for i in [4/3, 1, 1]] List comprehension. Vapory does not seem to have a vector class that would make things like this easier. Actually, a true vector type in Python would be nice to have.
score: 0
type: Comment

http://stackoverflow.com/q/51227159
downvote count: 0
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/51231777
tagged with: python
type: AnsweredQuestion
score: 59
has body: I need to set some access token environment variables for my python project that I am running in a pipenv. I will want to set these environment variables every time I start the pipenv. How do I do this?
upvote count: 59
accepted answer: http://stackoverflow.com/a/51231777
type: Question
tagged with: pipenv
has title: How do I set environment variables in pipenv?

http://stackoverflow.com/a/51823355
upvote count: 2
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/116676312
type: Answer
accepted answer of: http://stackoverflow.com/q/51260504
answers question: http://stackoverflow.com/q/51260504
score: 2
downvote count: 0
has body: Have faced similar thing at work, and have changed types using VARCHAR for the columns which are of string object def updateType(df_para): dtypedict = {} # create and empty dictionary for i,j in zip(df_para.columns, df_para.dtypes): if "object" in str(j): dtypedict.update({i: sa.types.VARCHAR}) return dtypedict updatedict = updateType(df) # update the datafraame type

http://stackoverflow.com/q/51288991
tagged with: inheritance
possible better answer: http://stackoverflow.com/a/51289181
tagged with: class
score: 0
has comment: http://stackoverflow.com/comment/89555969
has answer: http://stackoverflow.com/a/51289377
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51302249
tagged with: python
has comment: http://stackoverflow.com/comment/89555840
answer count: 4
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51289113
has title: How do I call a classes method from another class without initialising the first class?
accepted answer: http://stackoverflow.com/a/51302249
type: Question
has body: I have something like the following: class Class1(object): def __init__(self): print('I've init-ed') def print_me(self, string): print(string) class Class2(object): def __init__(self): print('Class 2 init') def print_me_from_other_class(self, string): Class1().print_me(string) And then if I call something like: test = Class2() test.print_me_from_other_class('TEST') then I get: Class 2 init I've init-ed TEST What I want to do is call the method from Class1 from the method in Class2 but without calling the init from class 1. So I'd end up with: Class 2 init TEST I've tried removing the brackets after Class1 in the print_me_from_another_class(self, string) function so it says: print_me_from_another_class(self, string): Class1.print_me(string) But that throws the error: TypeError: print_me() missing 1 required positional argument: 'string' Any ideas? Or is this a bad way to go about things? Seems like it will save rewriting code so should be a good thing. EDIT: I've worked out I need to pass the instance of Class2 to the function so that the function in Class2 becomes: def print_me_from_other_class(self, string): Class1.print_me(self, string) And it works! But I still want to know if this is a good way of doing things?
has answer: http://stackoverflow.com/a/51289181

http://stackoverflow.com/comment/89371741
comment on: http://stackoverflow.com/q/51193950
has text: There you have the query I used. When I try to implement this on Pyspark with SQLContext I get an error.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89528855
has text: This allowed me to `queue_service.put_message(response_queue, json.dumps(response))` which is preferable!
comment on: http://stackoverflow.com/a/51258849
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/51219664
tagged with: beautifulsoup
tagged with: http://stackoverflow.com/tag/csv
has answer: http://stackoverflow.com/a/51219819
tagged with: python
type: AnsweredQuestion
score: 1
has title: Python Writerow to CSV (Output into Columns from For Loops)
upvote count: 1
tagged with: python-requests
linked to: http://stackoverflow.com/q/54165551
type: Question
accepted answer: http://stackoverflow.com/a/51219819
has body: I thought I'd be able to figure this one out myself based on the last answer I received for a similar problem, but am again drawing a blank. I'm making a Python 3 web scraper that scrapes MLB scores from The Score's website. What I want, is to output the relevant information to a CSV in the exact same layout as it shows on the website. The URL to use for this example would be: https://www.thescore.com/mlb/events/date/2018-06-29 ...and this is my current code (I know it's incorrect, but I've tried several different solutions, but none of which are giving me the output I want, trying the row.append, etc. I have the URLs list imported from a CSV currently as I want this to cycle through a list of Urls, but this is the one link to use as an example) from bs4 import BeautifulSoup import requests import csv from csv import reader, writer with open('DailyResultsURLS.csv', newline='') as f_urls, open('DailyResultsOutput.csv', 'w', newline='') as f_output: csv_urls = csv.reader(f_urls) csv_output = csv.writer(f_output, delimiter=',') csv_output.writerow(['Date', 'Away Team', 'Home Team', 'Away Score', 'Home Score', 'Final/Extra Innings']) for line in csv_urls: page = requests.get(line[0]).text soup = BeautifulSoup(page, 'html.parser') date = soup.find('div', {'class' : 'events__date--1OuzN'}) teams = soup.findAll('span', {'class' : 'EventCard__title--DY0la'}) scores = soup.findAll('div', {'class' : 'col-xs-2 EventCard__rightColumn--7jlDP'}) final = soup.findAll('div', {'class' : 'col-xs-4 col-sm-3 EventCard__rightColumn--7jlDP'}) for d in range(len(date)): csv_output.writerow([[date.text] + [teams[r1].text for r1 in range(len(teams))] + [scores[r2].text for r2 in range(len(scores))] + [final[f3].text for f3 in range(len(final))]]) I have also attached a picture of what my "Desired" DailyResultsOutput.csv output file should look like. One thing to mention is that where it says "Final" on the site for each particular game, that can sometimes change to say something like "Final…
answer count: 1
downvote count: 0
favorite count: 0

http://stackoverflow.com/q/51296301
has body: I want to implement an asymmetric loss function such as referenced here https://stats.stackexchange.com/questions/37955/how-to-design-and-implement-an-asymmetric-loss-function-for-regression in TensorFlow. I currently am using the mean square error loss function: mse = tf.reduce_mean(tf.squared_difference(out,Y)) Which I want to replace with mse = tf.reduce_mean(asymetric_squared_difference(out,Y,alpha)) I Looked to see where tf.squared_difference is defined, and found https://www.tensorflow.org/api_docs/python/tf/squared_difference Which says that tensorflow/python/ops/gen_math_ops.py edit: After much digging SquaredDifference is called from ops.math_grad line 999 to 1012. But it has a lot of extra gradiant functionality that I am not sure how to replicate. How would I best go about adding this functionality?
answer count: 1
downvote count: 0
has title: tensorflow Asymmetric loss function
upvote count: 1
tagged with: python
favorite count: 0
has answer: http://stackoverflow.com/a/51297217
type: UnansweredQuestion
tagged with: tensorflow
score: 1
tagged with: loss-function
type: Question

http://stackoverflow.com/comment/89347727
comment on: http://stackoverflow.com/q/51182776
score: 0
type: Comment
type: QuestionComment
has text: You should post the full error, to make it easy for us to see where it is going wrong. However, your `min()` is returning a tuple because you have added tuples to `list1`. Why do you believe you have to `split()` this tuple again. Note: you may want to `map(float, coordList...)` because currently you are `min()`ing base on the string, which is not likely what you want.

http://stackoverflow.com/comment/112521432
type: Comment
has text: @Peter What exactly is not true?
comment on: http://stackoverflow.com/a/51245742
score: 0
type: AnswerComment

http://stackoverflow.com/comment/89411427
comment on: http://stackoverflow.com/q/51215163
type: Comment
type: QuestionComment
has text: What have you tried so far?
score: 1

yaml
tags question: http://stackoverflow.com/q/51291788
tags question: http://stackoverflow.com/q/51272814
tags question: http://stackoverflow.com/q/51316491
tags question: http://stackoverflow.com/q/51287352
tags question: http://stackoverflow.com/q/51186523
tags question: http://stackoverflow.com/q/51289824
tags question: http://stackoverflow.com/q/51187751
tag name: yaml
type: Tag

http://stackoverflow.com/comment/89512946
comment on: http://stackoverflow.com/q/51265302
type: Comment
has text: The .fmu file really is a zip file, and you can open it using e.g. 7-zip. Inside the archive there is a folder named binaries, and in there you will find the binaries. What do you see in there?
score: 0
type: QuestionComment

http://stackoverflow.com/comment/89597778
type: AnswerComment
type: Comment
has text: I have removed the 'failure = failures[0]' because we are using the for loop in the end. Above information helped.
comment on: http://stackoverflow.com/a/51308264
score: 0

http://stackoverflow.com/q/51277302
has answer: http://stackoverflow.com/a/51289396
has title: Qt Designer and PyQt5 custom plugin loading TypeError
type: Question
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/89542809
has comment: http://stackoverflow.com/comment/89532287
tagged with: qt-designer
has body: I'm having a problem loading custom PyQt5 plugins with Qt Designer. The example plugins available on GitHub were working and I used them to create my own plugin which was working as well. Then yesterday Designer stopped loading any of them. When I start Designer from the CLI I get: TypeError: unwrapinstance() argument 1 must be sip.simplewrapper, not PyAnalogClockPlugin TypeError: unwrapinstance() argument 1 must be sip.simplewrapper, not BubblesPlugin TypeError: unwrapinstance() argument 1 must be sip.simplewrapper, not CounterLabelPlugin TypeError: unwrapinstance() argument 1 must be sip.simplewrapper, not PyDateEditPlugin TypeError: unwrapinstance() argument 1 must be sip.simplewrapper, not PyDateTimeEditPlugin TypeError: unwrapinstance() argument 1 must be sip.simplewrapper, not HelloGLWidgetPlugin TypeError: unwrapinstance() argument 1 must be sip.simplewrapper, not MultiPageWidgetPlugin TypeError: unwrapinstance() argument 1 must be sip.simplewrapper, not PolygonWidgetPlugin TypeError: unwrapinstance() argument 1 must be sip.simplewrapper, not PyDemoPlugin TypeError: unwrapinstance() argument 1 must be sip.simplewrapper, not PythonConsolePlugin I don't know where to start and Google-ing the issue didn't help either. I'm using Python 3.6.6, Qt 5.11.1, PyQt5 5.11.2, and Linux 4.17.5-1-ARCH. What is causing this error? How do I fix it?
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
upvote count: 1
tagged with: python
score: 1
tagged with: pyqt5

http://stackoverflow.com/comment/89422523
type: AnswerComment
has text: @임종훈 I don’t know what “the Google page” is. And I don’t know what “a flat cloud” is. And I didn’t say graphing isn’t supported on the cloud, but that _streaming_ isn’t supported. So… I have no idea how to answer any of that.
score: 0
comment on: http://stackoverflow.com/a/51220695
type: Comment

http://stackoverflow.com/comment/89484831
type: Comment
has text: One question per question, please. The second one is covered by [Bounded root finding in scipy](https://stackoverflow.com/q/32814173) with the conclusion: use constrained minimization [`least_squares`](https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.least_squares.html#scipy.optimize.least_squares)
type: QuestionComment
comment on: http://stackoverflow.com/q/51239234
score: 1

http://stackoverflow.com/comment/89478148
comment on: http://stackoverflow.com/q/51248527
score: 0
type: Comment
type: QuestionComment
has text: @Will, I think the key word is **minimal**: [mcve]. The error is likely reproducible in 5lines of code.

http://stackoverflow.com/comment/89598458
type: Comment
type: QuestionComment
has text: my logic is same as set intersection, home depot is two words and not single, i realised now, updated my Question.
score: 0
comment on: http://stackoverflow.com/q/51310599

http://stackoverflow.com/q/51294548
type: Question
tagged with: imagej
has comment: http://stackoverflow.com/comment/89567292
score: 0
has title: Measuring the length of a fraction of a pixel
tagged with: python
tagged with: roi
has comment: http://stackoverflow.com/comment/89566691
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89566690
tagged with: image-processing
has body: I have a disk that I want to cut it in wedges, just like a pizza, I did this with ImageJ, Disk but as you can see in the picture, there are some pixels that has a fraction inside a ROI and the other fraction inside the other ROI. Fractioned Pixels Is there a way to find how much fraction of the area of the pixel lies in either ROIs? Ideally, I wouldn't want to do any kind of Interpolation, and write a python code for automating that. Eventually, I'd want to measure the raw intensity of each ROI in each time frame and generate a kymograph of the resulting array. Any kind of help would be much appreciated, even if it doesn't answer my question directly.

http://stackoverflow.com/q/51251851
downvote count: 1
has comment: http://stackoverflow.com/comment/89483013
answer count: 0
type: UnansweredQuestion
has title: Wrong NumPy array calculations results
tagged with: python
has comment: http://stackoverflow.com/comment/89482789
has comment: http://stackoverflow.com/comment/89482668
favorite count: 0
has body: I am stuck trying to figure out why it dosnt work. Must say I am new in python. Trying calculate when a^d + b^d = c^d; (Fermat`s theorem) using np.arrays for best performance. Problem: wrong results in array B for d > 2. Please point me in the right direction? Thank you! Kubuntu 17.10 Python 3.6.4 |Anaconda custom (64-bit)| (default, Jan 16 2018, 18:10:19) Type "copyright", "credits" or "license" for more information. IPython 6.4.0 -- An enhanced Interactive Python. This is code example when problem shows: import numpy as np d = np.float64(4.) A = np.float64([[99001457116.0, 99536254152.0], [99002341176.0, 99914925909.0], [99029463918.0, 99750866948.0]]) B = np.float64((np.sum(A**2, axis=1)**(1/d)).reshape((A.shape[0], 1))) B
type: Question
tagged with: numpy
upvote count: 1
tagged with: arrays
tagged with: python-3.6
tagged with: calculus
score: 0

http://stackoverflow.com/comment/89450195
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51235503
has text: of course, you can perform some operations in a template, like ` {{ prob*100 }}% `. It may be better to handle this kind of operation inside the view, and pass the correct value to the template

http://stackoverflow.com/q/51234534
has comment: http://stackoverflow.com/comment/89448317
has answer: http://stackoverflow.com/a/51234584
accepted answer: http://stackoverflow.com/a/51234584
possible better answer: http://stackoverflow.com/a/51234572
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/89448413
has comment: http://stackoverflow.com/comment/89451339
has title: Will itertools.permutations always return a sorted object?
tagged with: python
type: AnsweredQuestion
has body: My problem requires me to iterate through a very large permutation of 10! (or larger) permutations : a = itertools.permutation(range(10)) My input range will always be of form range(x) and while I see in almost all cases when I iterate through a the permutations are sorted lexicographically ie a[0] = (0,1,2,3,4,5,6,7,8,9) a[1] = (0,1,2,3,4,5,6,7,9,8) and so on. Is this always a guarantee? I do not want to sort it explicitly a = sorted(itertools.permutation(range(10))) as that will convert a &lt;class 'itertools.permutations'&gt; to &lt;class 'list'&gt; which will mean python will try allocating a huge amount of memory which I would like to avoid. For eg a = itertools.permutations([1,2,3,4,5,6,7,8,9]) sys.getsizeof(a) Output 232 b = sorted(a) sys.getsizeof(b) Output 3215232 if this is not a guarantee, what is the alternative?
has comment: http://stackoverflow.com/comment/89448105
type: Question
has answer: http://stackoverflow.com/a/51234572
tagged with: python-itertools

http://stackoverflow.com/q/51182316
type: Question
has comment: http://stackoverflow.com/comment/89448441
tagged with: pyserial
accepted answer: http://stackoverflow.com/a/51182336
has body: This is the error: AttributeError: module 'serial' has no attribute 'Serial' I installed pySerial and uninstalled serial. import serial ser = serial.Serial('/dev/tty.usbmodem1d11', 9600) ser.write('5') So what is the problem? My Python is 3.6. My OS is Windows&nbsp;10.
has comment: http://stackoverflow.com/comment/89347080
answer count: 1
tagged with: python
tagged with: python-3.x
score: 0
has comment: http://stackoverflow.com/comment/89448975
has title: How do I fix this syntax error with Python serial?
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51182336
has comment: http://stackoverflow.com/comment/89347384
has comment: http://stackoverflow.com/comment/89448460
has comment: http://stackoverflow.com/comment/89346948

http://stackoverflow.com/q/51180972
has body: I have two csv files with the same column names in different orders. I need to correlate columns between both csv files between their common headers and plot a correlation plot of the data. For example from file1 and file2 I want to compare the 'ASA' column and form a correlation plot from this. I have a seperate file with all of the column names I need to compare so if can loop through the millions of files I have but pandas keeps telling me I have an attribute error when I add my 'list' to the y = data2.lines.values or x = data1.lines.values. I tried looping and making matching conditions but nothing has worked. import csv import pandas as pd import numpy as np from pandas import DataFrame import matplotlib.pyplot as plt from scipy import linspace, polyval, polyfit, sqrt, stats, randn #File1 data1 = pd.read_csv('sorted_42650files_from_the_1.7chembl_database.csv',low_memory=False) #read large csv filei #File2 data2 = pd.read_csv('sorted_60kdat_without_duplicates.csv',low_memory=False) #File3 data3 = pd.read_csv('headers.csv',low_memory=False) lines = data3.readlines() #create my x and y column for linear regression comparison based only on the descritor.csv header name x = data1.lines.values y = data2.lines.values print(x) print(y) #plot it slope, intercept, r_value, p_value, std_err = stats.linregress(x, y) plt.plot(x,y, 'o', color='purple') plt.plot(x,intercept + slope*x, color="black", label='fitted line' + ',' + '$R^2$={:.4f}'.format(r_value)) plt.suptitle('MOE ASA+ Descriptor Correlation Plot', fontsize=14) plt.xlabel('Ab Initio', fontsize=16) plt.ylabel('Molecular Mechanics', fontsize=16) plt.legend(loc=4) print('$R^2$={:.4f}'.format(r_value)) plt.show() plt.savefig('ASA+') plt.close() file data1 file data2 file data3 (all of the headers I want to correlate between the files) Thank you for any help you can give me.
accepted answer: http://stackoverflow.com/a/51181685
tagged with: scipy
tagged with: numpy
tagged with: pandas
has title: Two CSV files with same column names,. I need to perform linear regression comparing columns with same header name from both files
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51181685
type: Question
tagged with: python
answer count: 1
score: 0
tagged with: matplotlib

http://stackoverflow.com/q/51198633
tagged with: one-to-many
type: UnansweredQuestion
tagged with: django
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/89379241
score: 1
has title: Django - How to sort objects by an attribute of the first item in a sorted list of associated objects?
type: Question
has body: I want to achieve the following: I have one object, lets assume the following classes: class A(): title class B(): foreign key = A.id time #one-to-many relation I want to know what the view and template would look like if I wanted to display a list like: A.Title1 B.time #A is sorted on these ones B.time A.Title2 B.time #A is sorted on these ones B.time B.time Where each set of B() objects associated with one A() object are sorted by B.time, and the A() objects themselves are sorted by the top B.time in these A() objects. How would I achieve this? Thanks in advance! EDIT: I tried Willem van Onsen's solution, but it led me to the following outcomes: The objects I want to show: The objects that are actually shown:
tagged with: sorting
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/51198753
favorite count: 0

http://stackoverflow.com/comment/89579417
type: AnswerComment
comment on: http://stackoverflow.com/a/51300735
score: 0
type: Comment
has text: sys.path.append(/home/ec2-user/wep-rs/WEPR/weprs/api/api/voucher.py) is it again needed to import like from voucher import Voucher and creating the object for the class or directly we can access the functions under the class

http://stackoverflow.com/comment/89377548
type: Comment
comment on: http://stackoverflow.com/a/51196565
score: 0
type: AnswerComment
has text: @JinhuaWang simple fix it by convert to the string , it is a bug i think

http://stackoverflow.com/comment/89636694
score: 0
type: AnswerComment
has text: I tried both latest release (via `conda`) and pulled master branch. Both are fine on CentOS; both throw the compilation error on Mac OS X (and can be suppressed using the `-Wno-c++11-narrowing` flag).
type: Comment
comment on: http://stackoverflow.com/a/51291640

http://stackoverflow.com/q/51316688
has comment: http://stackoverflow.com/comment/89609783
has body: I had mod_wsgi working fine on RHEL/Apache2.4/python3.4/Django1.11/virtualenv. Then, I used pip within the virtualenv to upgrade numpy from 1.14.0 to 1.14.2, install pandas, and install a couple other modules. Then I restarted Apache and started getting server errors indicating AttributeError: 'module' object has no attribute 'arange' when trying to call numpy.arange, or similar errors when trying to call matplotlib.use('Agg'), etc. I replaced wsgi.py with the following and it works fine. As soon as I uncomment any of the numpy or matplotlib calls it returns a 500 error and in the apache error log it shows an error similar to AttributeError: 'module' object has no attribute ... import datetime import sys import numpy as np import matplotlib as mpl import mod_wsgi def application(env, start_response): #mpl.use('Agg') #a = np.arange(15).reshape(3, 5) #a = np.array([2,3,4]) status = '200 OK' output = 'Hello World! This is the wsgi app generated from python!' output += '\n\ncurrent time is: '+str(datetime.datetime.now()) output += '\n\nsys.executable='+sys.executable output += '\n\nsys.path='+str(sys.path) output += '\n\nsys.version=' + str(sys.version) output += '\n\nsys.prefix=' + str(sys.prefix) output += '\n\nmod_wsgi.version='+str(mod_wsgi.version) output += '\n\n\nEnvironment Variables:\n\n'+'\n'.join('%s: %s' % (k, v) for (k, v) in env.items()) output = bytes(output,'utf-8') response_headers = [('Content-type', 'text/plain'), ('Content-Length', str(len(output)))] start_response(status, response_headers) return [output] Relevant output from this wsgi.py: sys.executable=/usr/bin/python3 sys.path=['/usr/local/virtualenvs/myapp/wsgiapp', '/usr/local/virtualenvs/myapp/lib64/python34.zip', '/usr/local/virtualenvs/myapp/lib64/python3.4', '/usr/local/virtualenvs/myapp/lib64/python3.4/plat-linux', '/usr/local/virtualenvs/myapp/lib64/python3.4/lib-dynload', '/usr/lib64/python3.4', '/usr/lib/python3.4', '/usr/local/virtualenvs/myapp/lib/python3.4/site-packages'] sys.version…
answer count: 1
has comment: http://stackoverflow.com/comment/89610512
has comment: http://stackoverflow.com/comment/89611195
has answer: http://stackoverflow.com/a/51330254
tagged with: python
has comment: http://stackoverflow.com/comment/89612075
has comment: http://stackoverflow.com/comment/89611326
has comment: http://stackoverflow.com/comment/89610294
has comment: http://stackoverflow.com/comment/89610320
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89610895
tagged with: mod-wsgi
has comment: http://stackoverflow.com/comment/89629121
has comment: http://stackoverflow.com/comment/89636207
has comment: http://stackoverflow.com/comment/89610780
type: Question
accepted answer: http://stackoverflow.com/a/51330254
has title: mod_wsgi not finding modules - apache, RHEL, python3.4
has comment: http://stackoverflow.com/comment/89611024
has comment: http://stackoverflow.com/comment/89611412
tagged with: rhel
tagged with: python-3.4
score: 0

http://stackoverflow.com/a/51192188
type: Answer
upvote count: 4
downvote count: 0
has comment: http://stackoverflow.com/comment/134324936
score: 4
has body: You could use ndarray.max(). The axis keyword argument describes what axis you want to find the maximum along. keepdims=True lets you keep the input's dimensions. To get the indizes of the maxima in the columns, you can use the ndarray.argmax() function. You can also pass the axis argument ot this function, but there is no keepdims option. In both commands axis=0 describes the columns, axis=1 describes the rows. The standard value axis=None would search the maximum in the entire flattened array. Example: import numpy as np A = np.asarray( [[1, 2, 3, 4, 5], [2, 4, 5, 8, 7], [9, 8, 4, 5, 2], [1, 2, 4, 7, 2], [5, 9, 8, 7, 6], [1, 2, 5, 4, 3]]) print(A) max = A.max(axis=0, keepdims=True) max_index = A.argmax(axis=0) print('Max:', max) print('Max Index:', max_index) This prints: [[1 2 3 4 5] [2 4 5 8 7] [9 8 4 5 2] [1 2 4 7 2] [5 9 8 7 6] [1 2 5 4 3]] Max: [[9 9 8 8 7]] Max Index: [2 4 4 1 1]
answers question: http://stackoverflow.com/q/51191731

http://stackoverflow.com/q/51233683
type: AnsweredQuestion
tagged with: pyqt5
type: Question
tagged with: qwizardpage
has answer: http://stackoverflow.com/a/51236902
tagged with: qwizard
has title: Show messagebox after page load pyqt5
score: 0
accepted answer: http://stackoverflow.com/a/51236902
tagged with: pyqt
answer count: 1
has body: I have a PyQt5 Wizard and on the second page I want the behavior to change based on previous content. I have implemented initializePage def initializePage(self): if self.altThing: self.onloadbtn.show() # .. do Something QMessageBox.about(self, 'Hello', 'Hello') #Pops up before the page is rendered # do other stuff.. I want the page to load first and then do some stuff such as download files and display a progress bar etc. but not until the page loads. What happens is the QMessageBox will pop up before the page is loaded. Below is a MVCE import sys from PyQt5.QtGui import * from PyQt5.QtCore import * from PyQt5.QtWidgets import * class Wizard(QWizard): def __init__(self, parent=None): super(Wizard, self).__init__(parent) self.addPage(EnterToken(self)) self.addPage(ProcessData(self)) self.buttons = [self.button(t) for t in (QWizard.NextButton, QWizard.FinishButton)] for btn in self.buttons: btn.installEventFilter(self) def eventFilter(self, obj, event): if obj in self.buttons and event.type() == QEvent.Show: obj.setDefault(False) return super(Wizard, self).eventFilter(obj, event) class EnterToken(QWizardPage): def __init__(self, parent=None): super(EnterToken, self).__init__(parent) self.setTitle("Enter your token here") self.setSubTitle(" ") # Enter Token Widgets self.label = QLabel() self.enter_token_box = QLineEdit() self.btn = QPushButton('OK') # layout options layout = QVBoxLayout() layout.addWidget(self.label) self.label.setText("Enter Your 12 Digit Code.") layout.addWidget(self.enter_token_box) layout.addWidget(self.btn) # Enter Key TRigger self.enter_token_box.returnPressed.connect(self._EnterToken) self.btn.clicked.connect(self._EnterToken) self.setLayout(layout) def _EnterToken(self): """ Method for processing user input after the button is pressed""" pass class ProcessData(QWizardPage): """ Sensor Code Entry """ def __init__(self, parent=None): super(ProcessData, self).__init__(parent) self.altThing = True # num of logs combo box self.num_logs_combo = QComb…
tagged with: python

http://stackoverflow.com/a/51273274
has body: print(tmp_sta.append(s)) You can't combine print() and append() like this. list.append modifies the list but always returns None so you need separate commands: tmp_sta.append(s) print(s) To make your class print useful debugging information, add a __repr__ method. For example: class low: def __init__(self, n, b, c, l, m): .... def __repr__(self): return 'low({})'.format( ', '.join('{}={!r}'.format(k, getattr(self, k)) for k in ['n', 'b', 'c', 'l', 'm', 'status', 'tm_init']) )
has comment: http://stackoverflow.com/comment/89562168
score: 0
answers question: http://stackoverflow.com/q/51273207
type: Answer

http://stackoverflow.com/q/51244937
tagged with: python
has answer: http://stackoverflow.com/a/73661940
favorite count: 0
upvote count: 1
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51249971
score: 1
type: Question
answer count: 2
has title: MQTT Python-Client disconnect ungracefully
downvote count: 0
has body: I wrote basic MQTT python-client. But it disconnect ungracefully without giving any error. When i look event log file i found it's connected and same time is disconnected ungracefully. import paho.mqtt.client as mqtt Broker = "192.168.43.246" def on_connect(client, userdata, flages, rc): print("Connected with result code=",rc) client = mqtt.Client(client_id="Client123", clean_session=False, userdata=None) client.on_connect = on_connect client.connect(Broker, 1883, 60) Here i attached a snap of event log also.
accepted answer: http://stackoverflow.com/a/51249971
possible better answer: http://stackoverflow.com/a/73661940
tagged with: mqtt

http://stackoverflow.com/a/51243745
upvote count: 10
answers question: http://stackoverflow.com/q/51243702
downvote count: 0
has body: You can extract the first letter directly: df['Amino Acid'] = df['Percentage'].str[0] df['Percentage'] = df['Percentage'].str[1:]
type: Answer
score: 10

http://stackoverflow.com/comment/89395733
score: 0
type: AnswerComment
type: Comment
has text: @knelwood Oh, I expected that `.` should work like `0.` and `.0`. My bad.
comment on: http://stackoverflow.com/a/51207362

http://stackoverflow.com/comment/89428195
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51223908
has text: Thanks. finished signal would be convenient

http://stackoverflow.com/q/51230158
has title: numpy asmatrix sometimes produces an array of lists
has comment: http://stackoverflow.com/comment/89439905
has body: I am using numpy of python to convert multi dimensional data into matrix by using numpy.asmatrix(). data_array = [[] for k in range(K)] while Append data to data_array: data_array[k].append(data) mymatrix = numpy.asmatrix(data_array) The data_array ends up with K*E. While I try to use mymatrix for further manipulation, it turns out some of them works but others still remains as list. When I print it out, it looks like [[ list([..., ...]), list(..., ...) ]] Does anyone knows the potential reason for that?
tagged with: python
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/51230189
has comment: http://stackoverflow.com/comment/89439890
downvote count: 1
type: Question
tagged with: numpy
score: -1
has answer: http://stackoverflow.com/a/51237287
accepted answer: http://stackoverflow.com/a/51237287
answer count: 2
has answer: http://stackoverflow.com/a/51230189
tagged with: matrix
upvote count: 0
has comment: http://stackoverflow.com/comment/89443167
favorite count: 0

http://stackoverflow.com/comment/89508602
comment on: http://stackoverflow.com/q/51263929
has text: My friend, your comment don't help me. I went to the main page http://bbcode.readthedocs.io/en/latest/tags.html and realized, there are those "built in Tags", those doesn't include the tables, and several other things. The solution could be somehow adding the missing objects, but It is assumed that this module should have them, that's what the module is for.
score: 1
type: QuestionComment
type: Comment

variables
tag name: variables
tags question: http://stackoverflow.com/q/51319929
tags question: http://stackoverflow.com/q/51208399
tags question: http://stackoverflow.com/q/51181605
type: Tag
tags question: http://stackoverflow.com/q/51186430
tags question: http://stackoverflow.com/q/51247566
tags question: http://stackoverflow.com/q/51322864
tags question: http://stackoverflow.com/q/51201995
tags question: http://stackoverflow.com/q/51292296
tags question: http://stackoverflow.com/q/51302374
tags question: http://stackoverflow.com/q/51217871
tags question: http://stackoverflow.com/q/51215537
tags question: http://stackoverflow.com/q/51288181
tags question: http://stackoverflow.com/q/51216310
tags question: http://stackoverflow.com/q/51202148
tags question: http://stackoverflow.com/q/51212690

http://stackoverflow.com/comment/135461576
type: AnswerComment
has text: @Ja8zyjits Typecasting worked fine in my case. All numbers nicely multiply by 3600 and lose the fraction.
type: Comment
comment on: http://stackoverflow.com/a/54629675
score: 1

http://stackoverflow.com/a/51285434
accepted answer of: http://stackoverflow.com/q/51280808
downvote count: 0
answers question: http://stackoverflow.com/q/51280808
type: AcceptedAnswer
upvote count: 2
type: Answer
has body: Not hard to slap one together with pyparsing, after looking at the docs: import pyparsing as pp # from https://docs.python.org/3/library/stdtypes.html?highlight=string%20interpolation#printf-style-string-formatting PCT,LPAREN,RPAREN,DOT = map(pp.Literal, '%().') conversion_flag_expr = pp.oneOf(list("#0- +")) conversion_type_expr = pp.oneOf(list("diouxXeEfFgGcrsa%")) length_mod_expr = pp.oneOf(list("hlL")) interp_expr = (PCT + pp.Optional(LPAREN + pp.Word(pp.printables, excludeChars=")")("mapping_key") + RPAREN) + pp.Optional(conversion_flag_expr("conversion_flag")) + pp.Optional(('*' | pp.pyparsing_common.integer)("min_width")) + pp.Optional(DOT + pp.pyparsing_common.integer("max_width")) + pp.Optional(length_mod_expr("length_modifier")) + conversion_type_expr("conversion_type") ) tests = """ Now is the winter of our %s made %(adjective)s %(season)s by this %(relative)s of %(city)s %(name)s, %(name)s, %(name)s, a %4.8d deaths were not enough for %(name)s """.splitlines() for t in tests: print(t) for t,s,e in interp_expr.scanString(t): print("start: {} end: {}\n{}".format(s, e, t.dump())) print() Prints: Now is the winter of our %s made %(adjective)s %(season)s by this %(relative)s of %(city)s start: 29 end: 31 ['%', 's'] - conversion_type: 's' start: 37 end: 50 ['%', '(', 'adjective', ')', 's'] - conversion_type: 's' - mapping_key: 'adjective' start: 51 end: 61 ['%', '(', 'season', ')', 's'] - conversion_type: 's' - mapping_key: 'season' start: 70 end: 82 ['%', '(', 'relative', ')', 's'] - conversion_type: 's' - mapping_key: 'relative' start: 86 end: 94 ['%', '(', 'city', ')', 's'] - conversion_type: 's' - mapping_key: 'city' %(name)s, %(name)s, %(name)s, a %4.8d deaths were not enough for %(name)s start: 4 end: 12 ['%', '(', 'name', ')', 's'] - conversion_type: 's' - mapping_key: 'name' start: 14 end: 22 ['%', '(', 'name', ')', 's'] - conversion_type: 's' - mapping_key: 'name' start: 24 end: 32 ['%', '(', 'name', ')', 's'] - conversion_type: 's' - mapping_key: 'nam…
score: 2

http://stackoverflow.com/a/51319983
score: 0
has body: Short of placing timer above loop, as you correctly mention, you could save timer in its own module, then import it on top of the loop file. Indeed, imported modules are first executed upon import.
answers question: http://stackoverflow.com/q/51319918
type: Answer

http://stackoverflow.com/q/51299464
linked to: http://stackoverflow.com/q/9077687
tagged with: python
has answer: http://stackoverflow.com/a/51316460
has body: I recently started having a need for a task queue in my Django program, and I'm worried about how robust it will be in the future or what will need to be overcome for a production deployment. I'm using the Redis-Queue or RQ library for Python, which markets itself as easier to learn and use than something like Celery (which I haven't quite learned). Does anyone have any input on this? Do you think RQ coupled with Redis would be OK in production, or would you use something else? What do large-scale apps use for task queueing?
score: 0
answer count: 2
tagged with: django
tagged with: task
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51302458
tagged with: redis
has title: Redis-Queue (RQ) Task Queues in Production
type: Question
tagged with: production-environment

http://stackoverflow.com/comment/89400648
score: 0
comment on: http://stackoverflow.com/q/51194742
type: Comment
type: QuestionComment
has text: B = [(.3, 1.8, 28), (.3, 1.8, 21), (1.4, .8, p)] (where p is any positive number) should return a 3x2 (3 being the dimension of B's 0 axis) data structure : [[True, False], [True, True], [True, True]].

http://stackoverflow.com/a/51187663
score: 28
type: Answer
answers question: http://stackoverflow.com/q/51174691
has body: If you want to make a change to the whole notebook global: import matplotlib.pyplot as plt %matplotlib inline plt.rcParams["figure.figsize"] = [10, 5]
upvote count: 29
downvote count: 1

http://stackoverflow.com/comment/89457708
comment on: http://stackoverflow.com/a/51239426
type: AnswerComment
score: 0
type: Comment
has text: why user should go to that location? it will be already under environment variables, the issue here is user is trying in python shell instead of command line.

http://stackoverflow.com/a/51253945
has body: In tensorflow, a random operation relies on two different seeds: a global seed, set by tf.set_random_seed, and an operation seed, provided as an argument to the operation. You will find more details on how they relate in the docs. You have a different seed for each random op because each random op maintains its own internal state for pseudo-random number generation. The reason for having each random generator maintaining its own state is to be robust to change: if they shared the same state, then adding a new random generator somewhere in your graph would change the values produced by all the other generators, defeating the purpose of using a seed. Now, why do we have this dual system of global and per-op seeds? Well, actually the global seed is not necessary. It is there for convenience: It allows to set all random op seeds to a different and deterministic (if unknown) value at once, without having to go exhaustively through all of them. Now when a global seed is set but not the op seed, according to the docs, The system deterministically picks an operation seed in conjunction with the graph-level seed so that it gets a unique random sequence. To be more precise, the seed that is provided is the id of the last operation that has been created in the current graph. Consequently, globally-seeded random operation are extremely sensitive to change in the graph, in particular to those created before itself. For example, import tensorflow as tf tf.set_random_seed(1234) generate = tf.random_uniform(()) with tf.Session() as sess: print(generate.eval()) # 0.96046877 Now if we create a node before, the result changes: import tensorflow as tf tf.set_random_seed(1234) tf.zeros(()) # new op added before generate = tf.random_uniform(()) with tf.Session() as sess: print(generate.eval()) # 0.29252338 If a node is create after however, it does not affect the op seed: import tensorflow as tf tf.set_random_seed(1234) generate = tf.random_uniform(()) tf.zeros(()) # new op added after w…
score: 28
has comment: http://stackoverflow.com/comment/113863159
has comment: http://stackoverflow.com/comment/89494356
answers question: http://stackoverflow.com/q/51249811
downvote count: 0
upvote count: 28
type: Answer

http://stackoverflow.com/comment/89608343
type: Comment
type: QuestionComment
score: 0
has text: can you include the output of your 'print (data)' statement ?
comment on: http://stackoverflow.com/q/51315794

http://stackoverflow.com/q/51216169
has title: Pandas: How to group the non-continuous date column?
type: UnansweredQuestion
upvote count: 1
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/89421406
has body: I have a column in a dataframe which contains non-continuous dates. I need to group these date by a frequency of 2 days. Data Sample(after normalization): 2015-04-18 00:00:00 2015-04-20 00:00:00 2015-04-20 00:00:00 2015-04-21 00:00:00 2015-04-27 00:00:00 2015-04-30 00:00:00 2015-05-07 00:00:00 2015-05-08 00:00:00 I tried following but as the dates are not continuous I am not getting the desired result. df.groupby(pd.Grouper(key = 'l_date', freq='2D')) Is these a way to achieve the desired grouping using pandas or should I write a separate logic?
score: 0
tagged with: pandas
answer count: 1
has comment: http://stackoverflow.com/comment/89413690
favorite count: 0
tagged with: datetime
tagged with: python
has comment: http://stackoverflow.com/comment/89414831
has answer: http://stackoverflow.com/a/51216387

http://stackoverflow.com/a/51318794
score: 0
has comment: http://stackoverflow.com/comment/89697573
type: Answer
has body: import requests MY_API_KEY = 'Your API Key' gurl = 'https://maps.googleapis.com/maps/api/place/findplacefromtext/json?input=+14169743940&amp;inputtype=textquery&amp;key='+str(MY_API_KEY) r = requests.get(gurl) jdata = r.json() googleoutput = jdata["status"] print(jdata) Enter Your API Key in the place of 'Your API Key'. Your problem is the URL gurl, you need to pass the above API key variable to the URL or verify your API from console if still no results. Output: {u'status': u'ZERO_RESULTS', u'candidates': [], u'debug_log': {u'line': []}}
answers question: http://stackoverflow.com/q/51309686

http://stackoverflow.com/comment/89442709
type: Comment
has text: `context_pixels=16` so that is sometimes involved in scaling. However it may not add any pixels as I said above since I use `max()`. Say for example if `x2=224`, no additional pixels will be added to `x2`
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51229351

http://stackoverflow.com/q/51237499
favorite count: 0
linked to: http://stackoverflow.com/q/22240602
has title: How to check if a range in a list is the same?
possible better answer: http://stackoverflow.com/a/51237574
tagged with: python
downvote count: 4
type: AnsweredQuestion
upvote count: 0
score: -4
type: Question
duplicate of: http://stackoverflow.com/q/509211
duplicate of: http://stackoverflow.com/q/22240602
has comment: http://stackoverflow.com/comment/132511863
has comment: http://stackoverflow.com/comment/89453944
answer count: 2
has answer: http://stackoverflow.com/a/51237583
accepted answer: http://stackoverflow.com/a/51237583
has answer: http://stackoverflow.com/a/51237574
has body: I want to check if a certain range in a list is the same. For example: In a list I have [X,Y,X,X,X,Y,Y], and I want to see if the third, fourth, and fifth are the same. I have tried the following: list = ['X', 'Y', 'X', 'X', 'X', 'Y'] for i in list, range(2,4): if not i == 'X': print("Test") It does work, prints Test twice. Test Test I just don't want to write a bunch of this: if ... and .... and ..... and ... or .... and ...
linked to: http://stackoverflow.com/q/509211

http://stackoverflow.com/comment/89564181
score: 0
type: Comment
has text: Adding test with your version too ASAP!
comment on: http://stackoverflow.com/a/51292875
type: AnswerComment

http://stackoverflow.com/q/51308362
answer count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: scrapy
type: Question
score: 1
tagged with: pipeline
downvote count: 0
favorite count: 0
has title: Exporting to CSV file while spider is running using Scrapy
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has body: I'm trying to export scraped data to a CSV using Scrapy such that I'm able to utilize the data in the CSV file while my spider is running. Currently, I'm only able to generate a CSV file filled with data when my spider is finished scraping. My current pipeline is very simple: class ReDataSpiderPipeline(object): def open_spider(self, spider): self.file = open('stored_RE_data.csv', 'wb') self.exporter = CsvItemExporter(self.file) self.exporter.start_exporting() def process_item(self, item, spider): self.exporter.export_item(item) return item def close_spider(self, spider): self.exporter.finish_exporting() self.file.close() I've been through the Scrapy documentation and haven't been able to figure this out, but I imagine it's how many people using Scrapy would want their pipelines to work so I'm assuming I'm missing something simple. My goal is just to be able to start analyzing the CSV data as it comes in while the spider is still running rather than having to wait until the spider is finished before I can look at the data. Thanks in advance.

http://stackoverflow.com/comment/89475934
score: 2
has text: Hello ! Could you please reduce your code to a simple snippet showing what's not working ? It would be easier for the community to help you if you do so. Also, you're referring to another program, could you please embed it in the question ?
comment on: http://stackoverflow.com/q/51248067
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51277686
type: Answer
has body: Using map: 1. map+list comprehension: print(list(map(lambda x: [tuple(i.split('/')) for i in x],l))) 2. map+map: print(list(map(lambda x: list(map(lambda y: tuple(y.split('/')),x)),l))) Both of them output: [[('Di', 'in', 'QUE'), ('mana', 'wh', 'QUE'), ('lokasi', 'nn', 'INTENT'), ('laboratorium', 'nnp', 'LOC'), ('dasar', 'nnp', 'LOC'), ('?', '?', 'O')], [('Di', 'in', 'QUE'), ('mana', 'wh', 'QUE'), ('lokasi', 'nn', 'INTENT'), ('laboratorium', 'nnp', 'LOC'), ('dasar', 'nnp', 'LOC'), ('2', 'nnp', 'LOC'), ('?', '?', 'O')], [('Di', 'in', 'QUE'), ('mana', 'wh', 'QUE'), ('lokasi', 'nn', 'INTENT'), ('laboratorium', 'nnp', 'LOC'), ('lanjut', 'nnp', 'LOC'), ('?', '?', 'O')]]
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/51277552
downvote count: 0

http://stackoverflow.com/a/58347001
has body: Depending on where you're running the pipenv install command, set env variable PIP_NO_CACHE_DIR to off. In my case, I set this in my Dockerfile by having a line ENV PIP_NO_CACHE_DIR=false before RUN pipenv install
type: Answer
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/51255947
upvote count: 2

http://stackoverflow.com/a/51299578
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/51299354
score: 1
upvote count: 1
has body: It's easy to reach that, you just need to loop check if it's alpha and then pick up the alpha as key. something like the below: In [92]: key = '' ...: b = {} ...: a = ['a', '123', '643', 'b', '890', '234', '123', 'd', '432', '678' ] ...: for i in a: ...: ...: if i.isalpha(): ...: b[i]=[] ...: key = i ...: else: ...: b[key].append(i) In [94]: b Out[94]: {'a': ['123', '643'], 'b': ['890', '234', '123'], 'd': ['432', '678']} To get your second expect result, just simple do it by: In [95]: b.values() Out[95]: [['123', '643'], ['890', '234', '123'], ['432', '678']]

http://stackoverflow.com/comment/89325270
type: Comment
has text: The index of which list you want ? Maybe use a [dictionnary](https://www.tutorialspoint.com/python/python_dictionary.htm)
score: 3
comment on: http://stackoverflow.com/q/51171314
type: QuestionComment

http://stackoverflow.com/comment/89534900
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51278690
type: AnswerComment
has text: True, but if there are always 2 values for each ID, ordering should work

http://stackoverflow.com/comment/89415890
comment on: http://stackoverflow.com/q/51215919
score: 0
type: Comment
type: QuestionComment
has text: I use this option. But presence or absence of it doesn't effect overall behavior. I see session.modified = True as redundant.

http://stackoverflow.com/comment/121896129
comment on: http://stackoverflow.com/a/59474408
type: Comment
score: 1
has text: Can we get other information also using this? Note : I don't want to use aditional scrapers.
type: AnswerComment

http://stackoverflow.com/comment/89425569
type: AnswerComment
type: Comment
has text: @tarunsharma967 Renaming the variables doesn't make a difference. `x + y` creates a new list, always.
comment on: http://stackoverflow.com/a/51222514
score: 0

http://stackoverflow.com/comment/89425025
type: Comment
has text: Please make sure to have a look at the docs- [how to ask](https://stackoverflow.com/help/how-to-ask).
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51222237

http://stackoverflow.com/q/51223791
favorite count: 0
tagged with: http://stackoverflow.com/tag/zip
has title: Allow user to download zip file generated on AWS
tagged with: django
tagged with: python
upvote count: 2
type: UnansweredQuestion
score: 1
downvote count: 1
type: Question
tagged with: amazon-s3
has answer: http://stackoverflow.com/a/51224525
tagged with: amazon-web-services
has body: Here is how I do to generate ZIP and download it from a server, it works well in local development. import zipfile doc = get_object_or_404(Document,id=id_obj) filepath = doc.file.path filename = os.path.basename(doc.file.name) directory = os.path.dirname(filepath) xzip = zipfile.ZipFile(os.path.join(directory,"%s.zip" % filename), "w") xzip.write(filepath,filename) xzip.close() zip_file = open(xzip.filename, 'rb') response = HttpResponse(zip_file, content_type='application/zip') response['Content-Disposition'] = 'attachment; filename="%s.zip"' % os.path.splitext(filename)[0] return response All my static &amp; media files are uploaded to AWS in production. So I change a little bit # filepath becomes filepath = settings.MEDIA_ROOT + "/" + doc.file.name But When I try to download it, it gives me [Errno 2] No such file or directorywith the link: https://bucket_name.s3.amazonaws.com/media/public/files/file.pdf.zip the settings.MEDIA_ROOT is: AWS_ACCESS_KEY_ID = config('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = config('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = 'bucket_name' AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME AWS_PUBLIC_MEDIA_LOCATION = 'media/public' MEDIA_ROOT = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, AWS_PUBLIC_MEDIA_LOCATION) doc.file.path gives me the error: 'This backend doesn't support absolute paths', that's why I changed to MEDIA_ROOT + doc.file.name How to do that to download from AWS the zip file generated?
answer count: 1

http://stackoverflow.com/q/51264680
tagged with: plot
type: AnsweredQuestion
tagged with: matplotlib
has title: Show two plots of different natures in same figure with Matplotlib
type: Question
score: 0
accepted answer: http://stackoverflow.com/a/51264973
has body: I'm trying to plot two different plots (one is a simple figure generated by a matrix with a color scale) and the other is a graph with x and y axes from a group of points that represents an skeleton. The matrix color scale is associated with the skeleton graph. It must be shown n times in a loop, at each time that the canvas is closed, then next plot shows. But I'm only being capable of showing each figure at once, for example,let's say that I must have 43 canvas each one with a graph and a color scale matrix side by side, instead I'm getting 86 plots, one from the dots graph, the next for the scale matrix, and so on. The code is below, and so the pictures of each plot. I'm using gridspec to generate the graph, and a simple imgplot to generate the color scale matrix. from pylab import * from matplotlib import gridspec import numpy as np import sys import math import matplotlib.pyplot as plt movimento = np.loadtxt("file01.txt") qtd_posturas = int(len(movimento)/20) c = 0 lista = [] for i in range(qtd_posturas): lista.append(movimento[(i*20):((i+1)*20),:3]) matrixCoord = np.array(lista) matrixDistance= np.zeros((qtd_posturas,20,20)) for k in range(qtd_posturas): for i in range(len(matrixDistance[0])): for j in range(len(matrixDistance[0])): matrixDistance[k,i,j] = np.linalg.norm(matrixCoord[k,i,:] - matrixCoord[k,j,:]) num_plots = qtd_posturas z = 0 for m in range(num_plots): img = matrixDistance[m] imgplot = plt.imshow(img) imgplot.set_cmap('PuBu') plt.colorbar() plt.show() z += 20 esqueleto = movimento[:z,:2] x = esqueleto[:,0] y = -esqueleto[:,1] gs = gridspec.GridSpec(1, 2, width_ratios=[3, 1]) plt.figure() plt.subplot(gs[1]) plt.scatter(x,y, s=50) plt.title('Esqueleto') plt.show() Images:
answer count: 1
has comment: http://stackoverflow.com/comment/89507423
favorite count: 0
has comment: http://stackoverflow.com/comment/89507454
has comment: http://stackoverflow.com/comment/89507374
tagged with: python
has answer: http://stackoverflow.com/a/51264973
upvote count: 1
downvote count: 1

http://stackoverflow.com/comment/89355805
score: 0
has text: Please share your attempt (code) to do this.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51186450

http://stackoverflow.com/q/51189676
has title: Apply Function (MinCovDet) to a Pandas Dataframe rolling window (n x m array)
tagged with: python
has comment: http://stackoverflow.com/comment/90138112
upvote count: 2
has answer: http://stackoverflow.com/a/51586417
type: Question
has body: I want to calculate rolling robust covariance using sklearn.covariance MinCovDet. I have a dataframe df with 3000 rows and 20 columns contain dates in the index. For each row to calculate the robust covariance over the let's say last 200 days. I have tried with df.apply(lambda x: MinCovDet().fit(df[x-400:x].values)) I get a TypeError: ("Cannot convert input [date\n2004-01-02 etc ... Any idea? A more general question would be how to apply a function to a n x m array of a pandas Dataframe Many thanks
tagged with: apply
has answer: http://stackoverflow.com/a/51199969
has comment: http://stackoverflow.com/comment/89364188
answer count: 2
tagged with: pandas
score: 2
downvote count: 0
tagged with: scikit-learn
favorite count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/89573638
comment on: http://stackoverflow.com/q/51298207
type: Comment
score: 0
has text: Looks like you have an empty selection here: `var svg = d3.select("#d3-example").select("svg");` - you have an element with the ide `d3-select`, but it doesn't contain an svg. You could try to add an svg to the `d3-example` div: ` `, but I'm also not seeing things needed for a force layout such as a tick function.
type: QuestionComment

http://stackoverflow.com/q/51218470
score: -1
has answer: http://stackoverflow.com/a/51218529
has comment: http://stackoverflow.com/comment/89418017
has body: So for a while now i've been trying to complete this exercise. The idea is to store inputs of numbers in a list, until the word 'done' is entered. Then print the minimal and maximal values of integers. And it seems i can't get it to work however many solutions i've tried, and it raised some stupid questions i would love to get answers for. So here's my best try i guess: while True: mylist=[] mylist=[mylist.append(input('Please enter a number'))] if 'done' in mylist: print(min(mylist[:len(mylist)-4])) print(max(mylist[:len(mylist)-4])) break And unsurprisingly it doesn't work, and i've no idea why, and i've exhausted all of my ideas to get it to work. But i have i stupid question. If i declare a list in a loop like i did it here, will the declaration make it empty again while it loops a second time? If it does, then how do i declare list and use it in a loop when Python doesn't want me to use global variables? Also i might have used 'break' here incorrectly, but it doesn't really matter, since the code doesn't go that far, it's just reading inputs.
has title: Stuck with a list in a loop
downvote count: 1
accepted answer: http://stackoverflow.com/a/51218529
upvote count: 0
has comment: http://stackoverflow.com/comment/89418005
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51218527
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/51218527
answer count: 2
tagged with: python

http://stackoverflow.com/q/51221851
possible better answer: http://stackoverflow.com/a/51222106
has answer: http://stackoverflow.com/a/51222106
type: Question
accepted answer: http://stackoverflow.com/a/51221926
answer count: 2
tagged with: for-loop
downvote count: 0
has body: In my data frame I need to remove columns that contain a specific character. In order to search for those columns, I am trying to write a for loop in python that iterate over each column and, if find a column with the unwanted character, this column has to be dropped out. My data frame appears like this and I need to drop col3 and col5 that have 'f' and 't' col1 col2 col3 col4 col5 col6 1245 pink f Mar f f 245 green f Feb t f 1237 grey t Apr f f 267 black f Sep t f I am trying to write a script similar to this for col in df.items(): if df[col] == 'f' df = df.drop([col], axis=1)
tagged with: pandas
favorite count: 0
has answer: http://stackoverflow.com/a/51221926
upvote count: 1
tagged with: python
has title: Searching for element in a column by iterating over the column, pandas
type: AnsweredQuestion
score: 1

http://stackoverflow.com/comment/89466998
type: QuestionComment
comment on: http://stackoverflow.com/q/51244200
score: 0
has text: Can I add it as a solution?
type: Comment

http://stackoverflow.com/comment/89501559
type: QuestionComment
comment on: http://stackoverflow.com/q/51261043
has text: I think thats is array, but why the error say that is not array ??
score: 0
type: Comment

http://stackoverflow.com/q/51292589
has comment: http://stackoverflow.com/comment/89562996
has comment: http://stackoverflow.com/comment/89563238
tagged with: arrays
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/51292712
type: AnsweredQuestion
tagged with: list
has comment: http://stackoverflow.com/comment/89563020
upvote count: 1
type: Question
has title: unique values array in loop
has comment: http://stackoverflow.com/comment/89565587
score: 1
accepted answer: http://stackoverflow.com/a/51292712
has body: I hope you can help me. I have the follwoing problem. I have an array made of random numbers. Given a value n, I need to choose the n unique numbers from that array ,and then iterate over it comparing the next element with the previous n unique numbers. I have this until now: import random len1=30 array1=[] for j in range(1,len1): z=random.randint(1,30) array1.append(z) n=5 k=0 l=n for idx,val in enumerate(array1): if idx&gt;n-1: print(val) array2=array1[k:l] for p in array2: if p == val: #do things ok=1 else: ok=2 k=k+1 l=l+1 Overall the behaviour of this routine is good, however it doesn't take into account the uniqueness of the numbers of array2. My question is: How can I have a vector of unique n values extracted from array1? Just one condition I cannot look "forward" in the vector. I have to use always a lower index of array1 than the actual idx in the loop. In another words, if I have n =5 and: array1=[1,2,3,4,5,6,7,7,8,9] and I am in the idx 8 (i.e = array2=[3,4,5,6,7] (in any order)

http://stackoverflow.com/a/51527728
has body: Try to do following command instead of all go to terminal and type $ easy_install Flask-Session If it shows an error,use sudo before it , If it shows any error please let me know also feel free to upvote
type: Answer
answers question: http://stackoverflow.com/q/51313324
score: 0

http://stackoverflow.com/a/51178307
downvote count: 1
has body: try to open cmd as administrator and then: idle pythonPath.py or if you are using linux sudo idle pythonPath.py
answers question: http://stackoverflow.com/q/51178050
has comment: http://stackoverflow.com/comment/89339714
upvote count: 0
type: Answer
score: -1

http://stackoverflow.com/comment/89489763
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51255403
has text: I think you mean `np.array(...)` but `np.logspace` already returns an array, so that's unnecessary.

http://stackoverflow.com/comment/89411790
type: QuestionComment
comment on: http://stackoverflow.com/q/51214979
has text: @WiktorStribiżew Thanks for commenting. I prefer to consult with expert in the domain before coding.
score: 0
type: Comment

http://stackoverflow.com/comment/91829899
type: Comment
has text: Just curious: is it possible to _unset_ environment variables when exiting a pipenv-managed environment? For the record, I'm using the postactivate/postdeactivate in virtualenvwrapper to do that.
score: 1
comment on: http://stackoverflow.com/a/51231777
type: AnswerComment

http://stackoverflow.com/a/51315748
accepted answer of: http://stackoverflow.com/q/51272288
type: Answer
upvote count: 4
has body: Like others I am a bit unclear. From what I understand all you want is a vector that will take you from one point to another point. This is just basic vector addition and is very simple. I made so it works for any dimension not just the third. def multiDimenDist(point1,point2): #find the difference between the two points, its really the same as below deltaVals = [point2[dimension]-point1[dimension] for dimension in range(len(point1))] runningSquared = 0 #because the pythagarom theorm works for any dimension we can just use that for coOrd in deltaVals: runningSquared += coOrd**2 return runningSquared**(1/2) def findVec(point1,point2,unitSphere = False): #setting unitSphere to True will make the vector scaled down to a sphere with a radius one, instead of it's orginal length finalVector = [0 for coOrd in point1] for dimension, coOrd in enumerate(point1): #finding total differnce for that co-ordinate(x,y,z...) deltaCoOrd = point2[dimension]-coOrd #adding total difference finalVector[dimension] = deltaCoOrd if unitSphere: totalDist = multiDimenDist(point1,point2) unitVector =[] for dimen in finalVector: unitVector.append( dimen/totalDist) return unitVector else: return finalVector EDIT, forgot to include usage: vector = findVec([0,0,0],[3,6,8])# you can also set unitCircle to True &gt;&gt;[3,6,8]
answers question: http://stackoverflow.com/q/51272288
type: AcceptedAnswer
downvote count: 0
score: 4

http://stackoverflow.com/comment/89364309
score: 0
type: QuestionComment
has text: Your object should store the figure (what you call `canvasHandle` here). E.g. `self.fig = fig` in the init method.
type: Comment
comment on: http://stackoverflow.com/q/51186724

http://stackoverflow.com/a/51370520
has body: The code works fine. Apparently, I had to download a specific set of drivers to make the PS3 controller compatible with windows so it could be read as an XBOX 360 controller. There were some tutorials online that used SCP ToolKit driver installer to make the controller compatible, however, it did make it so I couldn't use my Bluetooth mouse for some reason.
type: AcceptedAnswer
score: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/51253184
has comment: http://stackoverflow.com/comment/89713435
answers question: http://stackoverflow.com/q/51253184

http://stackoverflow.com/a/51614167
score: 7
answers question: http://stackoverflow.com/q/51200369
accepted answer of: http://stackoverflow.com/q/51200369
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: Inspired by Roll rows of a matrix independently's solution, here's a vectorized one based on np.lib.stride_tricks.as_strided - from skimage.util.shape import view_as_windows as viewW def strided_indexing_roll(a, r): # Concatenate with sliced to cover all rolls p = np.full((a.shape[0],a.shape[1]-1),np.nan) a_ext = np.concatenate((p,a,p),axis=1) # Get sliding windows; use advanced-indexing to select appropriate ones n = a.shape[1] return viewW(a_ext,(1,n))[np.arange(len(r)), -r + (n-1),0] Sample run - In [76]: a Out[76]: array([[4, 0, 0], [1, 2, 3], [0, 0, 5]]) In [77]: r Out[77]: array([ 2, 0, -1]) In [78]: strided_indexing_roll(a, r) Out[78]: array([[nan, nan, 4.], [ 1., 2., 3.], [ 0., 5., nan]])
upvote count: 7

http://stackoverflow.com/comment/89531900
comment on: http://stackoverflow.com/a/51276884
score: 0
type: Comment
type: AnswerComment
has text: Unless you fully trust everyone that could interfere with the contents of that page, yes. And even if you think you do, why take that risk?

http://stackoverflow.com/comment/89544446
comment on: http://stackoverflow.com/a/51283438
has text: can you tell which one will be faster first one or the second for large dataframe?
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/51178408
score: 1
answers question: http://stackoverflow.com/q/51177900
has comment: http://stackoverflow.com/comment/89339653
has body: you can use import os url = "google.com" os.system('start chrome ' + url) for open new tab and you can use import requests request.post(url,json/data) for post request
upvote count: 1
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/89339391

http://stackoverflow.com/comment/89492546
type: Comment
score: 3
comment on: http://stackoverflow.com/q/51256630
type: QuestionComment
has text: If you just want to process the data as codepoints, use a different format than a Python string. Something like `''.join(format(ord(c), '04x') for c in a)` might do well for that, or you could space separate things if that made the processing easier.

http://stackoverflow.com/comment/89513179
comment on: http://stackoverflow.com/a/51265784
type: Comment
score: 0
has text: Thanks, the class method is interesting. TIL
type: AnswerComment

http://stackoverflow.com/q/51320926
downvote count: 0
favorite count: 0
has body: This is the problem: You try to run a python script that you didn't write yourself, and it is missing a module. Then you solve that problem and try again - now another module is missing. And so on. Is there anything, a command or something, that can go through the python sources and check that all the necessary modules are available - perhaps even going as far as looking up the dependencies of missing modules online (although that may be rather ambitious)? I think of it as something like 'ldd', but of course this is much more like yum or apt-get in its scope. Please note, BTW, I'm not talking about the package dependencies like in pip (I think it is called, never used it), but about the logical dependencies in the source code.
type: Question
score: 3
has answer: http://stackoverflow.com/a/70687145
tagged with: python
possible better answer: http://stackoverflow.com/a/70687145
has answer: http://stackoverflow.com/a/51321208
upvote count: 3
answer count: 2
accepted answer: http://stackoverflow.com/a/51321208
has comment: http://stackoverflow.com/comment/89618031
has title: Is there an ldd like command for python
type: AnsweredQuestion

http://stackoverflow.com/q/51245686
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/89470174
has comment: http://stackoverflow.com/comment/89471215
upvote count: 1
has comment: http://stackoverflow.com/comment/89472136
answer count: 1
has comment: http://stackoverflow.com/comment/89473247
has title: parent-child json from csv using python
has comment: http://stackoverflow.com/comment/89469984
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has body: I'm trying to use Python to turn data from a CSV into a JSON having parent-child transformation. I am able to make it according to the columns specified in my .csv file but I want something more to be added which can be a metadata to the node, or the header of the csv file can be as metadata. my text.csv Team,Task,Country,ID,ID2 Team C,Processing,US,67,34 Team C,Review,US,734,56 Team C,Support,US,34,43 I want the following output: {"name": "flare", "test": "flare", "children": [ { "name": "Team C", "test": "TEAM", "children": [{ "name": "Processing", "test": "Task", "children": [{ "name": "US", "test": "[ID: 67, ID2: 34]", "size": 1983 }, { "name": "Review", "test": "Task", "size": 1675 }, { "name": "Support", "test": "Task", "size": 2042 }, ] }, ] }, ] }; Python Code: import csv import json class Node(object): def __init__(self, name, size=None): self.name = name self.children = [] self.size = size def child(self, cname, size=None): child_found = [c for c in self.children if c.name == cname] if not child_found: _child = Node(cname, size) self.children.append(_child) else: _child = child_found[0] return _child def as_dict(self): res = {'name': self.name} if self.size is None: res['children'] = [c.as_dict() for c in self.children] else: res['size'] = self.size return res root = Node('Flare') with open('/tmp/test.csv', 'r') as f: reader = csv.reader(f) reader.next() for row in reader: grp1, grp2, grp3, size = row root.child(grp1).child(grp2).child(grp3, size) print json.dumps(root.as_dict(), indent=4) where "test" is some data that I want to be printed in the .json. Kindly help me for the same. Stuck and wasted many hours but couldn't find any. TIA :)
favorite count: 0
downvote count: 0
type: UnansweredQuestion
type: Question
has answer: http://stackoverflow.com/a/51259815
score: 1

http://stackoverflow.com/comment/89530959
score: 0
has text: Glad you got it to work :) I haven't worked on Python much so *.boto file I have no idea what that is ...:P
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51250674

http://stackoverflow.com/q/51231535
tagged with: anaconda
score: 1
type: Question
has body: I have set a virtual environment with anaconda on windows 10 I set the .condarc file with proxy setting the conda install commands work fine but the pip install (via same virtual env) does not work as cannot access network what should be set especially for pip? I put the proxy settings in the condarc proxy_servers: http: http://myproxy.coo:8080 https: https://myproxy.com:8081
answer count: 1
has answer: http://stackoverflow.com/a/51231706
favorite count: 0
has title: Configuring Anaconda proxy works for conda and not for pip
upvote count: 2
has comment: http://stackoverflow.com/comment/99743669
tagged with: python
accepted answer: http://stackoverflow.com/a/51231706
downvote count: 1
linked to: http://stackoverflow.com/q/14149422
type: AnsweredQuestion

http://stackoverflow.com/a/51306764
type: Answer
score: 2
type: AcceptedAnswer
downvote count: 0
has body: You can use style.Styler.apply with DataFrame of styles with numpy.select for filling: d = {'col1': ['a', 'b'], 'col2': [21, 22], 'col3': [0, -51]} df = pd.DataFrame(data=d) def color_negative_red(x): #select only numeric columns x1 = x.select_dtypes(np.number) c1 = 'color: red' c2 = 'color: green' c3 = '' #boolean masks m1 = x1 &lt; -1 m2 = x1 &gt; 1 #numpy array by conditions arr = np.select([m1, m2], [c1, c2], default=c3) df1 = pd.DataFrame(arr, index=df.index, columns=x1.columns) #added strings columns filled by c3 string df1 = df1.reindex(columns=x.columns, fill_value=c3) return df1 df.style.apply(color_negative_red, axis=None)
accepted answer of: http://stackoverflow.com/q/51306491
upvote count: 2
answers question: http://stackoverflow.com/q/51306491

http://stackoverflow.com/comment/89470873
comment on: http://stackoverflow.com/q/51244141
type: Comment
type: QuestionComment
score: 0
has text: Could be something to do with png color profiles

http://stackoverflow.com/comment/89358959
type: Comment
score: 1
has text: Ohhh Yeaaah. Because it only appears on Intents which has slots on it. Otherwise none and throw a KeyError. Thanks for this.
comment on: http://stackoverflow.com/a/51187307
type: AnswerComment

awk
tag name: awk
type: Tag
tags question: http://stackoverflow.com/q/51215163
tags question: http://stackoverflow.com/q/51189963
tags question: http://stackoverflow.com/q/51234935

http://stackoverflow.com/q/51279181
tagged with: python
tagged with: dictionary
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51279311
score: -5
has comment: http://stackoverflow.com/comment/89535844
tagged with: http://stackoverflow.com/tag/json
type: Question
has title: how to format the text-file data to a specific standard JSON
downvote count: 5
has comment: http://stackoverflow.com/comment/89536040
accepted answer: http://stackoverflow.com/a/51279311
possible better answer: http://stackoverflow.com/a/51279723
has answer: http://stackoverflow.com/a/51279723
answer count: 2
upvote count: 0
has body: I have data in a text file (test.txt), as below format ABCD=123=Durham EFGH=456=Nottingham IJKL=789=Peterborough I want to convert it to a standard json/dictionary (list of items) as below { "data":[ { "name":"ABCD", "id":"123", "place":"Durham", }, { "name":"EFGH", "id":"456", "place":"Nottingham", }, { "name":"IJKL", "id":"789", "place":"Peterborough", }, ] } How can i achieve this ?
favorite count: 0

http://stackoverflow.com/q/51289482
favorite count: 0
type: UnansweredQuestion
has title: Make new list of dictionaries from existing list of dictionaries?
score: -3
has answer: http://stackoverflow.com/a/51289836
tagged with: python
tagged with: dictionary
has body: I have the following list of dictionaries: dict1 = [{"id": 1, "name": "tamara", "age":23}, {"id": 1, "name": "mia", "age":14}, {"id": 1, "name": "teo", "age":33}, {"id": 2, "name": "maya", "age":30}} I would like to create new list of dictionaries from the existing list of dictionaries where If I have the same "id":1 three times in dict1 then don't repeat them in the list and rather have dict in a dict: dict2 = [{"id": 1, newkey: [{"name": "tamara", "age":23}, {"name":"mia", "age":14}, {"name": "teo", "age":33}]}, {"id": 2, "name": "maya", "age":30}} This is what I want to achieve any suggestion how?
upvote count: 0
has answer: http://stackoverflow.com/a/51289607
type: Question
answer count: 2
downvote count: 3
has comment: http://stackoverflow.com/comment/89556777

http://stackoverflow.com/comment/89595115
has text: yeah, that was why I asked for the file name :)
comment on: http://stackoverflow.com/a/51309294
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/51284483
upvote count: 3
has comment: http://stackoverflow.com/comment/89686364
accepted answer of: http://stackoverflow.com/q/51284315
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51284315
type: Answer
has comment: http://stackoverflow.com/comment/89687977
has body: I believe the answer is no -- you are not going to be able to do a simple conversion to C for the whole project. At least, not in a way that is likely to give you better performance. Also, the libraries you have listed are mostly implemented in C already, so the calls to those libraries are generally fast. Have you profiled the code? I think you would have more luck if you can identify where the bottle-necks are rather than attempt a total conversion.
score: 3

http://stackoverflow.com/comment/89601351
has text: Yeah I understand that, I just didn't know if in those cases you would want all 3-4 rows listed, and how you could go about grouping the pair-wise differences. Because it could be ambiguous if you just returned `abc 4 abc 3 abc 2 abc 1`
score: 0
comment on: http://stackoverflow.com/q/51311274
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89512660
comment on: http://stackoverflow.com/q/51267159
score: 0
type: QuestionComment
has text: Python dictionaries aren't sorted, by definition, and you wanted to remove counter, not the brackets
type: Comment

http://stackoverflow.com/comment/89604833
type: Comment
has text: I will try this code and the excercise later tonight when I can and send my answer then, thank you for the write up! Another question I thought of is how would you count the number of nodes in the tree? Would this recursion method work as well?
comment on: http://stackoverflow.com/a/51313782
type: AnswerComment
score: 0

http://stackoverflow.com/comment/89469062
score: 2
has text: Because `b` is a `float`.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51245310

stripe-payments
tags question: http://stackoverflow.com/q/51243465
tag name: stripe-payments
tags question: http://stackoverflow.com/q/51315823
type: Tag

http://stackoverflow.com/q/51197439
linked to: http://stackoverflow.com/q/522563
has comment: http://stackoverflow.com/comment/89376652
accepted answer: http://stackoverflow.com/a/51197469
has comment: http://stackoverflow.com/comment/89377007
score: -1
has comment: http://stackoverflow.com/comment/89376848
has comment: http://stackoverflow.com/comment/89376681
duplicate of: http://stackoverflow.com/q/522563
has comment: http://stackoverflow.com/comment/89376604
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/89376659
favorite count: 0
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/51197469
has comment: http://stackoverflow.com/comment/89376597
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89376583
has body: my_dict = {k:v for k, v in sorted_freq} # sorted_freq is a list containing key:value. {'like': 4870, 'taste': 4508, 'good': 3569, 'flavor': 3449, 'one': 3217, 'product': 3197, 'use': 3165, 'love': 3141, 'great': 3056, 'eat': 1614...} How do I replace the Key in this dictionary by natural numbers starting from 1 for all the Keys in dictionary? [('like', 4870), ('tast', 4508), ('good', 3569), ('flavor', 3449), ('one', 3217), ('product', 3197), ('use', 3165), ('love', 3141), ('great', 3056), 'get', 2400)...]
downvote count: 1
linked to: http://stackoverflow.com/q/39980323
type: Question
has title: Replace the Keys in a dictionary by Integers

http://stackoverflow.com/q/51229740
possible better answer: http://stackoverflow.com/a/73027154
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/89439947
upvote count: 3
has comment: http://stackoverflow.com/comment/89439852
has answer: http://stackoverflow.com/a/73027154
accepted answer: http://stackoverflow.com/a/51230426
type: Question
answer count: 2
has title: How to draw a semi-transparent circle in Pygame?
downvote count: 0
has answer: http://stackoverflow.com/a/51230426
has body: I'm trying to draw a semi-transparent circle in Pygame. Here is my code: import pygame pygame.init() clock = pygame.time.Clock() screen=pygame.display.set_mode((width,height)) while True: msElapsed = clock.tick(100) screen.fill((0,0,0,255)) pygame.draw.circle(screen,(30,224,33,100),(250,100),10) pygame.display.update() for event in pygame.event.get(): if event.type==pygame.QUIT: exit() I want to use RGBA as circle color. But the circle is fully colored. What's the problem with my code?
linked to: http://stackoverflow.com/q/31989468
tagged with: pygame
has comment: http://stackoverflow.com/comment/89439798
linked to: http://stackoverflow.com/q/6339057
favorite count: 0
has comment: http://stackoverflow.com/comment/89439660
has comment: http://stackoverflow.com/comment/89439867
tagged with: python

http://stackoverflow.com/q/51189892
type: Question
has body: I need to work on a SET data type and find all matching patterns. I have a working code: d=SET type input fin_list=[] for i in d: mat = re.findall(r"\w+\.\w+",str(i)) if mat: fin_list.append(' '.join(mat)) print ','.join(fin_list) e.g: Input: set(['databasename.tablename', 'hello', 'fact.table']) Output: databasename.tablename,fact.table Please suggest an efficient and pythonic way to do it.
tagged with: python-2.7
score: 0
has answer: http://stackoverflow.com/a/51190751
answer count: 3
has comment: http://stackoverflow.com/comment/89362615
has answer: http://stackoverflow.com/a/51190812
type: UnansweredQuestion
has title: Extract matching expressions from a SET data type
tagged with: python
has answer: http://stackoverflow.com/a/51190597

http://stackoverflow.com/q/51233859
type: UnansweredQuestion
tagged with: python
has title: Python subprocess kill is not affecting SSH command as same as manually killing it on command line
has comment: http://stackoverflow.com/comment/89477894
type: Question
has body: I have a SSH command that triggers an external application on the remote server, once this external application is triggered then it opens in several processes. One of my requirements is that once the SSH is killed then all of the processes that was opened by it on the remote server will also be killed. On one hand while using command line manually I succeeded to fill the above requirement as following: ssh -t -t root@1.2.3.4 &lt;command that opens in multi-processes&gt; cntrl + c =&gt; closes all remote processes successfully On the other hand the above doesn't work when I attempt to execute it by using python subprocess.popen: #Lets assume that below SSH command opens 4 processes of the external application p = subprocess.Popen(ssh_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) p.kill() =&gt; Kills only one of the remote processes Anyone have an idea what causes a different behavior between the above two methods?
score: 2
tagged with: signals
downvote count: 0
has comment: http://stackoverflow.com/comment/89468058
has comment: http://stackoverflow.com/comment/89446780
tagged with: ssh
has comment: http://stackoverflow.com/comment/89472044
favorite count: 0
answer count: 0
upvote count: 2

http://stackoverflow.com/a/51261774
has comment: http://stackoverflow.com/comment/89503437
has comment: http://stackoverflow.com/comment/89501800
type: Answer
upvote count: 12
accepted answer of: http://stackoverflow.com/q/51261740
downvote count: 0
answers question: http://stackoverflow.com/q/51261740
score: 12
type: AcceptedAnswer
has body: Use numpy.where: df['val'] = np.where(df['category'] == 'c1', df['val'].apply(f), df['val']) Or filter with loc: mask = df['category'] == 'c1' df.loc[mask, 'val'] = df.loc[mask, 'val'].apply(f)

http://stackoverflow.com/q/51260816
has title: Discord.py 'Channel Object has no attribute create_ytdl_player
type: UnansweredQuestion
tagged with: python
score: 1
type: Question
has body: Good evening, everyone. I'm currently writing a Discord bot for my friends and I to play music from YouTube URL's in our voice channel. I've been going off of discord.py's API reference to create it, but I'm facing an annoying error. Upon runtime, I see this: AttributeError: 'Channel' object has no attribute 'create_ytdl_player' I also do have the youtube-dl module installed. Below is my complete code. Thank you for any comments. import discord from discord.ext import commands from discord.ext.commands import Bot import asyncio import random bot = commands.Bot(command_prefix='!') @bot.command(pass_context=True) async def play(ctx): voice = ctx.message.author.voice.voice_channel await bot.join_voice_channel(voice) url = 'some_url' player = await voice.create_ytdl_player(url) bot.run(NO TOKEN 4 U)
has answer: http://stackoverflow.com/a/51261436
upvote count: 2
answer count: 1
downvote count: 1
tagged with: discord
favorite count: 0

http://stackoverflow.com/q/51290516
answer count: 1
downvote count: 0
tagged with: ios
tagged with: android
has title: Can I create based on Python code executable code for Android and/or iOS?
has answer: http://stackoverflow.com/a/51419755
tagged with: python
has body: I developed in Python an algorithm library (+ usage of e.g. pandas and numpy) and I search a way to deploy those algorithms on Android and iOS without rewritting the code native or in any other language. After exploring several options, I see four major possibilities how to solve the Python migration: Translate the Python code into native code (Java or Swift/Objective-C) for each platform (which I do not prefer as keeping the same code in line seems a lot of redundant work) Translate the Python code into C or C++ which is executable by both OS (unfortunately, I am not fluent in C/C++ and I think I won't be ;)) But there are tools or interpreters as Cypthon or Nuikta which can maybe translate the Python code into executable C or C++ versions? Use Kivy to create a Python based app for both OS, however I do not want a complete .apk instead just a AAR or library that can I use as a module by other apps (I am not sure if this works) With the help of Chaquopy run Python code in Android via an Python interpreter. However, I do not see any comparable solution for iOS... Spanning around these four options, I have several questions: Is it possible with Cython, Nuitka, or any other tool to translate Python code with all dependencies into executable C/C++ code that can be used by Android and iOS? Can I use Kivy to create a library (e.g. like this on Android or a library package on iOS) Is there any obvious option I miss? I know that using native code will be probably the fastest solution whereas automatic generated code may have flaws and is kind of inefficient (and one has always to rely on the maintainer). Nevertheless, I would now prefer the way to keep the Python code as my core as long as I am still in a prototype phase, would be great to hear the community's view!
favorite count: 0
tagged with: c++
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/134324873
upvote count: 1
type: Question
score: 1
tagged with: http://stackoverflow.com/tag/c

http://stackoverflow.com/comment/89504312
comment on: http://stackoverflow.com/q/51263220
type: QuestionComment
has text: Can you add your Posts model?
type: Comment
score: 1

http://stackoverflow.com/a/51278184
type: Answer
has body: Lambda layers in Keras help you to implement functionality that is not prebuilt and which do not require trainable weights. So you get this liberty to implement your own logic as in this case 'Log' This can also be done using keras Lambda layer as below: from keras.layers import Lambda import keras.backend as K Define your function here: def logFun(x): return keras.backend.log(x) And later create a lambda layer: model.add(Lambda(logFun, ...))
answers question: http://stackoverflow.com/q/51277748
has comment: http://stackoverflow.com/comment/89535689
score: 0

http://stackoverflow.com/q/51267652
has comment: http://stackoverflow.com/comment/89513582
type: Question
has comment: http://stackoverflow.com/comment/89513947
has answer: http://stackoverflow.com/a/51267750
has title: why cant i get my "def" functions to output text correctly?
has answer: http://stackoverflow.com/a/51267700
has comment: http://stackoverflow.com/comment/89513707
has body: When I run my script there is no output. It just does not output any text. #!/usr/bin/env python #coding: utf-8 def main_menu(): print "this is the main menu" What am I doing wrong?
answer count: 3
upvote count: 0
score: -6
favorite count: 0
has answer: http://stackoverflow.com/a/51267739
accepted answer: http://stackoverflow.com/a/51267739
duplicate of: http://stackoverflow.com/q/33816697
tagged with: python
possible better answer: http://stackoverflow.com/a/51267700
linked to: http://stackoverflow.com/q/33816697
downvote count: 6
type: AnsweredQuestion

nltk
tags question: http://stackoverflow.com/q/51219752
tags question: http://stackoverflow.com/q/51309278
tags question: http://stackoverflow.com/q/51308482
tags question: http://stackoverflow.com/q/51243650
tags question: http://stackoverflow.com/q/51213768
tags question: http://stackoverflow.com/q/51291380
tags question: http://stackoverflow.com/q/51287590
tags question: http://stackoverflow.com/q/51239434
tags question: http://stackoverflow.com/q/51201830
tags question: http://stackoverflow.com/q/51309446
tags question: http://stackoverflow.com/q/51178551
tag name: nltk
tags question: http://stackoverflow.com/q/51316438
tags question: http://stackoverflow.com/q/51198120
tags question: http://stackoverflow.com/q/51208208
tags question: http://stackoverflow.com/q/51324178
tags question: http://stackoverflow.com/q/51189880
tags question: http://stackoverflow.com/q/51214026
type: Tag
tags question: http://stackoverflow.com/q/51210929

http://stackoverflow.com/comment/89409361
score: 1
has text: Great, Just i want to try to avoid: name1 = models.ForeignKey(B), name2 = models.ForeignKey(C), How can i avoid this?
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51214136

http://stackoverflow.com/a/51258808
score: 1
accepted answer of: http://stackoverflow.com/q/51258736
answers question: http://stackoverflow.com/q/51258736
upvote count: 1
has body: I beleive need map if account_id in df2 values are unique: df1['label'] = df1['account_id'].map(df2.set_index('account_id')['label']) If not unique: s = df2.drop_duplicates(subset=['account_id']).set_index('account_id')['label'] df1['label'] = df1['account_id'].map(s)
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89496237
downvote count: 0
has comment: http://stackoverflow.com/comment/89496509
type: Answer

http://stackoverflow.com/q/51277484
has answer: http://stackoverflow.com/a/51277976
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51277976
has answer: http://stackoverflow.com/a/51277728
type: Question
answer count: 2
possible better answer: http://stackoverflow.com/a/51277728
score: 0
has title: Python Selenium: element is not attached to the page document error acting strangely
tagged with: python
has body: Essentially none of the traditional fixes are working. I have tried implicit and explicit waits, and waiting for the element to be clickable. As you can see below, the stack trace is a standard stale element exception, but the line of code beneath it (what throws the error), should be enough to stop the error I would think? Even stranger, the error does not throw consistently. I would be selenium.common.exceptions.StaleElementReferenceException: Message: stale element reference: element is not attached to the page document add_account = wait.until(EC.element_to_be_clickable((By.XPATH,"//span[.='Add another account']" )))
tagged with: selenium

http://stackoverflow.com/comment/89366558
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51177430
has text: This is still not working. I still get the same missing modules.
score: 0

http://stackoverflow.com/q/51231925
has body: I have a TensorFlow model in which I want to pass an image to it in order for it to determine the object within the image. However, the model is complaining of the shape of the image saying it wants it in the form (1, 1, 1, 2048) however it's receiving (1, 7, 7, 2048). I have tried doing a numpy.reshape() on the image by doing either numpy.reshape(myObj, (1, 1, 1, 2048)) or numpy.reshape(myObj, (1, 1, 1, -1)). However, the former just complains that it can't reshape array of size 100352 to (1, 1, 1, 2048) and the latter resizes the last element of the array to the multiple of (7, 7, 2048), i.e. 100352. How would one go about reshaping an odd array size, or is this not how Numpy shapes/reshapes work? Is there an alternative way to do what I'm asking for if not possible with Numpy?
answer count: 1
has comment: http://stackoverflow.com/comment/89444429
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/51231576
has answer: http://stackoverflow.com/a/51233015
type: Question
tagged with: numpy
tagged with: arrays
has title: Numpy - How to reshape odd array sizes?
score: 0

http://stackoverflow.com/q/51186355
tagged with: python
tagged with: telnet
score: 2
has title: Send telnet command in python
downvote count: 0
type: UnansweredQuestion
tagged with: telnetlib
has answer: http://stackoverflow.com/a/51187371
has body: I'm trying to send command in tetnet but it's not working. i tried different code find in this forum but no one works. it's for rebooting a device. i'm using python 3.6. import telnetlib host = "192.168.1.0" port = 23 timeout = 100 session = telnetlib.Telnet(host, port, timeout) session.write("administrator\n").encode('ascii') session.write("password\n").encode('ascii') session.write("reboot\n").encode('ascii')
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/76169240
type: Question
upvote count: 2
answer count: 2
has comment: http://stackoverflow.com/comment/89477522

http://stackoverflow.com/a/51169852
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/51169415
has comment: http://stackoverflow.com/comment/89322364
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/89322387
has body: You can do it like this: df['cgpa'] = df.groupby('St_id')['sgpa'].transform('mean') Output: St_id St_name sem_id sgpa cgpa 0 1 abc 1 2.0 2.5 1 2 pqr 1 2.5 3.0 2 1 abc 2 3.0 2.5 3 2 pqr 2 3.5 3.0 4 3 xzy 1 4.0 4.0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51169415

http://stackoverflow.com/comment/134691578
has text: This worked for me. Added __init__.py and tests were discovered.
score: 0
comment on: http://stackoverflow.com/a/65402475
type: AnswerComment
type: Comment

http://stackoverflow.com/q/51188027
downvote count: 0
has answer: http://stackoverflow.com/a/69917046
favorite count: 0
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51189649
upvote count: 3
has answer: http://stackoverflow.com/a/65457941
has body: I'm using a Mac , the python version is 2.7.10. and I installed flask ➜ Flask_blog python Python 2.7.10 (default, Oct 6 2017, 22:29:07) [GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.31)] on darwin Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import flask &gt;&gt;&gt; I try to follow the tutorial of flash on http://flask.pocoo.org/docs/1.0/ the commands: ➜ Flask_blog export FLASK_APP=flaskblog.py ➜ Flask_blog flask run zsh: command not found: flask ➜ Flask_blog code in flaskblog.py: from flask import Flask app = Flask(__name__) @app.route("/") def hello(): return "Hello World!" The error is command not found: flask I also tried an other tutorial. commands: ➜ Flask_blog cd /Users/jzd/Movies/flask/Second_video ➜ Second_video python one.py Sorry code in one.py from flask import Flask app = Flask(__name__) @app.route('/') def index(): return 'Hello World' if __name__ == '__name__': app.run('0.0.0.0') else: print("Sorry") the condition __name__ == '__name__': did not pass. I guess the python venv matters. Really want to know how to fix it.
type: Question
possible better answer: http://stackoverflow.com/a/74085690
has title: terminal error: flask run zsh: command not found: flask
has answer: http://stackoverflow.com/a/74085690
answer count: 6
tagged with: flask
has answer: http://stackoverflow.com/a/77028704
has comment: http://stackoverflow.com/comment/89357879
accepted answer: http://stackoverflow.com/a/51189649
has comment: http://stackoverflow.com/comment/89358503
score: 3
has answer: http://stackoverflow.com/a/52653822

http://stackoverflow.com/q/51252470
answer count: 0
tagged with: mysql
has body: atm I'm working with the python paho mqtt client and mysql to store weather data (temperature/humidity) collected via an microcontroller. The Setup: Raspi with raspian &amp; MariaDB &amp; Mosquitto Broker ESP8266 which publishes the data to the broker I wrote the following code to fetch the data from the broker and to write it to the database: main.py import paho.mqtt.client as mqtt #import client1 from time import sleep import json from Datenbank import * from datetime import * i=0 def on_log(client,userdata,level,buf): print("log: "+buf) def on_connect(client,userdata,flags,rc): if rc==0: print("connected OK") else: print("Bad connection Returned code=",rc) def on_disconnect(client,userdata,flags,rc=0): print("Disconnected result code "+str(rc)) def on_message(client,userdata,msg): #callback function topic=msg.topic m_decode=str(msg.payload.decode("utf-8","ignore")) print("message received",m_decode) m_in=json.loads(m_decode) dbG.writeData(m_in["Temperature"],m_in["Humidity"]) print("Data Written") print(datetime.now()) db=db() db.connectToDb("WeatherStation") broker="192.168.0.10" client=mqtt.Client("Sensor1_Client") client.connect(broker) print("Connecting to broker",broker) client.on_connect=on_connect client object #client.on_disconnect=on_disconnect client.on_log=on_log client.on_message=on_message client.subscribe("home/Sensor1") client.loop_forever() Datenbank.py import MySQLdb as db from datetime import * class db: def __init__(self): self.HOST = "192.168.0.10" self.PORT = 3306 self.USER = "xxx" self.PASSWORD = "xxx" def connectToDb(self,DB): try: self.connection = db.Connection(host=self.HOST, port=self.PORT, user=self.USER, passwd=self.PASSWORD, db=DB) self.connection.autocommit(True) print("Connection established") except Exception as e: print(e) def writeData(self,temp,hum): now=datetime.now() Full_Date=now.strftime("%y.%m.%d") current_year=now.strftime("%Y") current_month=now.strftime("%m") current_day=now.strftime("%d") current_time=now.strftime("%H:…
type: Question
tagged with: raspberry-pi
has comment: http://stackoverflow.com/comment/89486650
score: 0
has comment: http://stackoverflow.com/comment/89493917
type: UnansweredQuestion
tagged with: mqtt
has title: Python Mqtt/Mysql insertion ensemble breaks up after a short time
tagged with: python

http://stackoverflow.com/comment/89366494
comment on: http://stackoverflow.com/q/51192417
score: 2
has text: _"This operation takes some additional time and memory space."_ Yes, but the time and space are both O(N) with respect to the size of the data, so is it really worth worrying about? Have you performed benchmarking to empirically determine that this is a performance bottleneck?
type: Comment
type: QuestionComment

http://stackoverflow.com/tag/csv
type: Tag
tags question: http://stackoverflow.com/q/51321021
tags question: http://stackoverflow.com/q/51290182
tags question: http://stackoverflow.com/q/51207367
tags question: http://stackoverflow.com/q/51251588
tags question: http://stackoverflow.com/q/51189741
tags question: http://stackoverflow.com/q/51317007
tags question: http://stackoverflow.com/q/51195413
tags question: http://stackoverflow.com/q/51172784
tag name: csv
tags question: http://stackoverflow.com/q/51308362
tags question: http://stackoverflow.com/q/51195501
tags question: http://stackoverflow.com/q/51169415
tags question: http://stackoverflow.com/q/51291873
tags question: http://stackoverflow.com/q/51198871
tags question: http://stackoverflow.com/q/51231692
tags question: http://stackoverflow.com/q/51267230
tags question: http://stackoverflow.com/q/51200743
tags question: http://stackoverflow.com/q/51242638
tags question: http://stackoverflow.com/q/51268282
tags question: http://stackoverflow.com/q/51208672
tags question: http://stackoverflow.com/q/51192905
tags question: http://stackoverflow.com/q/51215295
tags question: http://stackoverflow.com/q/51202880
tags question: http://stackoverflow.com/q/51288530
tags question: http://stackoverflow.com/q/51245686
tags question: http://stackoverflow.com/q/51185638
tags question: http://stackoverflow.com/q/51295444
tags question: http://stackoverflow.com/q/51302907
tags question: http://stackoverflow.com/q/51208208
tags question: http://stackoverflow.com/q/51213451
tags question: http://stackoverflow.com/q/51276232
tags question: http://stackoverflow.com/q/51178613
tags question: http://stackoverflow.com/q/51263691
tags question: http://stackoverflow.com/q/51320142
tags question: http://stackoverflow.com/q/51215166
tags question: http://stackoverflow.com/q/51219892
tags question: http://stackoverflow.com/q/51201733
tags question: http://stackoverflow.com/q/51244536
tags question: http://stackoverflow.com/q/51264355
tags question: http://stackoverflow.com/q/51198175
tags question: http://stackoverflow.com/q/51280540
tags question: http://stackoverflow.com/q/51181171
tags question: http://stackoverflow.com/q/51293239
tags question: http://stackoverflow.com/q/51209153
tags question: http://stackoverflow.com/q/51245163
tags question: http://stackoverflow.com/q/51192552
tags question: http://stackoverflow.com/q/51219664
tags question: http://stackoverflow.com/q/51302633
tags question: http://stackoverflow.com/q/51304581
tags question: http://stackoverflow.com/q/51321783
tags question: http://stackoverflow.com/q/51230326
tags question: http://stackoverflow.com/q/51228118
tags question: http://stackoverflow.com/q/51174506
tags question: http://stackoverflow.com/q/51306959
tags question: http://stackoverflow.com/q/51274048
tags question: http://stackoverflow.com/q/51289689
tags question: http://stackoverflow.com/q/51284141
tags question: http://stackoverflow.com/q/51197760
tags question: http://stackoverflow.com/q/51314701
tags question: http://stackoverflow.com/q/51249813
tags question: http://stackoverflow.com/q/51262969
tags question: http://stackoverflow.com/q/51209836
tags question: http://stackoverflow.com/q/51214273
tags question: http://stackoverflow.com/q/51215163
tags question: http://stackoverflow.com/q/51278619
tags question: http://stackoverflow.com/q/51231442
tags question: http://stackoverflow.com/q/51270537
tags question: http://stackoverflow.com/q/51169624
tags question: http://stackoverflow.com/q/51317050
tags question: http://stackoverflow.com/q/51302227
tags question: http://stackoverflow.com/q/51247139
tags question: http://stackoverflow.com/q/51268856
tags question: http://stackoverflow.com/q/51203643
tags question: http://stackoverflow.com/q/51260935
tags question: http://stackoverflow.com/q/51272730
tags question: http://stackoverflow.com/q/51176851
tags question: http://stackoverflow.com/q/51296315
tags question: http://stackoverflow.com/q/51216549
tags question: http://stackoverflow.com/q/51320119

http://stackoverflow.com/a/51229117
has body: I would use prepared statement in your case and DATETIME for storing times: import sqlite3 from datetime import datetime db = sqlite3.connect(":memory:") now = datetime.now() with db: cur = db.cursor() cur.execute("""CREATE TABLE Login(StartTime1 DATETIME NOT NULL, BreakBegin1 DATETIME NOT NULL, BreakEnd1 DATETIME NOT NULL, EndTime1 DATETIME NOT NULL, comments TEXT)""") cur.execute("""INSERT INTO Login values(?, ?, ?, ?,"No Comments")""", (now, now, now, now)) for row in cur.execute("""select * from Login"""): print(row) Output: ('2018-07-08 08:25:57.718175', '2018-07-08 08:25:57.718175', '2018-07-08 08:25:57.718175', '2018-07-08 08:25:57.718175', 'No Comments')
type: Answer
upvote count: 2
score: 2
answers question: http://stackoverflow.com/q/51228853
accepted answer of: http://stackoverflow.com/q/51228853
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/51168071
answers question: http://stackoverflow.com/q/51168035
type: Answer
score: 2
downvote count: 0
has body: You have to escape the \ in code code = "print('hello\\n')" ast.parse(code) # &lt;_ast.Module object at 0x7fd68cb48cc0&gt; Or you can add r prefix to indicate everything in the string needs to be escaped code = r"print('hello\n')" ast.parse(code) # &lt;_ast.Module object at 0x7fd68cb48ef0&gt;
upvote count: 2

http://stackoverflow.com/comment/89402614
score: 0
type: QuestionComment
has text: Yup my file had four rows in it
type: Comment
comment on: http://stackoverflow.com/q/51199599

linux
tags question: http://stackoverflow.com/q/51275316
tags question: http://stackoverflow.com/q/51276461
tags question: http://stackoverflow.com/q/51168569
tags question: http://stackoverflow.com/q/51314045
tags question: http://stackoverflow.com/q/51218613
tags question: http://stackoverflow.com/q/51168730
tags question: http://stackoverflow.com/q/51299998
tags question: http://stackoverflow.com/q/51264043
tags question: http://stackoverflow.com/q/51214638
tags question: http://stackoverflow.com/q/51219201
tags question: http://stackoverflow.com/q/51195584
tags question: http://stackoverflow.com/q/51322951
tags question: http://stackoverflow.com/q/51209153
tags question: http://stackoverflow.com/q/51246962
tags question: http://stackoverflow.com/q/51248572
type: Tag
tags question: http://stackoverflow.com/q/51247772
tags question: http://stackoverflow.com/q/51250443
tags question: http://stackoverflow.com/q/51173298
tags question: http://stackoverflow.com/q/51270690
tags question: http://stackoverflow.com/q/51301448
tags question: http://stackoverflow.com/q/51167584
tags question: http://stackoverflow.com/q/51196028
tags question: http://stackoverflow.com/q/51280326
tags question: http://stackoverflow.com/q/51218108
tags question: http://stackoverflow.com/q/51242603
tags question: http://stackoverflow.com/q/51273579
tag name: linux
tags question: http://stackoverflow.com/q/51312017
tags question: http://stackoverflow.com/q/51168920
tags question: http://stackoverflow.com/q/51270537
tags question: http://stackoverflow.com/q/51254304
tags question: http://stackoverflow.com/q/51323776
tags question: http://stackoverflow.com/q/51184001
tags question: http://stackoverflow.com/q/51229274
tags question: http://stackoverflow.com/q/51279791
tags question: http://stackoverflow.com/q/51249525
tags question: http://stackoverflow.com/q/51280737
tags question: http://stackoverflow.com/q/51305831
tags question: http://stackoverflow.com/q/51246764
tags question: http://stackoverflow.com/q/51221163
tags question: http://stackoverflow.com/q/51256738
tags question: http://stackoverflow.com/q/51307026

http://stackoverflow.com/comment/89367409
has text: @tobias_k I hope it is clearer with the edit
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51191735

http://stackoverflow.com/comment/89605839
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51314091
has text: It's a question of personal taste, I'll go for first option with code shared between pages separated. Also remember that if your API should do same as regular site, you can write only the API and let the site call the API (you'll only need templates). Also sharing code gives the plus that in case of changes you'll have to put hands only in one place,
score: 0

http://stackoverflow.com/a/51272604
has body: Another way is to flatten the list using itertools.chain and then use np.unique(). This can be faster than np.concatenate() if you have a very large list. For example, consider the following: First generate random data: from itertools import chain import numpy as np import pandas as pd N = 100000 a = np.array( [[np.random.randint(0,1000) for _ in range(np.random.randint(0,10))] for _ in range(N)] ) Timing results: %%timeit np.unique(list(chain.from_iterable(a))) #10 loops, best of 3: 66.7 ms per loop %%timeit np.unique(np.concatenate(a)) #10 loops, best of 3: 123 ms per loop You could also use pandas.unique, which according to the docs: Significantly faster than numpy.unique. Includes NA values. %%timeit pd.unique(np.concatenate(a)) #10 loops, best of 3: 107 ms per loop %%timeit pd.unique(list(chain.from_iterable(a))) #10 loops, best of 3: 57.2 ms per loop
type: Answer
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/51272270

http://stackoverflow.com/a/51292632
answers question: http://stackoverflow.com/q/51292465
type: Answer
score: 1
upvote count: 1
has body: Usually the trick is to test what external function does by itself and not other functions that are called and are already tested. This is not a problem if internal functions are actually called, just avoid testing them again. If you want to avoid calling internal functions though, you may try dependecy injection or mocking. If your external function is simple enough, you may forgo testing it, 100% coverage is not a rule.
downvote count: 0

http://stackoverflow.com/a/51317454
has comment: http://stackoverflow.com/comment/89610861
accepted answer of: http://stackoverflow.com/q/51317438
score: 9
answers question: http://stackoverflow.com/q/51317438
type: AcceptedAnswer
type: Answer
upvote count: 9
has body: Simply using apply with sorted df['values'].apply(sorted) 0 [abc, cdf, efg] 1 [abc, rsy, xyz] Name: values, dtype: object For comma separated values, thanks @AChampion: df = pd.DataFrame({'id': [1,2], 'values': ['cdf, abc, efg', 'xyz, rsy, abc']}) df['values'].apply(lambda x: ','.join(sorted(x.split(',')))) 0 abc, efg,cdf 1 abc, rsy,xyz Name: values, dtype: object You can also use a list comprehension to increase performance: df['values'] = [','.join(sorted(i.split(','))) for i in df['values']]
downvote count: 0

http://stackoverflow.com/comment/89412310
type: AnswerComment
score: 0
type: Comment
has text: @CHaworth good catch, thank you
comment on: http://stackoverflow.com/a/51215579

celery
tags question: http://stackoverflow.com/q/51243515
tags question: http://stackoverflow.com/q/51202926
tags question: http://stackoverflow.com/q/51311195
tag name: celery
tags question: http://stackoverflow.com/q/51310414
tags question: http://stackoverflow.com/q/51304378
tags question: http://stackoverflow.com/q/51254226
tags question: http://stackoverflow.com/q/51275653
tags question: http://stackoverflow.com/q/51257153
tags question: http://stackoverflow.com/q/51280179
type: Tag
tags question: http://stackoverflow.com/q/51234071
tags question: http://stackoverflow.com/q/51210714
tags question: http://stackoverflow.com/q/51322207
tags question: http://stackoverflow.com/q/51273659
tags question: http://stackoverflow.com/q/51263040
tags question: http://stackoverflow.com/q/51294661
tags question: http://stackoverflow.com/q/51265595

http://stackoverflow.com/q/51191154
has comment: http://stackoverflow.com/comment/89367819
tagged with: python
answer count: 1
has comment: http://stackoverflow.com/comment/89364397
has title: Re-index with Python
upvote count: 0
downvote count: 5
tagged with: sorting
type: UnansweredQuestion
favorite count: 0
has body: Hi I have a student dataset consisting of their Names, Subjects and Scores. Each student has 5 subjects to write. However the below table has data missing for some students in terms of their subjects and marks. Please find the table below: Name Subject Score Harry Math 4 Harry Science 5 Harry Social 3 Harry French 5 Harry Spanish 4 Steve Math 5 Steve Science 3 Steve Social 5 Steve French 4 Tom Math 5 Tom Science 4 Tom Social 5 I would like to find Names which have scores for less than 5 subjects and append additional rows, so that all students have their individual scores for all 5 subjects. Expected output is below: Name Subject Score Harry Math 4 Harry Science 5 Harry Social 3 Harry French 5 Harry Spanish 4 Steve Math 5 Steve Science 3 Steve Social 5 Steve French 4 Steve Spanish 4 You can see here that Steve, Harry and Tom have scores for all 5 subjects.
tagged with: pandas-groupby
type: Question
tagged with: pandas
has answer: http://stackoverflow.com/a/51191663
score: -5

http://stackoverflow.com/q/51307561
has comment: http://stackoverflow.com/comment/89637351
has body: I am trying to detect blobs using opencv, however my accuracy haven't been any more that 80%. Here are images of detected blobs: Found blobs n = 350 Found blobs n = 550 import cv2 import numpy as np import matplotlib.pyplot as plt from sklearn.datasets import make_classification plt.figure(figsize=(10,5)) n_samples = 250 x, _ = make_classification(n_samples = n_samples) plt.scatter(x[:, 0], x[:, 1], marker='o', s=14 ) plt.axis('off') plt.savefig('sampleblobs.jpg') plt.show() img = cv2.imread('sampleblobs.jpg',0) params = cv2.SimpleBlobDetector_Params() params.filterByArea = False params.minDistBetweenBlobs = 1 params.thresholdStep = 10; params.minRepeatability = 2; params.minDistBetweenBlobs = 0; detector = cv2.SimpleBlobDetector_create(params) keypoints = detector.detect(img) print('Found: {}, Original: {}'.format(len(keypoints), n_samples)) # Draw detected blobs as red circles. # cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS ensures the size of the circle corresponds to the size of blob im_with_keypoints = cv2.drawKeypoints(img, keypoints, np.array([]), (0,0,100), cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS) # Show keypoints cv2.imshow("Found blobs", im_with_keypoints) cv2.imwrite("Found_blobs.jpg", im_with_keypoints) cv2.waitKey() cv2.destroyAllWindows() Is there any way to improve an accuracy in this case? Thank you in advance!
score: 0
has comment: http://stackoverflow.com/comment/89643054
tagged with: python
answer count: 0
type: UnansweredQuestion
has title: Improve accuracy of counting blobs using opencv
tagged with: opencv
type: Question

http://stackoverflow.com/q/51204963
answer count: 2
downvote count: 0
tagged with: sorting
has comment: http://stackoverflow.com/comment/89390941
has body: I have a dictionary that includes lists students = { 1:["name1", 20, 100], 2:["name2", 20, 100], 3:["name3", 20, 95], 4:["name4", 21, 65], 5:["name5", 22, 85] } I want to create table and sort the data by names. like this Name Age Score name1 20 100 name2 20 100 name3 20 95 name4 21 65 name5 22 85 How can I do this? I wrote like this: students = { 1:["Rauf", 20, 100], 2:["Shafag", 20, 100], 3:["Ali", 20, 95], 4:["Camal", 21, 65], 5:["Arzu", 22, 85] } print(" ") print("{:&gt;12} {:&gt;12} {:&gt;12}".format('Name','Age','Score')) print(" ") for v in students.values(): name, age, score = v print(sorted(("{:&gt;12} {:&gt;12} {:&gt;12}".format(name, age, score)), key= lambda v: v[2]))
score: 2
possible better answer: http://stackoverflow.com/a/51205171
has answer: http://stackoverflow.com/a/51205171
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89391192
upvote count: 2
has answer: http://stackoverflow.com/a/51208626
has comment: http://stackoverflow.com/comment/89390959
tagged with: python
tagged with: dictionary
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51208626
tagged with: list
has title: Create table and sort data from lists in dictionary
type: Question

http://stackoverflow.com/q/51275210
accepted answer: http://stackoverflow.com/a/51275324
favorite count: 0
upvote count: 2
has body: I have a kivy screen that I need to create elements in via a loop. I can do it as so: class HomeScreen(Screen): def show_tasks(self): global user tasks = DB.get_tasks(user) # Returns an array of tuples for task in tasks: self.add_widget(Label(text=task[1])) However, when I do it this way, the labels overlap on top of each other - literally on the z axis, making them all unreadable. Instead I want them to populate one above the other (on the y axis). Not only that, but eventually I'm going to want to create a table-like structure out of the data. Here's my kv: &lt;HomeScreen&gt;: name: 'home' FloatLayout: BoxLayout: orientation: "horizontal" pos_hint: {"x": 0, "y": 0} GridLayout: id: grid rows: 4 cols: 1 padding: 10 spacing: 10 row_force_default: True row_default_height: 40 Label: text: 'Your Tasks:' size_hint_x: None width: 200 font_size: 24 Any help or insight into how I can solve this problem would be greatly appreciated!
tagged with: python
answer count: 1
downvote count: 0
has title: Creating Kivy widgets in a loop
has answer: http://stackoverflow.com/a/51275324
type: Question
score: 2
type: AnsweredQuestion
tagged with: kivy

http://stackoverflow.com/comment/89578432
type: QuestionComment
comment on: http://stackoverflow.com/q/51300476
score: 0
has text: Why don't you do simple `y=np.log(x, where=x_1)` and then add 2 to y wherever `x_1==True`?
type: Comment

http://stackoverflow.com/comment/133310086
has text: thanks .. was out of action for few months hence was not able to respond earlier.
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/74796560
score: 0

http://stackoverflow.com/a/51194939
has comment: http://stackoverflow.com/comment/89371575
upvote count: 1
answers question: http://stackoverflow.com/q/51193743
type: AcceptedAnswer
type: Answer
has body: @Aavik, you can try the below code. I've used filter() function to filter the dictionaries with specific keys. Try the code online at http://rextester.com/URYZW46252 (less efficient way using filter() function). Also try http://rextester.com/HLVQL50077 (using list comprehension which is efficient way). def get_last_dict_with_specific_id(test_dict, id): # Create tasks list from test_dict tasks = test_dict["tasks"] # filter tasks list based on dictionaries id i.e get a list of dictionaries with only specific id # Update the same list tasks with different content (save space) tasks = [d for d in tasks if d["id"] == id] # tasks = filter(lambda d: d["id"] == id, tasks) # This is efficient like above one # Pick the last dictionary and return it if tasks: return tasks[len(tasks) - 1] else: return {} # TEST test_dict = {'user': 'xxx','tasks': [{'id':'01','age':'60'},{'id':'02','age':'50'},{'id':'01','age':'65'},{'id':'02','age':'65'}]}; last_dict_01 = get_last_dict_with_specific_id(test_dict, '01'); print last_dict_01; # {'age': '65', 'id': '01'} last_dict_02 = get_last_dict_with_specific_id(test_dict, '02'); print last_dict_02; # {'age': '65', 'id': '02'} last_dict_03 = get_last_dict_with_specific_id(test_dict, '03'); print last_dict_03; # {}
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/51193743

http://stackoverflow.com/q/51303537
tagged with: django-rest-framework
tagged with: ajax
type: AnsweredQuestion
tagged with: datatables
has answer: http://stackoverflow.com/a/54023280
type: Question
tagged with: django
tagged with: python
has body: I'm working on database program using Django. The program appends the database from user's forms/imported files, allows listing of data per category, and inline editing per category. I did a lot of research (since i'm new in django), and so far I've been successful in generating forms, and and customized tables by combining rest framework and datatables. The problem occurs when I tried to implement inline editing to my tables. I using the plugin datatables editor. My views and serializer seem to work since i can POST, PUT and DELETE in the Api Root. But then I can't make the ajax url point to the methods api detail views, I need the pkin the url to be variable to match the selection: my serializer.py class TankSerializer(serializers.ModelSerializer): modified_date = serializers.DateTimeField(format='%d/%m/%Y %H:%M', input_formats=None) updated_by = serializers.SlugRelatedField(slug_field='last_name', queryset=User.objects.all()) pid = serializers.SlugRelatedField(slug_field='number', queryset=PID.objects.all()) zone = serializers.SlugRelatedField(slug_field='number', queryset=ProcessZone.objects.all()) medium = serializers.SlugRelatedField(slug_field='code', queryset=Medium.objects.all()) revision = serializers.SlugRelatedField(slug_field='code', queryset=Revision.objects.all()) supplier = serializers.SlugRelatedField(slug_field='name', queryset=Supplier.objects.all()) po = serializers.SlugRelatedField(slug_field='number', queryset=PO.objects.all()) material = serializers.SlugRelatedField(slug_field='name', queryset=Material.objects.all()) DT_RowId = serializers.SerializerMethodField() def get_DT_RowId(self, tank): return 'row_%d' % tank.pk class Meta: model = Tank fields = ( 'DT_RowId', 'tag', 'description', 'pid', 'zone', 'medium', 'revision', 'supplier', 'po', 'material', 'volume', 'hight','modified_date','updated_by', 'created_by' ) my views.py @login_required @ensure_csrf_cookie def edit_tanks(request, project_code): project = get_object_or_404(Project, code=pr…
score: 0
accepted answer: http://stackoverflow.com/a/54023280
has title: Django REST framework use AJAX url to point api detail url
answer count: 1

http://stackoverflow.com/q/51248179
accepted answer: http://stackoverflow.com/a/51248433
has comment: http://stackoverflow.com/comment/89475474
tagged with: python
tagged with: dictionary
type: AnsweredQuestion
score: 3
linked to: http://stackoverflow.com/q/20250771
upvote count: 3
has title: Python / Pandas Dict to find closest match then end loop
has body: trying to apply this logic to the following DF I have a df as follows import pandas as pd import numpy as pd df = pd.read_csv('subjects.csv') Subjects Media information Media Digital Media I then try to map my subjects to a dict to output a validated corrected_subject d = {'Media' : 'Film &amp; Media', 'Information' : 'ICT', 'Digital' : 'ICT'} df['subject_corrected'] = df['subjects'](lambda x: ', '.join([d[i] for i in d if i in x])) Subjects subject_corrected Media Film &amp; Media information Media Film &amp; Media, ICT Digital Media Film &amp; Media, ICT now using this loops through my DF giving me all matches where I want it to find the closest match and exit the loop. so Digital Media would be ICT and not Media I have tried the following but it hasn't really boded well for me! for for k,v in d.items(): if k in df['subjects']: df['subject_corrected'] = d.values(): Subjects subject_corrected Media Film &amp; Media information Media ICT Digital Media ICT I've had a look at quite a few similar posts but couldn't work this one out. am I going around this the wrong way, shall I pass this into two lists/arrays and use an if statement to loop through any matches? also how is a dict different from a 2D Array. Any help is appreciated.
type: Question
has answer: http://stackoverflow.com/a/51248433
has comment: http://stackoverflow.com/comment/89475327
tagged with: pandas
answer count: 1
downvote count: 0
favorite count: 0

http://stackoverflow.com/q/51265302
type: Question
tagged with: modelica
has comment: http://stackoverflow.com/comment/89513932
has comment: http://stackoverflow.com/comment/89535612
has comment: http://stackoverflow.com/comment/89523644
has comment: http://stackoverflow.com/comment/89538580
has comment: http://stackoverflow.com/comment/89512946
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/51374827
favorite count: 0
tagged with: dymola
has comment: http://stackoverflow.com/comment/89523716
tagged with: python
tagged with: jmodelica
score: 2
type: AnsweredQuestion
has title: pyFMI Modelica: The FMU contains no binary for this platform
upvote count: 2
accepted answer: http://stackoverflow.com/a/51374827
has comment: http://stackoverflow.com/comment/89515343
has body: I'm trying to run the simple tutorial examples with pyFMI package in Python but I get an error The FMU contains no binary for this platform. Tried to set the enviromental variables for the FMULibrary but the error is still here. I would appreciate any hints. runfile('C:/Users/NiPap/.spyder-py3/temp.py', wdir='C:/Users/d60378/.spyder-py3') Could not find RADAR5 Could not find GLIMDA Traceback (most recent call last): File "&lt;ipython-input-1-b6c744d814b8&gt;", line 1, in &lt;module&gt; runfile('C:/Users/NiPap/.spyder-py3/temp.py', wdir='C:/Users/d60378/.spyder-py3') File "C:\Users\NiPap\AppData\Local\Continuum\anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 705, in runfile execfile(filename, namespace) File "C:\Users\NiPap\AppData\Local\Continuum\anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 102, in execfile exec(compile(f.read(), filename, 'exec'), namespace) File "C:/Users/NiPap/.spyder-py3/temp.py", line 9, in &lt;module&gt; fmi_bouncing_ball.run_demo() File "C:\Users\NiPap\AppData\Local\Continuum\anaconda3\lib\site-packages\pyfmi\examples\fmi_bouncing_ball.py", line 32, in run_demo model = load_fmu(fmu_name) File "src\pyfmi\fmi.pyx", line 7157, in pyfmi.fmi.load_fmu (src\pyfmi\fmi.c:82903) File "src\pyfmi\fmi.pyx", line 2666, in pyfmi.fmi.FMUModelME1.__init__ (src\pyfmi\fmi.c:33458) File "src\pyfmi\fmi.pyx", line 943, in pyfmi.fmi.FMUModelBase.__init__ (src\pyfmi\fmi.c:14153) FMUException: The FMU contains no binary for this platform.
has comment: http://stackoverflow.com/comment/89622382

http://stackoverflow.com/comment/89533697
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51243413
has text: python3 returns iterator object. so use list(filter(lambda x: "value4" in dic[x], dic))
type: AnswerComment

http://stackoverflow.com/q/51287333
tagged with: bokeh
has comment: http://stackoverflow.com/comment/89552708
has title: print value_counts for columns in a loop
type: Question
has comment: http://stackoverflow.com/comment/89552633
has comment: http://stackoverflow.com/comment/89552886
score: 0
tagged with: pandas
has answer: http://stackoverflow.com/a/51287540
answer count: 1
has body: I am using bokeh to print horizontal bar charts for a number of columns. I used for loop for the same. This is the code, but when I run this. I get this error. I am a beginner in bokeh. Please help. chart_cols = ['respondent_age respondent_gender respondent_edu respondent_occupation Religion Caste_cat CM_choice Likely_winner'.split()] chart_cols for f in chart_cols: count = df[f].value_counts() p = figure(plot_height=400, plot_width=400, title='Chart',toolbar_location=None) p.title.align = "right" p.xaxis.axis_label = 'Number of respondents' p.yaxis.axis_label = 'Something' p.hbar(y=sorted(df[f].unique()), height=0.7, left=0, right=count, color=Category20, alpha=0.7) show(p) print('Done') AttributeError: 'DataFrame' object has no attribute 'value_counts' To write the above code, I used bokeh documentation and data available with me. I tried using . operator but error is same. In that case it says that no . attribute For example df.f.value_counts() What mistake am I doing? Please help.
has comment: http://stackoverflow.com/comment/89552572
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51287540

http://stackoverflow.com/q/51183238
has answer: http://stackoverflow.com/a/51183374
has comment: http://stackoverflow.com/comment/89348653
accepted answer: http://stackoverflow.com/a/51185070
type: AnsweredQuestion
score: 2
downvote count: 0
favorite count: 0
tagged with: python-3.x
type: Question
has body: In the text below I only want to get "4th of July" Hello, happy [4th of July]. I love the firework I have these text: text = {{Hey, how are you.}} I've watched John Mulaney all night. I'm trying to remove {{Hey, how are you.}},, and. This is what I have tried so far, but it doesn't seem to work: hey_how_are_you = re.compile('\{\{.*\}\}') category = re.compile('\[\[Category:.*?\]\]') image = re.compile('\[\[Image:.*?\]\]') text = hey_how_are_you.sub('', text) text = category.sub('', text) text = image.sub('', text)
possible better answer: http://stackoverflow.com/a/51183316
tagged with: python
tagged with: regex
has title: Get text inside one-pair-brackets but not double square brackets
has answer: http://stackoverflow.com/a/51183316
has answer: http://stackoverflow.com/a/51185070
upvote count: 2
answer count: 3

http://stackoverflow.com/q/51177119
has comment: http://stackoverflow.com/comment/89336986
has title: What exactly is id() displaying?
has answer: http://stackoverflow.com/a/51177386
type: Question
answer count: 2
has body: The id() function appears to identify the value, not the object. Which of the entities below is actually an object: x ? 11 ? 12 ? id(object) Return the “identity” of an object. This is an integer (or long integer) which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes may have the same id() value. $ python Python 2.7.5 (default, May 3 2017, 07:55:04) [GCC 4.8.5 20150623 (Red Hat 4.8.5-14)] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; id(11) 11311992 &gt;&gt;&gt; x=11 &gt;&gt;&gt; id(x) 11311992 &gt;&gt;&gt; id(12) 11311968 &gt;&gt;&gt; x=12 &gt;&gt;&gt; id(x) 11311968
has answer: http://stackoverflow.com/a/51177354
score: 0
tagged with: python
linked to: http://stackoverflow.com/q/15171695
has comment: http://stackoverflow.com/comment/89337134
linked to: http://stackoverflow.com/q/49142505
type: UnansweredQuestion

http://stackoverflow.com/a/51273943
has comment: http://stackoverflow.com/comment/89530923
score: 2
upvote count: 2
has body: There seems to be an issue when the renderers share a data source. However, this works (with Bokeh >= 0.13.0) if you let Bokeh create a new separate source for each glyph: from bokeh.models import ColumnDataSource from bokeh.plotting import figure, show p = figure(tools="hover", tooltips="$name: @$name") data=dict(x=[1,2,3], y1=[2,6,5], y2=[6,2,3]) p.line('x', 'y1', color="navy", line_width=3, source=data, alpha=0.1, hover_color="navy", hover_alpha=0.6, name="y1") p.line('x', 'y2',color="firebrick", line_width=3, source=data, alpha=0.1, hover_color="firebrick", hover_alpha=0.6, name="y2") show(p)
answers question: http://stackoverflow.com/q/51255630
accepted answer of: http://stackoverflow.com/q/51255630
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/89529819
type: Answer

http://stackoverflow.com/a/61490823
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/51252221
upvote count: 1
type: Answer
has body: Though @paul41's approach works, it's somewhat a misuse. A proper way of doing this is using preprocessing or postprocessing (before or after numericalization correspondingly). Here is an example of postprocessing: def get_pad_to_min_len_fn(min_length): def pad_to_min_len(batch, vocab, min_length=min_length): pad_idx = vocab.stoi['&lt;pad&gt;'] for idx, ex in enumerate(batch): if len(ex) &lt; min_length: batch[idx] = ex + [pad_idx] * (min_length - len(ex)) return batch return pad_to_min_len FILTER_SIZES = [3,4,5] min_len_padding = get_pad_to_min_len_fn(min_length=max(FILTER_SIZES)) TEXT = Field(sequential=True, use_vocab=True, lower=True, batch_first=True, postprocessing=min_len_padding) Nested functions required to pass parameters to inner function if those defined in the main loop (e.g. min_length = max(FILTER_SIZES)), but parameters can be hardcoded inside the function if this works.

http://stackoverflow.com/comment/89536331
comment on: http://stackoverflow.com/q/51279294
score: 0
has text: OK, what about cmd.exe? Its just that you need to tie it down to a particular program or package. You probably won't be able to fix it yourself, but at least you would know who to complain to.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51173920
score: 4
upvote count: 4
tagged with: sympy
answer count: 1
downvote count: 0
favorite count: 0
tagged with: latex
has body: SymPy will pretty print expressions within a dict like this: &gt;&gt;&gt; latex(dict(a=1, b=2)) '\\left \\{ a : 1, \\quad b : 2\\right \\}' Instead I'd like to use the align environment to split my expressions across lines, with an output like this: \begin{align} a &amp; = 1 \\ b &amp; = 2 \\ \end{align} Can SymPy do this for me?
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51178366
type: Question
has title: Aligned LaTeX equations SymPy
accepted answer: http://stackoverflow.com/a/51178366

http://stackoverflow.com/a/51265784
type: Answer
accepted answer of: http://stackoverflow.com/q/51265145
upvote count: 2
score: 2
has body: Recursive approach: sort the list by the first criteria. Then group by that criteria, and recursively sort each sub-group using the remaining criteria. from operator import itemgetter import itertools def multisorted(seq, indices, reversed_states): if len(indices) == 0: return seq index = indices[0] reversed = reversed_states[0] partially_sorted_seq = sorted(seq, key = itemgetter(indices[0]), reverse=reversed_states[0]) result = [] for key, group in itertools.groupby(partially_sorted_seq, key=itemgetter(indices[0])): result.extend(multisorted(group, indices[1:], reversed_states[1:])) return result d = ((1, 'c', 'aa'), (2, 'b', 'bb'), (1, 'c', 'cc'), (1, 'd', 'dd')) print(multisorted(d, (0,1,2), (False, True, True))) Result: [(1, 'd', 'dd'), (1, 'c', 'cc'), (1, 'c', 'aa'), (2, 'b', 'bb')] Approach #2. sort and sorted can already sort by multiple criteria out-of-the-box. We only need to change the key so that some of the elements of each tuple have reversed logic in regards to inequality comparison. from functools import total_ordering @total_ordering class Negated: def __init__(self, value): self.value = value def __eq__(self, other): return self.value == other.value def __lt__(self, other): return self.value &gt; other.value def multisorted(seq, ordering): return sorted(seq, key = lambda t: [Negated(x) if reversed else x for x, reversed in zip(t, ordering)]) d = ((1, 'c', 'aa'), (2, 'b', 'bb'), (1, 'c', 'cc'), (1, 'd', 'dd')) print(multisorted(d, (False, True, True)))
has comment: http://stackoverflow.com/comment/89513179
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51265145

http://stackoverflow.com/comment/89541998
has text: I solved the error of the app, I go back to the previous website.urls, the error persists >.< You can access the webpage here: [link](http://206.189.31.17/)
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51280064

http://stackoverflow.com/q/51194153
score: 0
tagged with: api
answer count: 1
has title: How to send a large JSON file via python http request
has answer: http://stackoverflow.com/a/51194279
type: UnansweredQuestion
tagged with: python
tagged with: http://stackoverflow.com/tag/json
has body: I am running two services on my local machine. I want to send data from service 1 to service 2 which is on port 8004. I am doing the following: r = requests.get('http://127.0.0.1:8004/json_data='+json.dumps(json_data)) I get these 2 errors: ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host ConnectionError: ('Connection aborted.', ConnectionResetError(10054, 'An existing connection was forcibly closed by the remote host', None, 10054, None)) I assume that I am sending a large file which is causing the problem. My file is 15mb in size, its a python dictionary which I am sending via a json.dumps() Any recommendation for overcoming this error ?
tagged with: python-requests
tagged with: httprequest
type: Question

http://stackoverflow.com/comment/89580525
type: Comment
comment on: http://stackoverflow.com/a/51295555
score: 1
type: AnswerComment
has text: Thank you so much! If its not obvious I'm new to programming, so this really helped!

http://stackoverflow.com/comment/89464743
has text: I used data['lon'][1:] because the 1st value was nan maybe due to header. And I think I can remove header using skip_header = 1 Actually the problem is when I do a pcolormesh() plot then the z value should not be a nx1 matrix which I am getting here.That i couldnt able to make it and hence the error @ThomasKühn
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51237022

http://stackoverflow.com/comment/89342913
has text: what other information should i put down? i can try to add more
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/51178866

http://stackoverflow.com/comment/89373212
score: 1
comment on: http://stackoverflow.com/q/51195799
has text: Why do you say you *need* to take arguments in this highly unusual format?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89569751
has text: You are using a Python2 kernel named "Python 3".
comment on: http://stackoverflow.com/q/51295377
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/a/74034064
score: 0
answers question: http://stackoverflow.com/q/51300674
has body: with open('out.json', 'w') as f: for obj in objs: json.dump(obj, f) f.write('\n')
type: Answer

http://stackoverflow.com/comment/89523541
comment on: http://stackoverflow.com/q/51272645
score: 0
type: Comment
type: QuestionComment
has text: Ah, true, I missed that. Regardless they still need to convert to an int if they want to do integer comparison. I think using `argparse` is simpler.

http://stackoverflow.com/q/51268702
tagged with: django-templates
has comment: http://stackoverflow.com/comment/89516000
answer count: 0
type: Question
has title: Not a registered tag library - Django custom filter error
has comment: http://stackoverflow.com/comment/89537814
has comment: http://stackoverflow.com/comment/89516750
has comment: http://stackoverflow.com/comment/89539741
has comment: http://stackoverflow.com/comment/89541892
has comment: http://stackoverflow.com/comment/89516364
has comment: http://stackoverflow.com/comment/89543427
downvote count: 0
has body: I added a new custom template filter for my django app but I get the error 'my_filters' is not a registered tag library. Must be one of: admin_list admin_modify admin_static admin_urls cache compress i18n js keyvalue l10n log mul rest_framework static staticfiles tz I added my_filters.py in templatetags directory in the app directory. It also contains the '__ init __.py'file this is my_filters from django.template import Library register = Library() @register.filter(is_safe=True, name='lookup') def lookup(dict, index): if index in dict: return dict[index] return '' my template file looks like {% block content %} {% load my_filters %} {% load mul %} {% if not all_facilities %} &lt;div class="panel-warning pane This loads fine and works properly in my local machine when i run form pycharm. But the error is when i pushed it to production. I even restarted the server on production but i still get the error
has comment: http://stackoverflow.com/comment/89541834
has comment: http://stackoverflow.com/comment/89521073
has comment: http://stackoverflow.com/comment/89524629
favorite count: 0
tagged with: django-settings
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/105986196
tagged with: django
tagged with: python
score: 2

http://stackoverflow.com/comment/89567989
type: AnswerComment
has text: If that worked, you're on Python 2. You should really get Python 3. Also, your code will report that 5 percent of 10 is 0, due to Python 2-specific division behavior.
comment on: http://stackoverflow.com/a/51295223
type: Comment
score: 0

http://stackoverflow.com/a/51254931
score: 2
has comment: http://stackoverflow.com/comment/89496571
upvote count: 3
has comment: http://stackoverflow.com/comment/89489280
downvote count: 1
answers question: http://stackoverflow.com/q/51254859
has comment: http://stackoverflow.com/comment/89490454
has comment: http://stackoverflow.com/comment/89488920
type: Answer
has body: You can't have both an exception raised and a value returned (without getting hacky). If this is all code you control, then may I suggest this pattern: class something(object): Exception = None def __init__(self): ... if BadStuff: self.Exception = IrrelevantException() ... that_thing = something() if that_thing.Exception: print(that_thing.Exception) # carry on Note, if you are just looking for a message, then don't bother creating an Exception object, but rather just set an error code/message on self, and check for it later.

http://stackoverflow.com/a/51300028
answers question: http://stackoverflow.com/q/51299618
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89609336
type: Answer
has body: I think need first resample by minutes with forward filling NaNs, convert to inetgers and for Series add DataFrame.squeeze. Then aggregate by dates and hours with sum and last reshape by unstack: s = df'is_stockout'.resample('T').ffill().astype(int).squeeze() df1 = s.groupby([s.index.date, s.index.hour]).sum().unstack(fill_value=0) print (df1) datetime_create 0 1 2 3 4 5 6 7 8 9 ... 14 15 16 17 \ 2018-02-14 0 0 0 0 0 0 0 0 0 0 ... 0 0 0 0 2018-02-15 0 0 0 0 0 0 0 0 0 0 ... 0 0 15 60 2018-02-16 60 60 60 60 60 60 60 60 60 60 ... 0 0 0 0 2018-02-17 0 0 0 0 0 0 0 0 0 0 ... 0 0 0 0 2018-02-18 0 0 0 0 0 0 0 0 0 0 ... 0 0 0 0 2018-02-19 0 0 0 0 0 0 0 0 0 0 ... 0 0 15 60 2018-02-20 60 60 60 60 60 60 60 60 60 60 ... 0 0 0 0 2018-02-21 0 0 0 0 0 0 0 0 0 0 ... 0 0 0 0 datetime_create 18 19 20 21 22 23 2018-02-14 0 0 0 0 0 0 2018-02-15 60 60 60 60 60 60 2018-02-16 0 0 0 0 0 0 2018-02-17 0 0 0 0 0 0 2018-02-18 0 0 0 0 0 0 2018-02-19 60 60 60 60 60 60 2018-02-20 0 0 0 0 0 0 2018-02-21 0 0 0 0 0 0
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/51299618
downvote count: 0

http://stackoverflow.com/q/51215981
answer count: 2
has answer: http://stackoverflow.com/a/51216277
has body: I'm trying to download a few images using Scrapy. I've followed official documentation, copy&amp;paste some examples and read many similar questions but it's still now working at all. What am I missing? I noticed that items pipeline looks empty, but I couldn't figure it out. 2018-07-06 20:10:18 [scrapy.middleware] INFO: Enabled item pipelines: [] Also, I've tried different sites, played around with the headers,... but nothing. It looks as if it was working, but then no file has been saved. Here I post the code I'm using to test this functionality. myspider.py: class ImageSpider(scrapy.Spider): name = "imagespider" start_urls = [ "http://www.upv.es/", ] def parse(self, response): for elem in response.xpath("//img"): img_url = elem.xpath("@src").extract_first() yield ImageItem(image_urls=[img_url]) # Not working #yield {'image_urls': [img_url]} # Not working items.py: class ImageItem(scrapy.Item): image_urls = scrapy.Field() images = scrapy.Field() settings.py: ITEM_PIPELINES = { 'scrapy.pipelines.images.ImagesPipeline': 1, } IMAGES_STORE = '/Users/salva/Desktop/demo/demo/temp' Console: 2018-07-06 20:10:18 [scrapy.utils.log] INFO: Scrapy 1.5.0 started (bot: scrapybot) 2018-07-06 20:10:18 [scrapy.utils.log] INFO: Versions: lxml 4.2.3.0, libxml2 2.9.8, cssselect 1.0.3, parsel 1.5.0, w3lib 1.19.0, Twisted 18.4.0, Python 3.6.5 (v3.6.5:f59c0932b4, Mar 28 2018, 03:03:55) - [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)], pyOpenSSL 18.0.0 (OpenSSL 1.1.0h 27 Mar 2018), cryptography 2.2.2, Platform Darwin-17.6.0-x86_64-i386-64bit 2018-07-06 20:10:18 [scrapy.crawler] INFO: Overridden settings: {'USER_AGENT': 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)'} 2018-07-06 20:10:18 [scrapy.middleware] INFO: Enabled extensions: ['scrapy.extensions.corestats.CoreStats', 'scrapy.extensions.telnet.TelnetConsole', 'scrapy.extensions.memusage.MemoryUsage', 'scrapy.extensions.logstats.LogStats'] 2018-07-06 20:10:18 [scrapy.middleware] INFO: Enabled downloader middlewares: ['scrapy.download…
downvote count: 0
tagged with: python
favorite count: 0
tagged with: download
type: UnansweredQuestion
tagged with: file
upvote count: 1
has answer: http://stackoverflow.com/a/51218783
tagged with: scrapy
type: Question
has title: Scrapy is not downloading images
score: 1
tagged with: image

http://stackoverflow.com/comment/89424409
has text: @jpp, of course, when combining those 2 in one common block, `s = pd.Series(x)` and `dups = s.duplicated(keep=False)` should be calculated beforehand. I separated them for demonstration `pandas` one-liners
comment on: http://stackoverflow.com/a/51221785
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/51170530
linked to: http://stackoverflow.com/q/51153569
type: AnsweredQuestion
downvote count: 0
score: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/51170839
type: Question
possible better answer: http://stackoverflow.com/a/51170677
has answer: http://stackoverflow.com/a/51170877
has answer: http://stackoverflow.com/a/51170677
has answer: http://stackoverflow.com/a/51172392
answer count: 6
has answer: http://stackoverflow.com/a/51170839
has body: Similar to this question I have a string of names and numbers separated by a colon: s = 'Waz D: 5 l gu l: 5 GrinVe: 3 P LUK: 2 Cubbi: 1 2 nd dok: 1 maf 74: 1 abr12: 1 Waza D 5' I'm trying to split this to get: ('Waz D', '5'), ('l gu l', '5'), ('GrinVe', '3'), ('P LUK', '2'), ('Cubbi', '1'), ('2 nd dok', '1') ('maf 74', '1') ('abr12', '1') I have tried two regular expressions so far with mixed success: re.findall(r"(.*?)[a-zA-Z0-9]+: (\d+)*", s) [('Waz ', '5'), (' l gu ', '5'), (' ', '3'), (' P ', '2'), (' ', '1'), (' 2 nd ', '1'), (' maf ', '1'), (' ', '1')] And: re.findall(r"(.*?)([a-zA-Z0-9]+): (\d+)*", s) [('Waz ', 'D', '5'), (' l gu ', 'l', '5'), (' ', 'GrinVe', '3'), (' P ', 'LUK', '2'), (' ', 'Cubbi', '1'), (' 2 nd ', 'dok', '1'), (' maf ', '74', '1'), (' ', 'abr12', '1')] How can I adjust this to get the output I'm after?
has comment: http://stackoverflow.com/comment/89323761
has answer: http://stackoverflow.com/a/51196738
upvote count: 1
has answer: http://stackoverflow.com/a/51170806
has title: Extracting name and number from string
tagged with: python
tagged with: regex

http://stackoverflow.com/comment/89347524
type: Comment
comment on: http://stackoverflow.com/q/51182689
has text: Do you want to scan through the list, find the first `qty`, the first `pass` and the first `fail` and group them all together into one element (and so on)?
score: 0
type: QuestionComment

http://stackoverflow.com/q/51312412
has answer: http://stackoverflow.com/a/51853943
type: UnansweredQuestion
tagged with: python
tagged with: tkinter
linked to: http://stackoverflow.com/q/51314105
type: Question
linked to: http://stackoverflow.com/q/12791666
has title: cx_Freeze generated Executable won't open
score: 0
has body: I've read many other cx_Freeze related issues on Stack Overflow and so far they've been beneficial, but I'm still not getting the executable to work. When you click on the .exe file nothing happens. I also made a square root calculator to try to figure out why it wouldn't work without any of the tkinter GUI that this one uses, but it doesn't work either. They both work great in Python, but the .exe doesn't do anyting at all. I'm using Python 3.7 (32bit), cx_Freeze 5.1.1 (32bit), Windows 10 pro (64bit), setup.py import cx_Freeze from cx_Freeze import setup, Executable import tkinter import ThreadCalc import sys import os ba = None if sys.platform == 'win32': ba = "Win32GUI" if sys.platform == 'win64': ba = "Win64GUI" os.environ['TCL_LIBRARY'] = r'C:\Python37-32\tcl\tcl8.6' os.environ['TK_LIBRARY'] = r'C:\Python37-32\tcl\tk8.6' build_exe_options = {"include_msvcr": True} ex = Executable(script="ThreadCalc.py", base = ba, targetName='CreoThreadNoteGenerator.exe') cx_Freeze.setup(name = "CreoThreadNoteGenerator", options = {"build_exe":{"include_files": ['small_logo.gif'],"includes":["tkinter","os","math","sys"]}}, version = '0.1', description = 'Generates A Thread Quality Control Note for Creo', executables = [ex] ) SQUARE ROOT CALCULATOR sqrt.py import math a = input('Enter a number to Evaluate') x = math.sqrt(a) print("The square root of {} is {}").format(a,x) setup.py import cx_Freeze import os import sys import math from cx_Freeze import setup, Executable ba = None if sys.platform == 'win32': ba = "Win32GUI" ex = Executable(script="sqrt.py", base = ba, targetName='SquareRootCalc.exe') cx_Freeze.setup(name = "SquareRootCalc", options = {"build_exe":{"packages":["os", "math", "sys"]}}, version = '0.1', description = 'Square Root Calculator', executables = [ex] )
answer count: 1
tagged with: cx-freeze

http://stackoverflow.com/comment/89373052
type: Comment
type: QuestionComment
has text: @Jcho can check this photo is this do you need https://imageresize.org/view/9295bcd3-9903-4886-b7ed-ee9435dc8729
comment on: http://stackoverflow.com/q/51194341
score: 0

http://stackoverflow.com/comment/89562371
score: 0
comment on: http://stackoverflow.com/a/51292014
type: Comment
has text: Add `from xlrd import XLRDError` to your code. That solved it for me.
type: AnswerComment

http://stackoverflow.com/comment/89512953
type: QuestionComment
has text: 1. try `{{ file_name.id }}` 2. try `name = request.POST["FileName"]` what kind of error do you get?
comment on: http://stackoverflow.com/q/51265991
score: 0
type: Comment

http://stackoverflow.com/q/51218314
tagged with: python
tagged with: airflow-scheduler
has comment: http://stackoverflow.com/comment/89427508
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51386238
has comment: http://stackoverflow.com/comment/89428864
upvote count: 10
has title: DAGs not clickable on Google Cloud Composer webserver, but working fine on a local Airflow
has body: I'm using Google Cloud Composer (managed Airflow on Google Cloud Platform) with image version composer-0.5.3-airflow-1.9.0 and Python 2.7, and I'm facing a weird issue : after importing my DAGs, they are not clickable from the Web UI (and there are no buttons "Trigger DAG", "Graph view", ...), while all works perfectly when running a local Airflow. Even if non usable from the webserver on Composer, my DAGs still exist. I can list them using CLI (list_dags), describe them (list_tasks) and even trigger them (trigger_dag). Minimal example reproducing the issue A minimal example I used to reproduce the issue is shown below. Using a hook (here, GoogleCloudStorageHook) is very important, since the bug on Composer happens when a hook is used. Initially, I was using a custom hook (in a custom plugin), and was facing the same issue. Basically here, the example lists all entries in a GCS bucket (my-bucket) and generate a DAG for each entry beginning with my_dag. import datetime from airflow import DAG from airflow.contrib.hooks.gcs_hook import GoogleCloudStorageHook from airflow.operators.bash_operator import BashOperator google_conn_id = 'google_cloud_default' gcs_conn = GoogleCloudStorageHook(google_conn_id) bucket = 'my-bucket' prefix = 'my_dag' entries = gcs_conn.list(bucket, prefix=prefix) for entry in entries: dag_id = str(entry) dag = DAG( dag_id=dag_id, start_date=datetime.datetime.today(), schedule_interval='0 0 1 * *' ) op = BashOperator( task_id='test', bash_command='exit 0', dag=dag ) globals()[dag_id] = dag Results on Cloud Composer After importing this file to Composer, here's the result (I have 4 files beginning with my_dag in my-bucket) : As I explained, DAGs are not clickable and the columns "Recent Tasks" and "DAG Runs" are loading forever. The "info" mark next to each DAG name says : This DAG isn't available in the webserver DagBag object. It shows up in this list because the scheduler marked it as active in the metadata database. Of course, refreshing is n…
type: Question
tagged with: airflow
score: 10
has comment: http://stackoverflow.com/comment/89447309
has comment: http://stackoverflow.com/comment/89461264
tagged with: google-cloud-composer
accepted answer: http://stackoverflow.com/a/51386238
tagged with: python-2.7
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/89462900
favorite count: 0
has comment: http://stackoverflow.com/comment/89450730
has comment: http://stackoverflow.com/comment/89460229

http://stackoverflow.com/q/51202484
has answer: http://stackoverflow.com/a/51202786
favorite count: 0
upvote count: 1
tagged with: python
type: AnsweredQuestion
score: 1
accepted answer: http://stackoverflow.com/a/51202786
type: Question
has title: How to understand the `org = super(Singleton, cls)` and `org.__new__(cls, *args, **kw)`?
has comment: http://stackoverflow.com/comment/89386384
has body: How to understand this code: I am researching the Singleton of Python implementation: class Singleton(object): ''''' A python style singleton ''' def __new__(cls, *args, **kw): if not hasattr(cls, '_instance'): org = super(Singleton, cls) # what does this line mean, what's the funciton of it? cls._instance = org.__new__(cls, *args, **kw) # and this line return cls._instance if __name__ == '__main__': class SingleSpam(Singleton): def __init__(self, s): self.s = s def __str__(self): return self.s s1 = SingleSpam('spam') print id(s1), s1 s2 = SingleSpam('spa') print id(s2), s2 print id(s1), s1 I do not understand the two lines code: org = super(Singleton, cls) cls._instance = org.__new__(cls, *args, **kw) whether the cls equals self? what's the meaning of org = super(Singleton, cls)? why use org.__new__(cls, *args, **kw) for creating the Singleton instance's property _instance?
has comment: http://stackoverflow.com/comment/89386957
answer count: 1
downvote count: 0

http://stackoverflow.com/comment/89616777
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51320142
has text: hmmm, but if need column to 3rd position, solution should be a bit different, it is necessary?

http://stackoverflow.com/comment/89846368
type: Comment
score: 0
comment on: http://stackoverflow.com/q/51274541
has text: Or you could even pass the queue reference to file handler and do the queue check in `emit`. This way, you use the standard `QueueListener` and need to write only the file handler. Whatever fits your current architecture best.
type: QuestionComment

http://stackoverflow.com/comment/89475882
has text: Note how your values inside of `attributes` are additionally wrapped in a list; simply accessing it with an additional `[0]` should do the trick, i.e. `resp['attributes'][0]['value']`
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51248455
score: 1

http://stackoverflow.com/a/51258632
has body: This is one of the rare cases where recursion in Python seems to be appropriate and helpful. The following function adds a value to the hierarchical dictionary d specified by the list of keys: def add_to_dict(d, keys, value): if len(keys) == 1: # The last key d[keys[0]] = value return if keys[0] not in d: d[keys[0]] = {} # Create a new subdict add_to_dict(d[keys[0]], keys[1:], value) The function works with the dictionaries of arbitrary depth. The rest is just the matter of calling the function: d = {} for line in file: keys, value = line.split("=") keys = keys.split(":") add_to_dict(d, keys, value.strip()) Result: {'INFO': {'20180606_141527': { 'submit': {'is_test': 'False', 'username': 'Mary'}, 'env': {'sys.platform': 'linux2', 'os.name': 'ubuntu'}}}} You can modify the code to exclude certain levels (like the timestamp).
type: Answer
answers question: http://stackoverflow.com/q/51258434
upvote count: 7
score: 7
downvote count: 0

http://stackoverflow.com/q/51303638
tagged with: python
tagged with: pca
has comment: http://stackoverflow.com/comment/89587189
has comment: http://stackoverflow.com/comment/89584619
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/89584568
has body: I have a data which has 1700 rows, each with 9 features of houses and an array holding the prices corresponding to those features. I have built a linear regression model on this data, but I would like to visualize it. Can I somehow convert these 9 features into single feature using PCA? I have tried this but I still get error saying that x, y need to be of same size. from sklearn.model_selection import train_test_split from sklearn import linear_model from sklearn.decomposition import PCA clf = linear_model.LinearRegression() pca = PCA(n_components = 9) # features contains 1700 rows of 9 feature data, y contains 1700 price values x_train, x_test, y_train, y_test = train_test_split(features, y) pca.fit(x_train) x_train = pca.transform(x_train) x_test = pca.transform(x_test) clf.fit(x_train, y_train) pred = clf.predict(x_test) plt.scatter(x_train, y_train) plt.show() Error occurs at plt.scatter() function, feature.shape = (17000, 9), y.shape = (17000, 1)
has answer: http://stackoverflow.com/a/51310824
has comment: http://stackoverflow.com/comment/89584693
has title: Plotting multidimensional data on a graph
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89584416
tagged with: scikit-learn
accepted answer: http://stackoverflow.com/a/51310824
type: Question

http://stackoverflow.com/comment/89581303
has text: The issue is that all of Python's string interpolation methods collide with parts of your HTML string that are supposed to be static. You might want to look a template engines. There are many different options just for HTML templating that take care of the potential collisions for you. [Jinja 2](http://jinja.pocoo.org/) for example. But maybe you prefer something even more lightweight. [Here's](https://wiki.python.org/moin/Templating) what I expect to be a pretty exhaustive list of engines available in Python
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51300363

http://stackoverflow.com/a/51309969
answers question: http://stackoverflow.com/q/51309117
score: 0
has body: this should work in this scenario: while count&lt;10: message, address = s.recvfrom(5555) messageString = message.decode("utf-8") print(messageString) count=count+1 filename = yourfile.xlsx workbook = Workbook(filename + '.xlsx') worksheet = workbook.add_worksheet() with open(filename , 'rt', encoding='utf8') as f: for r, row in enumerate(reader): print(r) for c, col in enumerate(messageString): worksheet.write(r, c, col) workbook.close()
type: Answer
has comment: http://stackoverflow.com/comment/89665613

http://stackoverflow.com/q/51253262
type: AnsweredQuestion
has title: Difference between `block_size` and `digest_size` in hashlib?
accepted answer: http://stackoverflow.com/a/51335622
type: Question
has comment: http://stackoverflow.com/comment/89485507
tagged with: hashlib
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/51335622
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89646332
has comment: http://stackoverflow.com/comment/89512069
score: 6
tagged with: python
upvote count: 6
has body: I was going through the Python hashlib package documentation and wanted some clarification on two hash object attributes (namely hash.block_size and hash.digest_size). Here is the definition of each attribute: hash.digest_size= "The size of the resulting hash in bytes." hash.block_size = "The internal block size of the hash algorithm in bytes." source: https://docs.python.org/2/library/hashlib.html So I understand that hash.digest_size is simply the length or size (in bytes) of the data once it is hashed or "digested" by the hash_object. For for example from the code below getting the digest of the string 'Hello World' via a SHA256 hash object returns a digest_size of 32 bytes (or 256 bits). import hashlib hash_object = hashlib.sha256() hash_object.update(b'Hello World') hex_dig = hash_object.hexdigest() print(hex_dig) &gt;&gt;&gt;a591a6d40bf420404a011733cfb7b190d62c65bf0bcda32b57b277d9ad9f146e print(hash_object.digest_size) &gt;&gt;&gt;32 print(hash_object.block_size) &gt;&gt;&gt;64 print(len(hex_dig)) &gt;&gt;&gt;64 What I don't understand is this hash.block_size attribute. Is it simply the length of characters required to represent the hexadecimal representation of the hashed data? Is it something else entirely? I don't quite understand the definition of this attribute so any clarification on this would be very helpful &amp; insightful!

http://stackoverflow.com/comment/89518522
comment on: http://stackoverflow.com/a/51270174
score: 0
type: AnswerComment
has text: just what I was looking for. Two questions, 1) can I get the rank to be an `int` instead of `float`? 2) `df.Quality` refers to the column name right? Can I do a df['Quality'] as well?
type: Comment

http://stackoverflow.com/a/51235748
downvote count: 0
type: Answer
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/51195525
has body: for line in inp: will store the next line of inp in line including the terminating new line character '\n'. When you pass this unmodified to ssh_client.connect(), then the host name will include '\n'. The reason that you get a successful connection with the last line of your input file is very likely that the last line is not terminated by '\n'. One way to remove the '\n' is: line = line.strip() To put it all together, including my comments to your question regarding the recommended use of with: import socket import paramiko # get user/password as in the question code (not repeated here) # .... status = 'OK' with open(r'ipaddressrouter.txt', 'r') as inp: for line in inp: line = line.strip() with paramiko.SSHClient() as ssh_client: ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) try: ssh_client.connect(hostname=line, username=user, password=password) print("Successful Connection to " + line) stdin, stdout, stderr = ssh_client.exec_command('target command here') output = stdout.read() with open('out.txt', 'a') as out: out.write(line + '\n') out.write(str(output, encoding='utf-8') + '\n') out.write('\n') except (socket.error, paramiko.AuthenticationException) as e: print("Failed connection to " + line) status = 'fail' Note: I modified your example to work with Python3. Some of my changes are probably not necessary for Python2. If you are not forced to use Python2, I would always recommend to use Python3 for new projects. See End of support for python 2.7?
answers question: http://stackoverflow.com/q/51195525
type: AcceptedAnswer

http://stackoverflow.com/a/51280408
answers question: http://stackoverflow.com/q/51279535
type: Answer
upvote count: 3
score: 3
has body: &lt; /Hey > As designed by the Raspberry Pi's circuit layout, in short: The 3.5mm Audio Jack on the Raspberry Pi models cannot be used as an audio input. I'm not sure if you would want to anyways. This means you have a couple of options on how you want to set up your microphone setup. 1. Using a small mic array (Like Alexa Echo or Google Home) A lot of the time these kind of systems are prototyped on Raspberry Pi's or similar (see the official Alexa development kit). You can find similar replicas to the microphone arrays found on google home etc. , specifically fitted for the Raspberry Pi. These include some added advanced features such as Noise Suppression, Direction of Sound Source and other neat features I'll leave for you to explore yourself. Here's 3 I found after googling (I'm sure if you look you can find more): ReSpeaker 4-mic array ReSpeaker 7-mic array Matrix Creator If you wanted high quality results for speech recognition I'd probably begin to look more down this route. 2. Using a normal USB microphone Probably the most common approach is to get a standard USB microphone that has Raspberry Pi drivers and use this. I found one from Adafruit which I'm sure is just plug and play which could be nice and easy to get going with. Again I'm sure you'll find plenty of other options online, these were just suggestions to get you started. Hopefully this helps! :-)
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51279535
downvote count: 0

http://stackoverflow.com/q/51267467
favorite count: 0
has comment: http://stackoverflow.com/comment/89514646
upvote count: 1
has comment: http://stackoverflow.com/comment/89517508
has comment: http://stackoverflow.com/comment/89625364
tagged with: python-behave
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89517126
tagged with: bdd
answer count: 0
downvote count: 0
has body: What i am trying I am trying to run behave from a Window machine which don't have behave or any other depended libraries pip installed. 1. Including all modules path to sys.path. 2. Running behave using behave_main method. Code sample: import sys sys.path.append('C:\\MyWorkspace\\synthetics\\features\\modules\\behave-1.2.6') sys.path.append('C:\\MyWorkspace\\synthetics\\features\\modules\\parse-1.8.4') sys.path.append('C:\\MyWorkspace\\synthetics\\features\\modules\\selenium-3.13.0') sys.path.append('C:\\MyWorkspace\\synthetics\\features\\modules\\parse_type-0.4.2') sys.path.append('C:\\MyWorkspace\\synthetics\\features\\modules\\traceback2-1.4.0') sys.path.append('C:\\MyWorkspace\\synthetics\\features\\modules\\linecache2-1.0.0') sys.path.append('C:\\MyWorkspace\\synthetics\\features\\modules\\nose-1.3.7') sys.path.append('C:\\MyWorkspace\\synthetics\\features\\modules\\six-1.11.0') sys.path.append('C:\\MyWorkspace\\synthetics\\features\\modules\\enum-0.4.6') from behave.__main__ import main as behave_main behave_main(["C:\\MyWorkspace\\synthetics\\features\\", "-n Login"]) I am able to run behave script this way from my Mac OS, having issue doing the same from Windows machine. Error: C:\MyWorkspace\synthetics\features&gt;python run_behave.py Traceback (most recent call last): File "run_behave.py", line 16, in &lt;module&gt; behave_main(["C:\\MyWorkspace\\synthetics\\features\\", "-n NEAT"]) File "C:\MyWorkspace\synthetics\features\modules\behave-1.2.6\behave\__main__.py", line 182, in main config = Configuration(args) File "C:\MyWorkspace\synthetics\features\modules\behave-1.2.6\behave\configuration.py", line 647, in __init__ self.reporters.append(SummaryReporter(self)) File "C:\MyWorkspace\synthetics\features\modules\behave-1.2.6\behave\reporter\summary.py", line 49, in __init__ self.feature_summary = {Status.passed.name: 0, Status.failed.name: 0, AttributeError: 'int' object has no attribute 'name' Update I was able to eliminate this issue by running the code wi…
has title: Error while running behave_main from windows
type: Question
tagged with: python
score: 1

http://stackoverflow.com/a/51179299
has body: I found multiple problems with your code. Here are some solutions: The first problem is that you are using event.type where you need to be using event.key. for event in pygame.event.get(): if event.type == pygame.KEYDOWN: if event.type == pygame.K_a: isRunning = False The second event.type needs to be changed to an event.key. The second problem is that K_a needs to be prefixed with pygame., like this: if event.key == pygame.K_a: Your desktop looked all fuzzy because the PyGame application ran in 800x600 resolution, which is less than most monitors. The PyGame window was still open until you closed it. As long as the window is open, the custom resolution remains. I hope I've helped you out!
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/89341048
downvote count: 0
answers question: http://stackoverflow.com/q/51179065
upvote count: 2
has comment: http://stackoverflow.com/comment/89435879

http://stackoverflow.com/comment/89348616
comment on: http://stackoverflow.com/q/51183014
has text: @JeremyKahan This made it loop completely! I'm not sure why though. But that made it work! Why exactly is that the case?
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/89566245
score: 0
type: Comment
has text: Hello, Thank you for your reply. Unfortunately, I can't make your code work for me. I tried to adjust the code, but I keep getting errors. The first error I get was 'local variable 'row' referenced before assignment'. Next error that occurs is for row in csv_in[1:]: TypeError: '_csv.reader' object is not subscriptable I have changed the code a bit and currently, it saves the headers but no other values are saved into the new file. Could you please guide me how to fix it? Thanks
comment on: http://stackoverflow.com/a/51291459
type: AnswerComment

http://stackoverflow.com/q/51320027
upvote count: 5
has title: Keras with tensorflow-gpu totally freezes PC
tagged with: python
has answer: http://stackoverflow.com/a/67655757
type: AnsweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/51342090
tagged with: tensorflow
type: Question
tagged with: crash
score: 5
has answer: http://stackoverflow.com/a/51356697
accepted answer: http://stackoverflow.com/a/51356697
possible better answer: http://stackoverflow.com/a/67655757
tagged with: deep-learning
answer count: 3
has body: I have pretty simple architecture lstm NN. After few epoch 1-2 my PC totally freezes I can't even move my mouse : Layer (type) Output Shape Param # ================================================================= lstm_4 (LSTM) (None, 128) 116224 _________________________________________________________________ dropout_3 (Dropout) (None, 128) 0 _________________________________________________________________ dense_5 (Dense) (None, 98) 12642 ================================================================= Total params: 128,866 Trainable params: 128,866 Non-trainable params: 0 # Same problem with 2 layers LSTM with dropout and Adam optimizer SEQUENCE_LENGTH =3, len(chars) = 98 model = Sequential() model.add(LSTM(128, input_shape = (SEQUENCE_LENGTH, len(chars)))) #model.add(Dropout(0.15)) #model.add(LSTM(128)) model.add(Dropout(0.10)) model.add(Dense(len(chars), activation = 'softmax')) model.compile(loss = 'categorical_crossentropy', optimizer = RMSprop(lr=0.01), metrics=['accuracy']) This is how I train: history = model.fit(X, y, validation_split=0.20, batch_size=128, epochs=10, shuffle=True,verbose=2).history NN needs 5 minutes to finish 1 epoch. Higher size of batch doesn't mean that problem will occur faster. But more complex model can train more time achieving almost same accuracy - about 0.46 (full code here ) I have last up to date Linux Mint, 1070ti with 8GB, 32Gb ram +-----------------------------------------------------------------------------+ | NVIDIA-SMI 396.26 Driver Version: 396.26 | |-------------------------------+----------------------+----------------------+ | GPU Name Persistence-M| Bus-Id Disp.A | Volatile Uncorr. ECC | | Fan Temp Perf Pwr:Usage/Cap| Memory-Usage | GPU-Util Compute M. | |===============================+======================+======================| | 0 GeForce GTX 107... Off | 00000000:08:00.0 On | N/A | | 0% 35C P8 10W / 180W | 303MiB / 8116MiB | 0% Default | +-------------------------------+----------------------+-------------…
tagged with: keras
favorite count: 0

http://stackoverflow.com/comment/135347181
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/69803152
type: Comment
has text: For seekers, the issue and resolution is here: https://github.com/microsoft/vscode-python/issues/18199

http://stackoverflow.com/comment/116146466
type: AnswerComment
comment on: http://stackoverflow.com/a/59608886
score: 0
type: Comment
has text: Most packages were listed this way, except `WARNING: Could not generate requirement for distribution -lxc 0.1 (/usr/lib64/python3.7/site-packages): Parse error at "'-lxc==0.'": Expected W:(abcd...)`

http://stackoverflow.com/q/51215339
tagged with: python-3.x
type: Question
has comment: http://stackoverflow.com/comment/89411769
has comment: http://stackoverflow.com/comment/89411812
tagged with: python
has comment: http://stackoverflow.com/comment/89411811
has body: I'm trying to make an availability comparison program, similar to https://doodle.com/ where it: 1) shows the dates most similar (which I've figured out with the code below) dateSet1 = {'31/12/2015', '01/01/2016', '02/01/2016'} dateSet2 = {'31/12/2015', '01/01/2016', '03/01/2016'} dateSet3 = {'31/12/2015', '02/01/2016', '04/01/2016'} dateSet1 &amp; dateSet2 &amp; dateSet3 2) if no common date among the lists then show second most common, then third, etc. (This is where I'm not sure what to do) How would I go about finding that out? Are there any functions or libraries that already do this?
has title: Python: How to find similarities between lists then finding second most similar, then third, etc
score: 0
tagged with: set
has comment: http://stackoverflow.com/comment/89412216
has comment: http://stackoverflow.com/comment/89411730
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/89378723
comment on: http://stackoverflow.com/q/51198333
has text: A print-debugging suggestion: add the line `print(n.shape, j, J)` right before `b = numpy.max( n[j:J] )`.
type: Comment
type: QuestionComment
score: 2

http://stackoverflow.com/comment/89367129
has text: @billjamesdev - See my answer below. Now the buffer memory is allocated in the Python program and the pointer-to-pointer is passed to the C function. Hope this looks better?
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51178284
type: Comment

http://stackoverflow.com/comment/89513770
type: AnswerComment
comment on: http://stackoverflow.com/a/51250399
has text: I guess you mean `numpy.linalg.norm`? It is indeed a good way to do the calculations. I'm using this as well when my code is not performance critical (well, in Python it generally never should be, but saving some time is always nice :) ). Don't know why I forgot to mention it in my answer. `np.linalg.norm` should be, depending on the array size, about 5%-30% slower than `((b - a)**2).sum(axis=1)**0.5`. And thanks alot for marking my answer, I'm glad I was able to help.
type: Comment
score: 1

http://stackoverflow.com/a/51192719
has comment: http://stackoverflow.com/comment/89368983
has comment: http://stackoverflow.com/comment/89371840
upvote count: 1
has comment: http://stackoverflow.com/comment/111960577
type: AcceptedAnswer
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/89370730
has comment: http://stackoverflow.com/comment/89370445
has body: There are some misconceptions in your example: The moving average is defined based on a variable or tensor. You effectively created moving averages for each of your constants (explaining the results you are getting). You have to call ema_op every time you want to update your moving average. The moving average is initialised with the initial value of your variable (not zero as you are expecting). The following example behaves as you are expecting: import tensorflow as tf w = tf.Variable(0.0, dtype=tf.float32) ema = tf.train.ExponentialMovingAverage(decay=0.9) ema_op = ema.apply([w]) assigns = [] with tf.control_dependencies([ema_op]): for val in [10., 20., 40.]: assigns.append(tf.assign(w, tf.constant(val))) with tf.Session() as sess: sess.run(tf.global_variables_initializer()) for assign in assigns: _, _, w_ = sess.run([ema_op, assign, ema.average(w)]) print w_ _, w_ = sess.run([ema_op, ema.average(w)]) print w_ The resulting output is: 0.0 1.0000002 2.9000006 6.6100016
type: Answer
accepted answer of: http://stackoverflow.com/q/51191470
answers question: http://stackoverflow.com/q/51191470

http://stackoverflow.com/comment/99845176
has text: The docs were changed when the error was pointed out [here](https://github.com/sentinelsat/sentinelsat/issues/216#issuecomment-404136389)
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51280857

http://stackoverflow.com/a/60215205
has body: Looks like pycrypto has not been under active development since 2014 and support ended at python 3.3. cryptography seems like the standard now. Using cryptography: from cryptography.hazmat.primitives import serialization from cryptography.hazmat.primitives.asymmetric import rsa from cryptography.hazmat.backends import default_backend password = b'thepassword' key = rsa.generate_private_key( backend=default_backend(), public_exponent=65537, key_size=2048 ) private_key = key.private_bytes( serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8, serialization.BestAvailableEncryption(password) ) public_key = key.public_key().public_bytes( serialization.Encoding.OpenSSH, serialization.PublicFormat.OpenSSH )
type: Answer
answers question: http://stackoverflow.com/q/51228645
downvote count: 1
upvote count: 5
has comment: http://stackoverflow.com/comment/116056670
score: 4

http://stackoverflow.com/q/51284908
favorite count: 0
linked to: http://stackoverflow.com/q/48709009
tagged with: python
has answer: http://stackoverflow.com/a/51315941
type: AnsweredQuestion
score: 2
upvote count: 2
accepted answer: http://stackoverflow.com/a/51315941
type: Question
has title: Python 2.7 Pyautogui.locateOnScreen not working
tagged with: python-imaging-library
tagged with: pyautogui
has body: For some unknown reason the Pyautogui's locateOnScreen() function (and all other Pyautogui's locate functions) is not working properly and returns None. My Code: &gt;&gt;&gt; pyautogui.screenshot('test.png',region=(100,20, 30, 20)) &lt;PIL.Image.Image image mode=RGB size=30x20 at 0x39E35C0&gt; &gt;&gt;&gt; print pyautogui.locateOnScreen('test.png') None My research I know that when it returns None, it means that pyautogui was not able to locate the image on the screen. I also know that it has to be visible on the screen. The code above was executed while not moving a single window. I also know that there are very similar/identical questions at stackoverflow like this one. But the solution from that question is not applicable to my situation since I am actually using the pyautogui's screenshot and cropping features straightaway and not even cropping with 3rd party software, yet pyautogui is not able to locate it. Additional info Python: 2.7.15 (64-bit) OS: Windows 10 Home 64-bit
tagged with: python-2.7
answer count: 1
downvote count: 0

http://stackoverflow.com/a/51290924
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51290827
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/51290827
type: Answer
has body: In your __init__ function myList is just local variable. Use self.myList in order to make it as a class member. Of course access it in function addSomething() by using self as well: self.myList.append(x). Also you need to change signature of method addSomething from addSomething(cls, x) to addSomething(self, x)

http://stackoverflow.com/q/51172489
type: Question
tagged with: class
has title: Can't make use of a link generated by a method within my scraper
has answer: http://stackoverflow.com/a/51173084
downvote count: 0
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/89327841
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89328241
has body: I'm very new to write and work with classes in python. I've written a parser using class to check whether there is any next page url generated by .get_nextpage() method. However, when .get_nextpage() method produces a link then it should be printed right after self.get_nextpage(soup) line in try except block within .get_links() method. I've got stuck here as to how I can make it possible. No alternative solution is what I'm after. I just wish to know the logic If I can make a go. I used while True condition within .get_links() method so that it will run until the .get_nextpage() method generates a new link. (It's not the part of this question. Just to let you know why I used "while True" there) This is the scraper: import requests from bs4 import BeautifulSoup from urllib.parse import urljoin url = "https://stackoverflow.com/questions/tagged/web-scraping" class StackOverflowClass(object): def __init__(self, link): self.url = link def get_links(self): while True: res = requests.get(self.url) soup = BeautifulSoup(res.text,"lxml") try: self.get_nextpage(soup) # what to do here to get the link generated within ".get_nextpage()" method except:break def get_nextpage(self,sauce): nurl = sauce.select_one("div.pager a[rel='next']") if nurl: link = urljoin(self.url,nurl.get("href")) crawler = StackOverflowClass(url) crawler.get_links() To be clearer what I meant, take a look at the following lines once again: try: self.get_nextpage(soup) # what to do here to get the link generated within ".get_nextpage()" method except:break
tagged with: python
has comment: http://stackoverflow.com/comment/89327843
accepted answer: http://stackoverflow.com/a/51173084
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89328639
score: 1
tagged with: web-scraping
upvote count: 1

http://stackoverflow.com/comment/89384812
type: QuestionComment
has text: Yes, but there are features in python 3.7, such as breakpoint(), that aren't available in the openSUSE 3.4.6 python package. python 3.7.0 is now the latest release version. In any case, the distro packages are usually pretty far behind, so many people may want to build and install Python from source.
comment on: http://stackoverflow.com/q/51201459
score: 0
type: Comment

http://stackoverflow.com/a/51200875
has body: Your indentation is incorrect. In Python indentation signals the end of a code block import openpyxl, glob # This loops through all of the workbooks for file in glob.glob('*.xlsx'): wb = openpyxl.load_workbook(file) # Now, once all of the workbooks have been looped through, only the last one is edited for sheetName in wb.worksheets: if sheetName.title != 'abc': wb.remove(sheetName) wb.save(file) Try this import openpyxl, glob for file in glob.glob('*.xlsx'): wb = openpyxl.load_workbook(file) for sheetName in wb.worksheets: if sheetName.title != 'abc': wb.remove(sheetName) wb.save(file)
type: Answer
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/51200747
downvote count: 0

http://stackoverflow.com/q/51258954
accepted answer: http://stackoverflow.com/a/51258988
downvote count: 0
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/89497599
type: AnsweredQuestion
has body: I have a list of coordinates that looks like this: my_list = [[1, 1], [1, 3], [1, 5], [2, 1], [2, 3]] As we see, there are same X values for first three coordinates with different Y and same situation for another two coordiantes. I want to make new list which will look like this: new_list = [[1, 3], [2, 2]] where y1 = 3 = (1+3+5)/3 and y2 = 2 = (1+3)/2. I have written my code which is below, but it works slowly. I work with hundreds of thousands coordinates so the question is: How to make this code work faster? Is there any optimization or special open source libraty, which can speed up my code? Thank you in advance. x_mass = [] for m in mass: x_mass.append(m[0]) set_x_mass = set(x_mass) list_x_mass = list(set_x_mass) performance_points = [] def function(i): unique_x_mass = [] for m in mass: if m[0] == i: unique_x_mass.append(m) summ_y = 0 for m in unique_x_mass: summ_y += m[1] point = [float(m[0]), float(summ_y/len(unique_x_mass))] performance_points.append(point) return performance_points for x in list_x_mass: function(x)
has answer: http://stackoverflow.com/a/51258988
tagged with: coordinates
type: Question
possible better answer: http://stackoverflow.com/a/51259109
has title: Python 3.6. Get average Y for all same X coordinates
score: 4
tagged with: python-3.6
has answer: http://stackoverflow.com/a/51259109
upvote count: 4
answer count: 2

http://stackoverflow.com/a/51173400
accepted answer of: http://stackoverflow.com/q/51172775
type: Answer
has body: You problem/error comes from you input shape. Your input shape is too small. All pre-trained networks have a minimum of image size. For ResNet50 this minimum is 197. Increase you SAMPLE_SHAPE to 197 or to the default size for ResNet50, 224: SAMPLE_SHAPE = (197,197,3) or SAMPLE_SHAPE = (224,224,3) if your images are smaller, resize them to 197 or 224
upvote count: 1
downvote count: 1
score: 0
answers question: http://stackoverflow.com/q/51172775
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89329729

http://stackoverflow.com/comment/89473422
type: QuestionComment
has text: Thanks, I saw that earlier, just now saw again, yes, its almost same, but could you please guide what that [...] means cause i have to use it twice, as i have to use it multiple times. as its not straight assign but df=df-np.mean(df), so how to use [...] in this case?
type: Comment
comment on: http://stackoverflow.com/q/51241068
score: 0

http://stackoverflow.com/q/51266282
has comment: http://stackoverflow.com/comment/89511015
tagged with: postgresql
type: UnansweredQuestion
has body: I would like to upload some data that is currently stored in postGreSQL to Google Bigquery to see how the two tools compare. To move data around there are many options but the most user friendly (for me) one I found thus far leverages the power of python pandas. sql = "SELECT * FROM {}".format(input_table_name) i = 0 for chunk in pd.read_sql_query(sql , engine, chunksize=10000): print("Chunk number: ",i) i += 1 df.to_gbq(destination_table="my_new_dataset.test_pandas", project_id = "aqueduct30", if_exists= "append" ) however this approach is rather slow and I was wondering what options I have to speed things up. My table has 11 million rows and 100 columns. The postGreSQL is on AWS RDS and I call python from an Amazon EC2 instance. Both are large and fast. I am currently not using multiple processors although there are 16 available.
has answer: http://stackoverflow.com/a/51267059
tagged with: python
upvote count: 1
tagged with: google-bigquery
downvote count: 1
type: Question
score: 0
tagged with: pandas
has title: Speed up PostgreSQL to BigQuery
tagged with: amazon-ec2
answer count: 1
favorite count: 0

http://stackoverflow.com/q/51292186
downvote count: 0
tagged with: pytest
has title: with pytest.raises(Exception) not working with flask app.post
accepted answer: http://stackoverflow.com/a/51292731
type: Question
upvote count: 2
answer count: 2
has answer: http://stackoverflow.com/a/51292731
tagged with: flask
has body: i have a folder like this python ├── foo │ ├── __init__.py │ └── web │ ├── __init__.py │ ├── api │ │ ├── __init__.py │ │ └── helper_api.py │ └── server.py └── test_server.py ├── test_helper_api.py The helper_api.py is like @helper_api.route("/helper", methods=['POST']) def helper(): data = request.get_json(force=True, silent=True, cache=True) if data is None: raise QueryParseException("JSON-formatted query is required, none found") In the test_helper_api.py, I have import ...... from foo.web.api.helper_api import QueryParseException class TestClass(object): @pytest.fixture def client(self, request): self.client = server.app.test_client() return self.client def test_helper_api(self, client): with pytest.raises(QueryParseException): client.post('/helper') When I run the test class, the code fails at client.post, a exception was raised, however pytest failed to catch it. ---------------------------------------------------- Captured log call ----------------------------------------------------- app.py 1761 ERROR Exception on /helper [POST] Traceback (most recent call last): File "/Users/...personal path.../flask/app.py", line 2292, in wsgi_app response = self.full_dispatch_request() ....... File "/Users/...personal path.../foo-1.0.0-py3.6.egg/foo/web/api/helper_api.py", line 12, in precheck raise QueryParseException("JSON-formatted query is required, none found") foo.web.api.helper_api.QueryParseException: JSON-formatted query is required, none found why pytest is not catching this exception?
tagged with: python
possible better answer: http://stackoverflow.com/a/78717964
favorite count: 0
has answer: http://stackoverflow.com/a/78717964
tagged with: unit-testing
score: 2
type: AnsweredQuestion

google-app-engine-python
type: Tag
tags question: http://stackoverflow.com/q/51213822
tag name: google-app-engine-python

http://stackoverflow.com/comment/89599008
type: Comment
type: QuestionComment
has text: @J.Zagdoun I tried tokenizing the keyword, it did not make a difference.
comment on: http://stackoverflow.com/q/51309446
score: 0

http://stackoverflow.com/comment/89382478
has text: Partially worked the Port that I defined within Jenkins parameters is 22 and the port that I'm seeing within the AWS console is 0.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51198477

http://stackoverflow.com/comment/89452698
score: 0
has text: @Umair if I put it inside `def my_func(): my_var = something return my_var` and then call my_func() within a form class it does not include the output of the function
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51232227

http://stackoverflow.com/q/51284653
tagged with: python
score: 2
has comment: http://stackoverflow.com/comment/89546765
type: Question
tagged with: flask
has title: Cannot access flask web application deployed on the Google cloud platform app engine
tagged with: google-cloud-platform
answer count: 1
downvote count: 0
favorite count: 0
has body: I am successfully able to deploy the application without any errors but when I access the app URL, I get an error : Error: Not Found The requested URL / was not found on this server. When I access the error log on the cloud console, I see the error : ValueError: virtualenv: cannot access flask: No such virtualenv or site >directory My codes are listed as follows : application.py from flask import Flask, render_template, request,url_for,redirect,flash import os from sqlalchemy import create_engine from sqlalchemy.orm import scoped_session, sessionmaker app = Flask(__name__) app.secret_key = 'some_secret' engine = create_engine("postgresql://postgres:sona@localhost:1234/users") db = scoped_session(sessionmaker(bind=engine)) @app.route("/") def index(): return render_template("index.html") @app.route("/register") def register(): return render_template("register.html") @app.route("/hello", methods=["GET","POST"]) def hello(): if request.method=="GET": return redirect(url_for('index')) else: fname = request.form.get("fname") fname = fname.capitalize() lname = request.form.get("lname") lname = lname.capitalize() username = request.form.get("username") password = request.form.get("password") email = request.form.get("email") mobile = request.form.get("mobile") age = request.form.get("age") location = request.form.get("location") if fname == '' and age == '': flash('Invalid Credentials !!') return render_template("register.html",message='True') else: db.execute("INSERT INTO users(fname, lname, username, password, email, mobile, age, location) VALUES (:fname, :lname, :username, :password, :email, :mobile, :age, :location)", {"fname": fname, "lname": lname,"username": username, "password": password, "email": email, "mobile": mobile, "age": age, "location": location}) db.commit() users = db.execute("SELECT * FROM users").fetchall() return render_template("hello.html",fname=fname,lname=lname, username=username,password=password, email=email,mobile=mobile,age=age, location=locat…
has answer: http://stackoverflow.com/a/51288161
upvote count: 2
type: UnansweredQuestion
tagged with: google-app-engine
tagged with: web-applications

http://stackoverflow.com/q/51250095
score: 0
tagged with: visualization
has comment: http://stackoverflow.com/comment/89479606
answer count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/89480983
tagged with: python-3.x
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51523633
has comment: http://stackoverflow.com/comment/89482550
has comment: http://stackoverflow.com/comment/89480010
has title: plotly with Python - limits of Gantt Chart
tagged with: plotly
has comment: http://stackoverflow.com/comment/89498888
type: Question
has comment: http://stackoverflow.com/comment/89480212
has comment: http://stackoverflow.com/comment/89481566
linked to: http://stackoverflow.com/q/31820578
has body: I have a dataframe like this which is an application log: +---------+----------------+----------------+---------+----------+-------------------+------------+ | User | ReportingSubId | RecordLockTime | EndTime | Duration | DurationConverted | ActionType | +---------+----------------+----------------+---------+----------+-------------------+------------+ | User 5 | 21 | 06:19.6 | 06:50.5 | 31 | 00:00:31 | Edit | | User 4 | 19 | 59:08.6 | 59:27.6 | 19 | 00:00:19 | Add | | User 25 | 22 | 29:09.4 | 29:37.0 | 28 | 00:00:28 | Edit | | User 10 | 19 | 28:36.9 | 33:37.0 | 300 | 00:05:00 | Add | | User 27 | 22 | 13:27.7 | 16:54.9 | 207 | 00:03:27 | Edit | | User 5 | 21 | 11:22.8 | 12:37.3 | 75 | 00:01:15 | Edit | +---------+----------------+----------------+---------+----------+-------------------+------------+ I wanted to visualize the duration of adds and edits for each user, ad Gantt Chart seemed ideal for me. I was able to do it for a sample dataframe of 807 rows with the following code: data = [] for row in df_temp.itertuples(): data.append(dict(Task=str(row.User), Start=str(row.RecordLockTime), Finish=str(row.EndTime), Resource=str(row.ActionType))) colors = {'Add': 'rgb(110, 244, 65)', 'Edit': 'rgb(244, 75, 66)'} fig = ff.create_gantt(data, colors=colors, index_col='Resource', show_colorbar=True, group_tasks=True) for i in range(len(fig["data"]) - 2): text = "User: {}&lt;br&gt;Start: {}&lt;br&gt;Finish: {}&lt;br&gt;Duration: {}&lt;br&gt;Number of Adds: {}&lt;br&gt;Number of Edits: {}".format(df_temp["User"].loc[i], df_temp["RecordLockTime"].loc[i], df_temp["EndTime"].loc[i], df_temp["DurationConverted"].loc[i], counts[counts["User"] == df_temp["User"].loc[i]]["Add"].iloc[0], counts[counts["User"] == df_temp["User"].loc[i]]["Edit"].iloc[0]) fig["data"][i].update(text=text, hoverinfo="text") fig['layout'].update(autosize=True, margin=dict(l=150)) py.iplot(fig, filename='gantt-group-tasks-together', world_readable=True) and I am more than happy with the result : https://pl…

http://stackoverflow.com/a/51210848
has body: Paths mappings don't deploy your files to the remote server. You need to create a remote server configuration and upload your files to the remote machine. Pycharm has a tool for deployment as described here
score: 5
type: AcceptedAnswer
upvote count: 5
answers question: http://stackoverflow.com/q/51173450
type: Answer
accepted answer of: http://stackoverflow.com/q/51173450
downvote count: 0

http://stackoverflow.com/q/51225278
type: Question
has answer: http://stackoverflow.com/a/51225783
has title: How to dissaggregate data in pandas?
tagged with: dataframe
tagged with: python-2.7
has body: I have this dataframe: Excercise A Excercise B Excercise x Group Sex Person 1 1 4 ... A F Person 2 2 5 ... B F Person i 3 5 ... C M For clarifying reasons, here is an example of my real dataset in Excel: Dataset example. The column "Gimnasta" can be either the index or a normal column, although I have consider it as index. "Plancha" and "Staddler" are columns of exercises, and there are 17 more hidden in the snapshot. "Grupo" and "Sexo" are "Group" and "Sex" respectively. This data frame needs to be "disaggregated" in order to make a swarm plot for each exercise. This would be an example of what I need: Excercise Score Group Sex Person 1 A 1 A F Person 1 B 4 A F Person i C X C M The example in Excel:Final dataset I have followed the next tutorial: Pandas: creating dataframe rows from other dataframe information However, I am stuck because of the differences between the two examples. I have split my original df in two for making the process easier (or that is what I think) with the following code: df = pd.read_csv("data.csv",index_col=0) df2 = df'Group','Sex' df3 = df.drop(df'Group','Sex',axis=1) series = df3.stack() So that we have df2 containing just the columns of Group and Sex and df3 containing all the excercise with their scores, both dataframes with the "Gimnasta" column as index, for making it easy identify the values for each gimnast later on. I do not know how to continue.
score: 0
answer count: 2
linked to: http://stackoverflow.com/q/30829270
has answer: http://stackoverflow.com/a/51225864
accepted answer: http://stackoverflow.com/a/51225783
has comment: http://stackoverflow.com/comment/89431716
tagged with: pandas
possible better answer: http://stackoverflow.com/a/51225864
tagged with: python
type: AnsweredQuestion
tagged with: python-3.x

http://stackoverflow.com/comment/89671941
type: Comment
score: 0
comment on: http://stackoverflow.com/a/51318341
type: AnswerComment
has text: Would you know how I can access the source code within the iframe. I want to pass states and countys in the drop down menus. I can get the list of all the states and countys but when I use click() nothing happens. Thanks in advance.

http://stackoverflow.com/a/51271643
has comment: http://stackoverflow.com/comment/89526663
has comment: http://stackoverflow.com/comment/89521929
type: Answer
upvote count: 6
has comment: http://stackoverflow.com/comment/89522120
has comment: http://stackoverflow.com/comment/89522011
score: 6
has body: Executors use multithreading to accomplish this (or mulitprocessing, if you prefer). Asyncio is used to optimize code where you wait frequently for input, output operations to run. Sometimes that can be writing to files or loading websites. However, with cpu heavy operations (that don't just rely on waiting for IO), it's recommended to use something akin to threads, and, in my opinion, concurrent.futures provides a very nice wrapper for that and it is similar to Asyncio's wrapper. The reason why Asyncio.sleep would make your code run faster because it starts the function and then starts checking coroutines to see if they are ready. This doesn't scale well with CPU-heavy operations, as there is no IO to wait for. To change the following example from multiprocessing to multi-threading Simply change ProcessPoolExecutor to ThreadPoolExecutor. Here is a multiprocessing example: import concurrent.futures import time def a(z): time.sleep(1) return z*12 if __name__ == '__main__': with concurrent.futures.ProcessPoolExecutor(max_workers=5) as executor: futures = {executor.submit(a, i) for i in range(5)} for future in concurrent.futures.as_completed(futures): data = future.result() print(data) This is a simplified version of the example provided in the documentation for executors.
accepted answer of: http://stackoverflow.com/q/51271451
has comment: http://stackoverflow.com/comment/89526647
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51271451

http://stackoverflow.com/a/51274433
has comment: http://stackoverflow.com/comment/89528092
has comment: http://stackoverflow.com/comment/89527401
type: Answer
has body: You can solve your problem using the concept of a graph and its connected components. You will need module networkx. First, build a graph from the dataframe. The file names are going to be graph nodes, and two nodes are connected with an edge if the names refer to the identical files: import networkx as nx graph = nx.from_pandas_edgelist(df, 'col1', 'col2') Now, extract the connected components (subgraphs where you can get from any node to any other node): parts = list(nx.connected_components(graph)) # [{1, 2, 3, 4, 8}, {5, 6, 7}] As you can see, the names 1,2,3,4, and 8 refer to the identical files, ad so do the names 5,6, and 7. Now, you may want to convert the list of parts back to pandas. Enumerate the parts with enumerate, convert them into a list of (filename,part_id) pairs, and create a series out of the list: from itertools import chain parts_series = pd.Series(dict(chain.from_iterable(\ [[(name,part_id) for name in filenames] for part_id,filenames in enumerate(parts)]))) #File1 0 #File2 0 #File3 0 #File4 0 #File5 1 #File6 1 #File7 1 #File8 0
answers question: http://stackoverflow.com/q/51274255
has comment: http://stackoverflow.com/comment/89527452
score: 0

http://stackoverflow.com/a/51262479
has body: Use groupby and mean(). import pandas as pd df = pd.DataFrame({'disc_off_m4':['NaN','NaN','Y','Y','NaN','N','N','NaN','N','Y','Y'], 'form' : [1,1,1,1,0,1,1,0,0,0,1]}) df = df.groupby('disc_off_m4', as_index=True).mean() df.index = df.index.name + '_' + df.index print(df) # Out put: form disc_off_m4_N 0.666667 disc_off_m4_NaN 0.500000 disc_off_m4_Y 0.750000
type: Answer
upvote count: 2
has comment: http://stackoverflow.com/comment/89503788
downvote count: 1
answers question: http://stackoverflow.com/q/51262367
has comment: http://stackoverflow.com/comment/89502908
score: 1

http://stackoverflow.com/q/51178251
possible better answer: http://stackoverflow.com/a/51178277
type: AnsweredQuestion
score: 1
has body: I am trying to work with the Cornell movie dataset to create a chatbot. Here is the format of the list of strings that I want to extract from, saved as conv_lines: ["u0 +++$+++ u2 +++$+++ m0 +++$+++ ['L194', 'L195', 'L196', 'L197']", "u0 +++$+++ u2 +++$+++ m0 +++$+++ ['L198', 'L199']", "u0 +++$+++ u2 +++$+++ m0 +++$+++ ['L200', 'L201', 'L202', 'L203']"] I am trying to create the following list from the above list of strings by extracting the list inside each string. [['L194', 'L195', 'L196', 'L197'], ['L198', 'L199'], ['L200', 'L201', 'L202', 'L203']] I found this code but don't understand how it works. Would someone please explain. convs = [ ] for line in conv_lines[:-1]: _line = line.split(' +++$+++ ')[-1][1:-1].replace("'","").replace(" ","") convs.append(_line.split(',')) I don't understand why the [:-1] was used in the for statement, and after the code after the split.
has answer: http://stackoverflow.com/a/51178750
type: Question
downvote count: 0
tagged with: dataset
tagged with: string
has answer: http://stackoverflow.com/a/51178299
answer count: 3
has title: Extracting List from Within a String in Python
accepted answer: http://stackoverflow.com/a/51178750
favorite count: 0
tagged with: extract
has answer: http://stackoverflow.com/a/51178277
upvote count: 1
tagged with: python

http://stackoverflow.com/comment/89371228
type: Comment
comment on: http://stackoverflow.com/a/51194532
type: AnswerComment
score: 0
has text: @sacul 10000000 is a tiny number ?

http://stackoverflow.com/comment/89344166
has text: @user3483203, I don't think that's true. You can use `df.loc` to drop rows via a Boolean series, no need for `drop`. I suggest OP do some more debugging themselves, e.g. try `df['B'].iloc[2] == ''`. This is basic debugging which should be learnt when using Python (or any language).
comment on: http://stackoverflow.com/q/51180771
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89345905
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51181710
has text: Other problems: List x is appending integers at first, then assigning strings, then being used to search for a string in mylist. Also, the time complexity of searching a list scales with the size of the list , so it is not the best choice of data structure for this problem. Have you covered data structures and time complexity in your study of Python yet? It would be needed for this type of problem.
score: 0

http://stackoverflow.com/q/51229872
has title: python, move the row rightward when there is none and fill missing by back filling
score: 2
has comment: http://stackoverflow.com/comment/89446787
has body: Data: year all deceased living data 0 2018 7,107 4,394 2,713 None 1 2017 16,478 10,286 6,192 None 2 2016 15,944 9,971 5,973 None 3 Alabama To Date 5,926 3,471 2,455 124 1990 85 49 36 None 125 1989 80 57 23 None 126 1988 86 68 18 None 127 Arkansas To Date 2,963 1,931 1,032 128 1989 16 12 4 None 129 1988 16 11 5 None I want to detect rows with the data=None, move those rows rightward for one column, leaving the first column missing, and fill it by backward filling. Result: state year all deceased living 0 None 2018 7,107 4,394 2,713 1 None 2017 16,478 10,286 6,192 2 None 2016 15,944 9,971 5,973 3 Alabama To Date 5,926 3,471 2,455 124 Alabama 1990 85 49 36 125 Alabama 1989 80 57 23 126 Alabama 1988 86 68 18 127 Arkansas To Date 2,963 1,931 1,032 128 Arkansas 1989 16 12 4 129 Arkansas 1988 16 11 5 At last I will delete rows with year=To Date, making it a formal dataset. thanks.
type: Question
tagged with: dataframe
has answer: http://stackoverflow.com/a/51233659
upvote count: 2
tagged with: pandas
answer count: 1
downvote count: 0
linked to: http://stackoverflow.com/q/51184346
favorite count: 0
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/89431592
type: QuestionComment
type: Comment
has text: Can you post the error that you are getting?
score: 1
comment on: http://stackoverflow.com/q/51225657

http://stackoverflow.com/comment/89500955
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51259286
has text: I fixed it but your suggestions went a long way. Thank you anyways.

http://stackoverflow.com/a/51302710
has body: You need to post your python code, otherwise it's hard to say for sure. It could be that you are missing the relevant module import: https://www.pydoc.io/pypi/django-cassandra-engine-1.1.0/autoapi/management/commands/sync_cassandra/index.html You can take a look here, I think you will find this useful: https://github.com/r4fek/django-cassandra-engine/blob/master/django_cassandra_engine/management/commands/sync_cassandra.py
has comment: http://stackoverflow.com/comment/89583350
answers question: http://stackoverflow.com/q/51301761
score: 0
type: Answer

http://stackoverflow.com/q/51280861
type: AnsweredQuestion
score: 2
has comment: http://stackoverflow.com/comment/89539115
upvote count: 2
type: Question
accepted answer: http://stackoverflow.com/a/51280970
tagged with: indexing
has body: I have a dataframe with a large multiindex, sourced from a vast number of csv files. Some of those files have errors in the various labels, ie. "window" is missspelled as "winZZw", which then causes problems when I select all windows with df.xs('window', level='middle', axis=1). So I need a way to simply replace winZZw with window. Here's a very minimal sample df: (lets assume the data and the 'roof', 'window'… strings come from some convoluted text reader) header = pd.MultiIndex.from_product(['roof', 'window', 'basement'], names = ['top', 'middle', 'bottom']) dates = pd.date_range('01/01/2000','01/12/2010', freq='MS') data = np.random.randn(len(dates)) df = pd.DataFrame(data, index=dates, columns=header) header2 = pd.MultiIndex.from_product(['roof', 'winZZw', 'basement'], names = ['top', 'middle', 'bottom']) data = 3*(np.random.randn(len(dates))) df2 = pd.DataFrame(data, index=dates, columns=header2) df = pd.concat([df, df2], axis=1) header3 = pd.MultiIndex.from_product(['roof', 'door', 'basement'], names = ['top', 'middle', 'bottom']) data = 2*(np.random.randn(len(dates))) df3 = pd.DataFrame(data, index=dates, columns=header3) df = pd.concat([df, df3], axis=1) Now I want to xs a new dataframe for all the houses that have a window at their middle level: windf = df.xs('window', level='middle', axis=1) But this obviously misses the misspelled winZZw. So, how I replace winZZw with window? The only way I found was to use set_levels, but if I understood that correctly, I need to feed it the whole level, ie df.columns.set_levels([u'window',u'window', u'door'], level='middle',inplace=True) but this has two issues: I need to pass it the whole index, which is easy in this sample, but impossible/stupid for a thousand column df with hundreds of labels. It seems to need the list backwards (now, my first entry in the df has door in the middle, instead of the window it had). That can probably be fixed, but it seems weird I can work around these issues by xsing a new df of only w…
possible better answer: http://stackoverflow.com/a/78148367
tagged with: dataframe
has answer: http://stackoverflow.com/a/78148367
has title: How to replace a string in a pandas multiindex?
has comment: http://stackoverflow.com/comment/89539811
answer count: 2
has comment: http://stackoverflow.com/comment/89539867
tagged with: pandas
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/51280970
tagged with: python

http://stackoverflow.com/q/51304635
answer count: 1
tagged with: pybind11
score: 4
has answer: http://stackoverflow.com/a/51352302
tagged with: spyder
accepted answer: http://stackoverflow.com/a/51352302
tagged with: python
has title: Pybind: Is it possible to inform Python about the names of the arguments for constructors?
favorite count: 0
tagged with: constructor
downvote count: 0
upvote count: 4
type: AnsweredQuestion
tagged with: anaconda
has body: In Pybind it is possible to inform Python about the names of the arguments for functions: m.def("add", &amp;add, "A function which adds two numbers", py::arg("i"), py::arg("j")); (http://pybind11.readthedocs.io/en/stable/basics.html#keyword-arguments) Is there something similar for constructors? Spyder (Anaconda) already shows the input arguments of functions by default, but for constructors the "help" only shows: (*args, **kwargs).
type: Question

http://stackoverflow.com/q/51273823
has comment: http://stackoverflow.com/comment/89547868
has comment: http://stackoverflow.com/comment/89526075
type: Question
has comment: http://stackoverflow.com/comment/89527441
has comment: http://stackoverflow.com/comment/89526098
has comment: http://stackoverflow.com/comment/89526810
duplicate of: http://stackoverflow.com/q/16176996
has comment: http://stackoverflow.com/comment/89548121
has comment: http://stackoverflow.com/comment/89526386
score: 0
has comment: http://stackoverflow.com/comment/89547485
linked to: http://stackoverflow.com/q/16176996
tagged with: pandas
has title: Pandas: convert column to datetime format
has comment: http://stackoverflow.com/comment/89548081
has comment: http://stackoverflow.com/comment/89547986
has body: I have a pandas column ['Date'] which has of the type datetime.datetime and looks like 2014-07-30 00:00:00. Now I want to convert it to the same datatype datetime.datetime but minus the time that is 2014-07-30 . I tried a bunch of stuff like: df['PSG Date '] = pd.to_datetime(df['PSG Date '], format='%Y-%m-%-d %H:%M:%S') but it didn't work. edit a=df['PSG Date '].iloc[0] print(a,type(a)) gives &lt;class 'datetime.datetime'&gt; doing df['PSG Date '] = df['PSG Date '].dt.date gives - AttributeError: Can only use .dt accessor with datetimelike values printing df['PSG Date'] gives the column with values like 2013-10-30 00:00:00 so on
has comment: http://stackoverflow.com/comment/89548487
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89526133
tagged with: python
has comment: http://stackoverflow.com/comment/89547965
has comment: http://stackoverflow.com/comment/89549532
answer count: 0

http://stackoverflow.com/comment/89587457
type: AnswerComment
type: Comment
has text: Thanks but here doesn't work :( **Output** **First sentence:** table ahahave the chber be breakn **Second sentence:** chewillolhahave be plie in the street **Third sentence:** I hahave a lot of cat. It works for a few words, but the others get very strange. Thank you for your help.
comment on: http://stackoverflow.com/a/51303150
score: 0

http://stackoverflow.com/a/51323693
has comment: http://stackoverflow.com/comment/89623676
answers question: http://stackoverflow.com/q/51323622
has comment: http://stackoverflow.com/comment/89641254
type: Answer
has comment: http://stackoverflow.com/comment/89639591
has comment: http://stackoverflow.com/comment/89623339
has body: Try this - correct_answer= 41 guess = raw_input("Guess the number") try: guess = int(guess) except ValueError: print "Wrong value entered" if guess == correct_answer: print ("You found my number!") elif.... Let me know if that helps When you take the input and someone enters an alphabet or something which is not an integer, and you try to typecast it, python will throw a ValueError. To catch such cases, we use try except block will catch it. More about python try except in python Couple of pointers about your code - if int(input()) == correct_answer: here, you are just calling input() function and your program will not work, use variable guess, this is the variable you have put your input into. and if int(input()) == correct_answer: print ("You found my number!") if int (input()) &gt;= correct_answer: print ("My number is lower.") if int (input()) &lt;= correct_answer: print ("My number is higher.") Use python's if elif elif else instead. Also, since you have typecasted to integer already, you don't need to do that with every if condition, this would suffice - if input &gt; correct_answer and you don't need &gt;= or &lt;=. &gt;= means greater or equal, but you have handled the equal case in first condition, if it's equal, it'll be caught there, similar with less than or equal
score: 0

http://stackoverflow.com/a/51228667
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/51228122
has body: Python strings are just strings of Unicode characters, they don't say anything about font one way or another. The font is determined by whatever is rendering the characters, e.g. the terminal program you're using, or the browser you're using. The print function just spits out the resulting string. As you pointed out, if you're in a terminal that understands those escape sequences, then you can use those to affect the output. If your output is a web page, then you can embed html code to specify whatever you like, but all the python interpreter sees is a string of characters, not a string of characters in any particular font.
accepted answer of: http://stackoverflow.com/q/51228122
score: 5
upvote count: 5
type: AcceptedAnswer

http://stackoverflow.com/comment/89557359
comment on: http://stackoverflow.com/a/51289404
type: Comment
score: 0
type: AnswerComment
has text: @chepner: what??

http://stackoverflow.com/a/51313427
has comment: http://stackoverflow.com/comment/89605118
has body: It looks like that web page may be using JavaScript to populate and update that number. I'm not familiar with BeautifulSoup but I don't think it will run the JavaScript on the page to update that number. You may want to use something like Chrome Developer Tools to keep an eye on the network tab. I looked and it looks like there is a websocket connection to wss://push.wallstreet-online.de/lightstreamer going on behind the scenes. You may want to use a websocket client Python library to read from this socket and either find some API docs or reverse engineer the data that comes from the socket. Good luck!
downvote count: 0
answers question: http://stackoverflow.com/q/51313195
type: Answer
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/89605308

http://stackoverflow.com/comment/89476995
type: QuestionComment
has text: @dportman Please see edited version now.
comment on: http://stackoverflow.com/q/51248810
score: 0
type: Comment

http://stackoverflow.com/comment/89553951
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/51287668
has text: But this does not explain the `global` statement?? Please refresh to see my edited question, I added another part for `global`.

http://stackoverflow.com/comment/89503093
score: 1
comment on: http://stackoverflow.com/q/51262549
has text: Side note, don't shadow built-ins, use `lst` or `list_` or `L` instead of `list` for your variable name.
type: QuestionComment
type: Comment

http://stackoverflow.com/q/51191538
score: 3
has title: How to create a list of unique ID from a column in pandas where lists of ID are mentioned as strings in Python
tagged with: dataframe
answer count: 2
has answer: http://stackoverflow.com/a/51191778
tagged with: pandas
accepted answer: http://stackoverflow.com/a/51191778
has answer: http://stackoverflow.com/a/51192056
has body: I have a pandas dataframe df import pandas as pd lst = [23682, 21963, 9711, 21175, 13022,1662,7399, 13679, 17654,4567,23608,2828, 1234] lst_match = ['[21963]','[21175]', '[1662 7399 13679 ]','[17654 23608]','[2828]','0','0','0','0','0','0', '0','0' ] df = pd.DataFrame(list(zip(lst, lst_match)),columns=['ID','ID_match']) df ID ID_match 0 23682 [21963] 1 21963 [21175] 2 9711 [1662 7399 13679] 3 21175 [17654 23608] 4 13022 [2828] 5 1662 0 6 7399 0 7 13679 0 8 17654 0 9 4567 0 10 23608 0 11 2828 0 12 1234 0 The values in ID_match column are also IDs though in a list in string format. I want to create a dataframe of unique IDs in such a manner that my unique ID frame should contain all the ID which have some value other than 0 in ID_match column and those IDs' which are mentioned in the ID_match column. so my output dataframe of unique ID's must look like: ID 0 23682 1 21963 2 9711 3 21175 4 13022 5 1662 6 7399 7 13679 8 17654 9 23608 10 2828 How can I do this with python pandas?
favorite count: 0
upvote count: 3
tagged with: python
downvote count: 0
possible better answer: http://stackoverflow.com/a/51192056
type: Question
type: AnsweredQuestion

http://stackoverflow.com/comment/89375504
score: 0
has text: I have the 1.11 version of django, and 2.7.12 version of python
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51178308

http://stackoverflow.com/a/63785959
score: 9
type: Answer
answers question: http://stackoverflow.com/q/51264355
upvote count: 9
downvote count: 0
has body: I ran into problems with the typeshed defs and ended up using the following: class Writer(Protocol): def writerow(self, row: Iterable[Any]) -&gt; Any: ... def writerows(self, rows: Iterable[Iterable[Any]]) -&gt; None: ... Reader = Iterator[Any] writer: Writer = csv.writer(open('outfile.csv', 'w')) reader: Reader = csv.writer(open('outfile.csv', 'w'))

http://stackoverflow.com/comment/89343570
score: 0
type: AnswerComment
type: Comment
has text: I will. Thanks a lot for the help! @nosklo
comment on: http://stackoverflow.com/a/51180392

http://stackoverflow.com/a/51307130
answers question: http://stackoverflow.com/q/51307061
has comment: http://stackoverflow.com/comment/89593301
accepted answer of: http://stackoverflow.com/q/51307061
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/89591634
type: Answer
has comment: http://stackoverflow.com/comment/89594117
has comment: http://stackoverflow.com/comment/89591689
has body: Use merge with numpy.where: df3 = df1'No','Type'.merge(df2, on=['No','Type'], how='left') df3['Desc'] = np.where(df3['Desc'].notnull(), 'Done', df1['Desc']) print (df3) No Type Desc 0 123 A Done 1 123 B Bla 2 123 D Bla 3 342 A Done 4 342 C Done 5 543 B Bla 6 543 C Bla
upvote count: 3
score: 3

ascii
tags question: http://stackoverflow.com/q/51266556
type: Tag
tag name: ascii

http://stackoverflow.com/comment/89616770
score: 0
comment on: http://stackoverflow.com/a/51319993
type: Comment
has text: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/174931/discussion-between-irene-and-brute).
type: AnswerComment

http://stackoverflow.com/a/51172449
type: Answer
score: 2
has body: find returns the position of the string or -1 if not found, so: line.find('python') will always return a non-zero unless the line starts by python, and you'll enter the if. So every line is skipped except the ones that start with python (your first 2 lines match) You need: if line.find('python') == -1: # != -1: the string is there # python is not in the line continue but it's much better to just write: if "python" not in line: # python is not in the line continue since you don't need to know where is python located in the line. Also: perform the rstrip() operation only if you need to print the line. Else it just wastes CPU since the result of find doesn't depend on it. So to sum it up here's how I would write it: with open('demo.txt') as fhand: for line in fhand: if "python" in line: print(line.rstrip())
downvote count: 0
answers question: http://stackoverflow.com/q/51172346
upvote count: 2
has comment: http://stackoverflow.com/comment/89327962
has comment: http://stackoverflow.com/comment/89327940

http://stackoverflow.com/q/51276845
type: Question
has answer: http://stackoverflow.com/a/51276972
score: 5
tagged with: django
accepted answer: http://stackoverflow.com/a/51276972
tagged with: python
answer count: 1
upvote count: 5
has body: I have a model called Product and two viewsets that manage the same model in different ways. Each one must set a different value for field product_type, which is set read_only in the serializer SuplementSerializer. I trying to override perform_create() method and set the value for field product_type, but it always takes the default value. This is my model: class Product(models.Model): ROOM = 'ROOM' SUPLEMENT = 'SUPLEMENT' PRODUCT_TYPE_CHOICES = ( (ROOM, _('Room')), (SUPLEMENT, _('Suplement')) ) hotel = models.ForeignKey(Hotel, on_delete=models.PROTECT, related_name='products', verbose_name=_('Hotel')) name = models.CharField(max_length=100, verbose_name=_('Name')) product_type = models.CharField(max_length=9, choices=PRODUCT_TYPE_CHOICES, default=ROOM, verbose_name=_('Product Type')) room_type = models.ForeignKey(RoomType, null=True, blank=True, on_delete=models.PROTECT, related_name='products', verbose_name=_('Room Type')) plan_type = models.ForeignKey(PlanType, null=True, blank=True, on_delete=models.PROTECT, related_name='products', verbose_name=_('Plan Type')) content_type = models.ForeignKey(ContentType, null=True, blank=True, on_delete=models.PROTECT, related_name='rate_base_products', verbose_name=_('Rate Base')) object_id = models.PositiveIntegerField(null=True, blank=True) rate_base = GenericForeignKey('content_type', 'object_id') class Meta: verbose_name = _('Product') verbose_name_plural = _('Products') def __str__(self): return "[{}][{}]{}".format(self.id, self.hotel, self.name) def save(self, *vars, **kwargs): self.full_clean() return super().save(*vars, **kwargs) def clean(self, *vars, **kwargs): if self.content_type != None: if self.content_type.model != 'ages' and self.content_type.model != 'roombase' and self.content_type.model != 'product': raise CustomValidation(_("rate_base must be an instance of either 'Ages' or a 'RoomBase'"), 'rate_base', status.HTTP_400_BAD_REQUEST) These are my viewsets: class SuplementViewSet(viewsets.ModelViewSet): permiss…
type: AnsweredQuestion
downvote count: 0
tagged with: django-rest-framework
has title: How can I override Django Rest Framework viewset perform_create() method to set a default value to a field
favorite count: 0

http://stackoverflow.com/comment/89423056
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51221190
has text: SRY I tried this But not working

http://stackoverflow.com/comment/138076871
has text: @CharlieParker It doesn't handle nesting very well. If you have a dataclass with dataclass fields, the fields are recursively converted to dicts instead of being handled by the data class serialization code. That makes it impossible to identify the concrete class of the field during deserialization. I perfer ´.__dict__()`
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51286749
type: Comment

http://stackoverflow.com/q/51221951
linked to: http://stackoverflow.com/q/43648073
answer count: 2
has title: How to gain speed in Python function minimization to find solutions to Ellipsoid equation
downvote count: 0
has answer: http://stackoverflow.com/a/51227013
has comment: http://stackoverflow.com/comment/89426437
tagged with: minimization
favorite count: 0
tagged with: convex-optimization
has answer: http://stackoverflow.com/a/51225371
has comment: http://stackoverflow.com/comment/89431219
has body: Introduction Using Python, I want to retrieve a set of solutions that satisfy the following equation describing an ellipsoid: where H is a positive definite matrix. In order to retrieve a vector x that satisfies the condition for an arbitrary positive definite matrix 30-dimensional matrix H and arbitrary y, I will minimize the following function: from scipy.optimize import minimize import numpy as np N = 30 H = np.identity(N) y = 5 def fct(x): return np.abs(np.dot(x, np.dot(H, x))-y) x0 = np.ones(N)/ N solution = minimize(fct, x0, method='Nelder-Mead')['x'] In light of my research goal, I want to retrieve many different solutions that satisfy the condition for a large number (=500) of different positive definite matrices H. As such, I will minimize the function many times with different starting values denoted by x0 for each matrix H. I would like to tailor my approach to the problem such that I gain some performance (in terms of computational time) from special characteristics of my problem. Problem Analysis I know very little of numerical optimization (plan on diving into it when I have the time) but after having read an interesting post here and some scipy lectures I have come to the following conclusions: My problem is one of convex optimization given that H is a positive definite matrix. I believe my problem is one of unconstrained optimization. I am not sure whether my problem is well or ill conditioned. Solutions do change with a change in starting values but I think my problem is well conditioned. Questions Is it correct to state that in case H is a positive definite matrix my problem is an unconstrained convex optimization problem? The Nelder-Mead algorithm does return solutions that 'make sense'. Could I gain a speed up by leveraging characteristics of my problem? Or potentially by use of a different optimization algorithm? I am aware that there are certain methods for which supplying the jacobian and hessian dramatically improve performance but I am not s…
accepted answer: http://stackoverflow.com/a/51227013
upvote count: 1
tagged with: python
possible better answer: http://stackoverflow.com/a/51225371
has comment: http://stackoverflow.com/comment/89427926
type: AnsweredQuestion
tagged with: performance
score: 1
tagged with: scipy
has comment: http://stackoverflow.com/comment/89431200
type: Question

http://stackoverflow.com/q/51169603
downvote count: 0
has answer: http://stackoverflow.com/a/51173482
answer count: 1
favorite count: 0
upvote count: 2
has title: Changing row height for different treeviews tkitner
tagged with: python
accepted answer: http://stackoverflow.com/a/51173482
score: 2
type: AnsweredQuestion
tagged with: tkinter
type: Question
has body: I have 2 treeviews, and I want to set the row height for first to be 45. Im using style but when I change the row height for first treeview , it automatically changes the row height for second treeview. What am I doing wrong? from tkinter import * from tkinter import ttk myApp = Tk() #first tree with row height of 45 s = ttk.Style() s.configure('Treeview', rowheight=45) NewTree= ttk.Treeview(myApp, height=4, style='Treeview') NewTree['show'] = 'headings' NewTree["columns"]=("1","2") NewTree.column("1", width=50) NewTree.column("2", width=50) NewTree.heading("1", text="Col A") NewTree.heading("2", text="Col B") item = NewTree.insert("", "end", values=("value 1","value 2")) NewTree.grid(row=0,column=0,padx=5) #second tree with defult row height (it automatically changed to 45) #How to set different row heights to diferent treeviews? SecondTree= ttk.Treeview(myApp, height=4) SecondTree['show'] = 'headings' SecondTree["columns"]=("1","2") SecondTree.column("1", width=50) SecondTree.column("2", width=50) SecondTree.heading("1", text="Col A") SecondTree.heading("2", text="Col B") item = SecondTree.insert("", "end", values=("value 1","value 2")) SecondTree.grid(row=0,column=1,padx=5) myApp.mainloop()

http://stackoverflow.com/a/51319909
score: 1
downvote count: 1
accepted answer of: http://stackoverflow.com/q/51319801
has comment: http://stackoverflow.com/comment/89686071
has body: I don't understand, it's so easy with loop. Why use others complicated? abc = [(1531,), (4325,), (9204,)] def_ = [] for i in abc: def_.append(str(i[0])) print(def_)
has comment: http://stackoverflow.com/comment/89616146
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51319801
upvote count: 2
type: Answer

http://stackoverflow.com/a/77485681
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/51294268
has body: read the error, its looking for mariadb connectors in -IC:/mariadb-connector\include\mariadb. download mariadb-connector "C connector" from https://mariadb.com/downloads/connectors/connectors-data-access/c-connector/ and install. go to installation folder C:\Program Files\MariaDB\MariaDB Connector C 64-bit and copy MariaDB Connector C 64-bit folder to the location its looking for in your case -IC:/mariadb-connector\include\mariadb. so you should past it in C:/ and rename it to mariadb-connector so it can find it.
downvote count: 0
type: Answer

http://stackoverflow.com/q/51264169
has answer: http://stackoverflow.com/a/51266275
has title: pyinstaller add folder with images in exe file
answer count: 3
downvote count: 0
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/55566317
tagged with: pyinstaller
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/48617861
upvote count: 16
has body: I have a python script called main.py that uses some images in the same path, in images folder. I want to create one exe file that has also the images that are used from main.py script. myprogram |-images_folder |-main.py How I have to do? I am launching: pyinstaller --onefile --windowed main.py But it generates a main.exe that can't visualize the images, because they are not included in exe.
linked to: http://stackoverflow.com/q/7674790
has answer: http://stackoverflow.com/a/73292960
has comment: http://stackoverflow.com/comment/89507226
score: 16
type: Question

http://stackoverflow.com/comment/89552264
score: 0
type: Comment
comment on: http://stackoverflow.com/q/51284879
type: QuestionComment
has text: there's not much you can do, make `data` -> `d` will save some space. Is it a real problem, tho? 35kb does't seem that much. Is it for a web expected to run in a phone? while on the street? desktop? stable connexion?

http://stackoverflow.com/comment/89598300
type: Comment
score: 1
has text: That should only happen in the REPL or using `repr(...)`. If you print it out with `print(q)` you'll get what you want.
type: QuestionComment
comment on: http://stackoverflow.com/q/51310795

http://stackoverflow.com/q/51246874
accepted answer: http://stackoverflow.com/a/51253824
answer count: 1
has comment: http://stackoverflow.com/comment/89472966
has answer: http://stackoverflow.com/a/51253824
has body: I'm trying to get all data from a website called Correios, in this website, I need to handle some dropdowns which I'm having some issues with like: There's two dropdowns which have some dependency, I want to create a robot that passes through all the options for every item of both dropdowns and gets data. from selenium import webdriver from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support.select import Select chrome_path = r"C:\\Users\\Gustavo\\Desktop\\geckodriver\\chromedriver.exe" driver = webdriver.Chrome(chrome_path) lista_x = [] driver.get("http://www2.correios.com.br/sistemas/agencias/") driver.maximize_window() dropdownEstados = driver.find_elements_by_xpath("""//*[@id="estadoAgencia"]""") optEstados = driver.find_elements_by_xpath("""//*[@id='estadoAgencia']/option""") optMunicipios = driver.find_elements_by_xpath("""//*[@id="municipioAgencia"]/option""") for valores in optEstados: encoded = valores.text.encode() valores.click() for municipio in optMunicipios: municipio.click() There's two dropdowns, one that select States and the other select counties, the second one depends directly of the first one. I would like to know how can I pass trough all the counties options after selecting a state in a for, doing that for all states. output: selecting Estado ACRE ...selecting Municipio ACRELANDIA ...selecting Municipio ASSIS BRASIL ...selecting Municipio BRASILEIA ...selecting Municipio BUJARI ...selecting Municipio CAPIXABA ...selecting Municipio CRUZEIRO DO SUL ...selecting Municipio EPITACIOLANDIA ...selecting Municipio FEIJO ...selecting Municipio JORDAO ...selecting Municipio MANCIO LIMA ...selecting Municipio MANOEL URBANO ...selecting Municipio MARECHAL THAUMATURGO ...selecting Municipio PLACIDO DE CASTRO ...selecting Municipio PORTO ACRE ...selecting Municipio PORTO WALTER ...selecting Municipio RIO BRANCO ...sele…
has comment: http://stackoverflow.com/comment/89474158
favorite count: 0
has title: Python, selenium robot drop down selection
tagged with: python
score: 2
type: AnsweredQuestion
downvote count: 0
tagged with: selenium
type: Question
upvote count: 2

http://stackoverflow.com/comment/89589888
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51296626
type: Comment
has text: Hi Mohan, thanks. I'll try that tonight. If you can share code even better!

http://stackoverflow.com/a/51227208
has body: The thing is... you got a series. Do this instead: df = pd.Series(listA).to_frame('Column_new') Full example: import pandas as pd listA = [{'index': 0, 'keywords': ['nuclear','china','force','capabilities','pentagon','defence']}, {'index': 1, 'keywords': ['pakistan', 'membership', 'china', 'nsg', 'kirby', 'meets']}, {'index': 2, 'keywords': ['payment', 'rbi', 'applications', 'bill', 'bbpou', 'payments']}] df = pd.Series(listA).to_frame('Column_new') print(df) Returns: Column_new 0 {'index': 0, 'keywords': ['nuclear', 'china', ... 1 {'index': 1, 'keywords': ['pakistan', 'members... 2 {'index': 2, 'keywords': ['payment', 'rbi', 'a...
accepted answer of: http://stackoverflow.com/q/51227172
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/89434448
type: Answer
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/90116012
answers question: http://stackoverflow.com/q/51227172

qpushbutton
type: Tag
tags question: http://stackoverflow.com/q/51308772
tag name: qpushbutton

http://stackoverflow.com/a/51305919
has comment: http://stackoverflow.com/comment/89651988
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/89671578
has comment: http://stackoverflow.com/comment/89608449
type: Answer
answers question: http://stackoverflow.com/q/51298992
has body: Since in binary mode you are essentially predicting one value which indicates the probability of positive class (i.e. binary classification), using .argmax() on predictions always return 0. Therefore, you need to modify your output_sensitivity_specificity function for this case: def output_sensitivity_specificity(epoch, predictions, y_test, mode='binary'): if mode == 'binary': # determine positive class predictions idx = predictions &gt;= 0.5 predictions = np.zeros(predictions.shape) predictions[idx] = 1 # no need to modify y_test since it consists of zeros and ones already else: y_test = np.argmax(y_test, axis=-1) predictions = np.argmax(predictions, axis=-1) c = confusion_matrix(y_test, predictions) print('Confusion matrix:\n', c) print('[{:03d}] sensitivity'.format(epoch), c[0, 0] / (c[0, 1] + c[0, 0])) print('[{:03d}] specificity'.format(epoch), c[1, 1] / (c[1, 1] + c[1, 0])) Just pass mode=class_mode when calling output_sensitivity_specificity in your callback and it would work for both binary and categorical modes.
score: 1
has comment: http://stackoverflow.com/comment/89661814
has comment: http://stackoverflow.com/comment/89613471
upvote count: 1
accepted answer of: http://stackoverflow.com/q/51298992

http://stackoverflow.com/comment/89435026
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51222815
has text: Thank you very much! :) It helped me a lot.
type: AnswerComment

http://stackoverflow.com/a/51213360
has comment: http://stackoverflow.com/comment/89407617
answers question: http://stackoverflow.com/q/51213300
has body: You have to parse the string if you must keep the item that you are adding to the list a string representation before you are adding it. This turns the string representation of the list into an actual list. You can do this by doing: import ast MasterPots.append(ast.literal_eval(TempString)) The other solution is to have it as a list in the first place and append it to the list: MasterPots.append([PotTitle, 0]) Note that you are probably experiencing an XY Problem
score: 0
has comment: http://stackoverflow.com/comment/89407653
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89407929
has comment: http://stackoverflow.com/comment/89408027
type: Answer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/51213300
downvote count: 1
has comment: http://stackoverflow.com/comment/89407750

http://stackoverflow.com/a/51177966
accepted answer of: http://stackoverflow.com/q/51177723
has body: Have you tried to use this? The solution might be in the output actually. Hope this works for you import numpy as np data = np.loadtxt('data4.txt') i=np.array(data[:,1]) #column having thousand values j=7/2 f = i-j while np.all(f &lt;= i+j): print(f) f += 1
type: Answer
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/89338579
has comment: http://stackoverflow.com/comment/89338492
has comment: http://stackoverflow.com/comment/89338599
upvote count: 1
answers question: http://stackoverflow.com/q/51177723
type: AcceptedAnswer

http://stackoverflow.com/q/51296848
accepted answer: http://stackoverflow.com/a/51297008
tagged with: python
type: AnsweredQuestion
has body: Hi in this code I tried to calculate the paths in the binary tree(data Structure). But in some case it will give me an error said that "AttributeError: 'int' object has no attribute 'left'" How can I fix this problem? For example in this case tree = BTNode(None, BTNode(None,1, 5), BTNode(8)) I will have the attribute error. class BTNode: """A node in a binary tree.""" def __init__(self: 'BTNode', item: object, left: 'BTNode' =None, right: 'BTNode' =None) -&gt; None: """Initialize this node. """ self.item, self.left, self.right = item, left, right def __repr__(self): return 'BTNode({}, {}, {})'.format(self.item, str(self.left), str(self.right)) def tree_paths(t: BTNode) -&gt; int: '''Return number of paths to get from root of t, to all houses, and back to t. &gt;&gt;&gt; tree_paths(BTNode(None, BTNode(4), BTNode(5))) 4 ''' ll = 0 rl = 0 if t is None: return -2 if t.left is not None and t.left != int: ll = tree_paths(t.left) + 2 if t.right is not None and t.right != int: rl = tree_paths(t.right) + 2 return ll + rl The error I see is: Traceback (most recent call last): File "&lt;pyshell#11&gt;", line 1, in &lt;module&gt; tree_paths(t) File "C:\Users\ma\Desktop\CSC148\lab7\trick.py", line 60, in tree_paths ll = tree_paths(t.left) + 2 File "C:\Users\ma\Desktop\CSC148\lab7\trick.py", line 60, in tree_paths ll = tree_paths(t.left) + 2 File "C:\Users\ma\Desktop\CSC148\lab7\trick.py", line 59, in tree_paths if t.left is not None and t.left != int: AttributeError: 'int' object has no attribute 'left'
has comment: http://stackoverflow.com/comment/89571133
type: Question
has title: Calculate paths in binary tree
answer count: 1
score: 0
has answer: http://stackoverflow.com/a/51297008
has comment: http://stackoverflow.com/comment/89571084
tagged with: python-3.x

http://stackoverflow.com/comment/89588137
type: QuestionComment
has text: Just because of curiosity, why do you use so long sleeps in your tests?
score: 1
type: Comment
comment on: http://stackoverflow.com/q/51305711

http://stackoverflow.com/comment/89597944
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51296815
type: Comment
has text: you are right, as that column has been constraucted from sql stuff method and consists of various type of data type, So how can i accomplish this job, any idea? Thanks

http://stackoverflow.com/a/51280554
has comment: http://stackoverflow.com/comment/89538622
has comment: http://stackoverflow.com/comment/89539075
type: Answer
answers question: http://stackoverflow.com/q/51280326
has comment: http://stackoverflow.com/comment/89539025
has body: If you check the configuration file you'll see the following: include /etc/nginx/sites-enabled/*; This means that additional vhost config files are being loaded from "/etc/nginx/sites-enabled/". The correct way to use this is to have the config files in /etc/nginx/sites-available/ and create symlinks to them in /etc/nginx/sites-enabled/.
score: 0

http://stackoverflow.com/comment/89433543
type: Comment
has text: It requires a sequence in Python 2 as well, it just doesn't _check_ it, so if you do, say, `choice({0: "spam", 2: "eggs"})` it'll return `"spam"` half the time and `KeyError: 1` the other half the time. It doesn't actually _work_ unless your keys happen to be exactly `range(0, len(d))`. The only reason it works on `keys()` in 2.x is that `keys()` is already copying the keys into a list.
comment on: http://stackoverflow.com/a/51226639
type: AnswerComment
score: 0

http://stackoverflow.com/comment/89581278
has text: consider using `with open..` construct to avoid bugs like you have now - not closing file
score: 3
comment on: http://stackoverflow.com/q/51302227
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89495415
type: Comment
comment on: http://stackoverflow.com/q/51224314
has text: @cruisepandey please find the URL "https://id.atlassian.com"
score: 0
type: QuestionComment

http://stackoverflow.com/comment/89375982
score: 0
type: Comment
type: QuestionComment
has text: Thanks. I corrected the error. The query above was not copy/pasted form the original source so I did re-typed it. It was a typo. Sorry sbout that.
comment on: http://stackoverflow.com/q/51196758

http://stackoverflow.com/comment/89538301
has text: @Divakar: thanks for the questions. If you mean an example array, see the example I provided in the first code block. Yes, there can be overlaps; see the example in the first code block.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51280203

http://stackoverflow.com/q/51318981
has body: I measured the fluorescence intensity of thousands of particles and made the histogram, which showed two adjacent gaussian curves. How to use python or its package to separate them into two Gaussian curves and make two new plots? Thank you.
upvote count: 10
answer count: 1
favorite count: 0
tagged with: python
tagged with: plot
type: AnsweredQuestion
downvote count: 0
type: Question
has answer: http://stackoverflow.com/a/51319904
accepted answer: http://stackoverflow.com/a/51319904
tagged with: gaussian
score: 10
has title: How to use python to separate two gaussian curves?

http://stackoverflow.com/comment/89466266
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51243515
score: 0
has text: Are you sure that the task is stored in the broker?

http://stackoverflow.com/q/51203784
score: 1
has title: Python moving class to separate file causes nameError
upvote count: 1
tagged with: import
type: Question
has comment: http://stackoverflow.com/comment/89407323
tagged with: nameerror
has comment: http://stackoverflow.com/comment/89400286
downvote count: 0
answer count: 1
has body: I am simply trying to move class ScreenThree to a separate file 9 I will soon have many more)....However for the lambdas I get nameError ...how to fix? I've tried many arrangements, but allways get some sort of nameError. For this post, I have deleted ScreenTwo, since these basically all look the same. When moving this class to its own file what needs to be changed? I used import, which seemed to work &amp; screen3 shows. , However the button lambda is where it fails import tkinter as tk LARGE_FONT = ("Verdana", 12) # font's family is Verdana, font's size is 12 class MainWindow(tk.Tk): def __init__(self, *args, **kwargs): tk.Tk.__init__(self, *args, **kwargs) self.title("Fuzzy System") # set the title of the main window self.geometry("300x300") # set size of the main window to 300x300 pixels # this container contains all the screens container = tk.Frame(self) container.pack(side="top", fill="both", expand=True) container.grid_rowconfigure(0, weight=1) # make the cell in grid cover the entire window container.grid_columnconfigure(0,weight=1) # make the cell in grid cover the entire window self.frames = {} # these are screens we want to navigate to for F in (ScreenOne, ScreenTwo,ScreenThree): # for each screen frame = F(container, self) # create the screen self.frames[F] = frame # store into frames frame.grid(row=0, column=0, sticky="nsew") # grid it to container self.show_frame(ScreenOne) # let the first screen is ScreenOne def show_frame(self, name): frame = self.frames[name] frame.tkraise() class ScreenOne(tk.Frame): def __init__(self, parent, controller): self.controller=controller tk.Frame.__init__(self, parent) label = tk.Label(self, text='This is ScreenOne', font=LARGE_FONT) label.pack(pady=10, padx=10) # center alignment # when click on this button, call the show_frame method to make screenOne appear button1 = tk.Button(self, text='Visit screen two', command=lambda : controller.show_frame(ScreenTwo)) button1.pack() # pack it in self.button2 = tk.Button(self, t…
favorite count: 0
has comment: http://stackoverflow.com/comment/89413183
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89413248
tagged with: python
has answer: http://stackoverflow.com/a/51203912
linked to: http://stackoverflow.com/q/39530107
linked to: http://stackoverflow.com/q/7546050
tagged with: tkinter

http://stackoverflow.com/q/51310795
has answer: http://stackoverflow.com/a/51310983
has answer: http://stackoverflow.com/a/51310914
has comment: http://stackoverflow.com/comment/89598289
type: Question
downvote count: 2
score: -2
tagged with: string
favorite count: 0
has answer: http://stackoverflow.com/a/51310953
has title: How do you deal with multiply nested single and double quotes in Python
has body: I am trying to create the string: 185 bananas walk into a bar. The bartender says, "We don't serve bananas here." So the bananas split! If I enter q = "185 bananas walk into a bar. The bartender says, \"We don't serve bananas here.\" So the bananas split!" I get 185 bananas walk into a bar. The bartender says, "We don\'t serve bananas here." So the bananas split! I don't want the \ before the ' but I don't know how to get rid of it
answer count: 4
has comment: http://stackoverflow.com/comment/89598584
has comment: http://stackoverflow.com/comment/89598300
upvote count: 0
has comment: http://stackoverflow.com/comment/89598275
has comment: http://stackoverflow.com/comment/89598298
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89598269
has answer: http://stackoverflow.com/a/51310949

http://stackoverflow.com/q/51313324
has title: ModuleNotFoundError: No module named 'flask_session'
has answer: http://stackoverflow.com/a/56030776
has answer: http://stackoverflow.com/a/51313420
has answer: http://stackoverflow.com/a/53458690
tagged with: python
answer count: 12
has answer: http://stackoverflow.com/a/53215582
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/76282386
downvote count: 2
has answer: http://stackoverflow.com/a/51527728
has comment: http://stackoverflow.com/comment/97603410
has answer: http://stackoverflow.com/a/52805736
upvote count: 17
type: Question
has comment: http://stackoverflow.com/comment/95422313
has answer: http://stackoverflow.com/a/75808383
score: 15
has answer: http://stackoverflow.com/a/61144675
has answer: http://stackoverflow.com/a/55291960
has answer: http://stackoverflow.com/a/53787463
has body: I have a simple python file that I am trying to set up to utilize sessions, when i run the file I am receiving the error below: ModuleNotFoundError: No module named 'flask_session' I believe I am importing the module properly, is there anything else that I can check to set this up properly? from flask import Flask, render_template, request, session from flask_session import Session app = Flask(__name__) app.config["SESSION_PERMANENT"] = False app.config["SESSION_TYPE"] = "filesystem" Session(app) @app.route("/", methods=["GET", "POST"]) def index(): if session.get("notes") is None: session["notes"] = [] if request.method == "POST": note = request.form.get("note") session["notes"].append(note) return render_template("index.html", notes=notes) Here is the traceback ( most recent call last ) File "c:\python37\lib\site-packages\flask\cli.py", line 325, in __call__ Open an interactive python shell in this frameself._flush_bg_loading_exception() File "c:\python37\lib\site-packages\flask\cli.py", line 313, in _flush_bg_loading_exception reraise(*exc_info) File "c:\python37\lib\site-packages\flask\_compat.py", line 35, in reraise raise value File "c:\python37\lib\site-packages\flask\cli.py", line 302, in _load_app self._load_unlocked() File "c:\python37\lib\site-packages\flask\cli.py", line 317, in _load_unlocked self._app = rv = self.loader() File "c:\python37\lib\site-packages\flask\cli.py", line 372, in load_app app = locate_app(self, import_name, name) File "c:\python37\lib\site-packages\flask\cli.py", line 242, in locate_app '\n\n{tb}'.format(name=module_name, tb=traceback.format_exc())
tagged with: flask
favorite count: 0
has answer: http://stackoverflow.com/a/60887641

http://stackoverflow.com/a/61793256
answers question: http://stackoverflow.com/q/51215625
type: Answer
has body: OO approch: write a sort of "VideoWrapper" class and derived classes: from abc import abstractmethod class VideoWrapper: def __init__(self, path: str, chunk_size: int = 1): self.path = path self.chunk_size = chunk_size @abstractmethod def __iter__(self): ... class VideoFileWrapper(VideoWrapper): def __iter__(self): chunk = [] cap = cv2.VideoCapture(self.path) while cap.isOpened(): ret, frame = cap.read() chunk.append(frame) if len(chunk) == self.chunk_size: yield chunk chunk = [] class VideoFolderWrapper(VideoWrapper): def __iter__(self): chunk = [] for frame_path in glob(os.path.join(self.path, '*')): frame = cv2.imread(frame_path) chunk.append(frame) if len(chunk) == self.chunk_size: yield chunk chunk = [] in that case you could pass a single class type across your code. an even nicer class would implement __enter__ and __exit__ methods in order to use the with statement, exception handling and so on. that might be too much, a simpler "Pythonic" version will be: def video_wrapper(path): if os.path.isdir(path): frames = list(glob(os.path.join(path, '*.png'))) frames.sort(key=file_name_order) for frame_path in frames: frame = cv2.cvtColor(cv2.imread(frame_path),cv2.COLOR_BGR2RGB) yield frame elif os.path.exists(path): cap = cv2.VideoCapture(path) while cap.isOpened(): ret, frame = cap.read() yield frame
score: 0

http://stackoverflow.com/comment/90207549
type: Comment
type: QuestionComment
has text: @aselle, this method worked for me in terms of conversion. I just have not tested it on a phone yet. I also noticed that quantized 8UINT conversion is not supported, so when I convert it, it ends up being a FLOAT type. Let's see how fast this will work on a smartphone's CPU (I do not own a Pixel, so I can only use my CPU): https://github.com/tensorflow/tensorflow/issues/15805#issuecomment-407298717
comment on: http://stackoverflow.com/q/51275360
score: 0

http://stackoverflow.com/q/51308352
tagged with: python
tagged with: dictionary
has title: Popping the EXACT same value from a dictionary
possible better answer: http://stackoverflow.com/a/51309122
has answer: http://stackoverflow.com/a/51308726
type: AnsweredQuestion
type: Question
accepted answer: http://stackoverflow.com/a/51308726
score: 0
has body: I have a general list with information: lis = ["Hello", "Hello1", "Test"] Then I have a dictionary with filepathes to .c files as values and keys are extensions of the lis values like: dict1 = {"/****Hello****/": ["C://test/hello/one.c", "C://test/hello/two.c"], "/****Hello1****/": ["C://test/helloNext/one.c", "C://test/helloNext/two.c"], "/****Test****/": ["C://test/bye/one.c", "C://test/bye/two.c"]} The idea is to replace the keys of dict1 with the values of lis, if values of lis are in the key information. for x in lis: for y in dict1.copy(): if x in y: dict1[x] = dict1.pop(y) As far as good but now I found a big problem: If I do it that way, some information of dict1 are overwritten because in this example, it searches for a key with "Hello" in it and overwrites dict1[0] but also overwrites dict1[1] to "Hello" instead of "Hello1" because it's the first information... I don't get to a solution on my own. I think I am just missing a little bit... Thanks! PS: It is not a solution to just cut out special characters from the keys, because it does not look the same for every file..
answer count: 4
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51309122
has answer: http://stackoverflow.com/a/51309123
has answer: http://stackoverflow.com/a/51309175

http://stackoverflow.com/comment/89824642
type: Comment
type: QuestionComment
has text: Hi JPP, all sorted - just needed to change my python interpreter location!
comment on: http://stackoverflow.com/q/51322230
score: 0

http://stackoverflow.com/a/63115595
has comment: http://stackoverflow.com/comment/132283319
answers question: http://stackoverflow.com/q/51306862
type: Answer
score: 14
has body: Follow the steps in the latest version of the documentation. Note: GPU and CPU functionality is now combined in a single tensorflow package pip install tensorflow # OLDER VERSIONS pip install tensorflow-gpu https://www.tensorflow.org/install/gpu This is a great guide for installing drivers and CUDA if needed: https://www.quantstart.com/articles/installing-tensorflow-22-on-ubuntu-1804-with-an-nvidia-gpu/
upvote count: 14
downvote count: 0

http://stackoverflow.com/comment/89463698
score: 0
has text: Using Python`s fairly new Async-Functionality might be an option and an even better solution than using threads (handling the state within the thread (i.e. communicating/synchronizations threads), depending on what exactly you want to achieve. See this [blogpost](https://www.aeracode.org/2018/02/19/python-async-simplified/) for an introduction.
comment on: http://stackoverflow.com/q/51241600
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89603395
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51313328
has text: Keys are unique in dictionaries. You are reassigning YYZ to the most recent output.
score: 1

http://stackoverflow.com/comment/89982757
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51253257
type: Comment
has text: Edit: now passing an explicit cancel scope for `ratelimit` to the caller

http://stackoverflow.com/q/51181274
has title: Converting pandas Dataframe to Google spreadsheet
linked to: http://stackoverflow.com/q/45540827
tagged with: google-sheets
downvote count: 0
has comment: http://stackoverflow.com/comment/119730101
favorite count: 0
tagged with: pandas
tagged with: python
has comment: http://stackoverflow.com/comment/89346612
answer count: 0
upvote count: 3
type: UnansweredQuestion
has body: I followed this answer to this question (Appending pandas Data Frame to Google spreadsheet) to append by dataframe to an empty google spreadheet. Some data is being added to it but not how I want: code: #complete_dict is just a dictionary I created from JSON df = pd.DataFrame(complete_dict).fillna(value='0').T convert_to_csv = df.to_csv('C:/Users/Elitebook/Documents/GitHub/test3.csv') print df scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive'] credentials = ServiceAccountCredentials.from_json_keyfile_name('C:/Users/Elitebook/Documents/GitHub/TrackRev-caad86be6e44.json', scope) file = gspread.authorize(credentials) #create the empty spreadsheet new_spreadsheet = file.create('CSV-test-6') #this step is necessary so we can view the spreadsheet new_spreadsheet.share("charlesdsmith25@gmail.com", perm_type='user', role='writer') #after the spreadsheet is created, open it spreadsheet = file.open('CSV-test-6').sheet1 existing = gd.get_as_dataframe(spreadsheet) updated = existing.append(df) df_spreadsheet = set_with_dataframe(spreadsheet, updated) This is what my dataframe looks like: add_classes add_grades change_classes ... delete_grades view_classes view_grades principle 1 0 1 ... 0 1 1 student1 0 0 0 ... 0 1 1 student2 0 0 0 ... 0 1 1 teacher 0 1 0 ... 1 1 1 But this is what the spreadsheet looks like: Unnamed: 0 Unnamed: 1 Unnamed: 10 Unnamed: 11 Unnamed: 12 Unnamed: 13 Unnamed: 14 Unnamed: 15 Unnamed: 16 Unnamed: 17 Unnamed: 18 Unnamed: 19 Unnamed: 2 Unnamed: 20 Unnamed: 21 Unnamed: 22 Unnamed: 23 Unnamed: 24 Unnamed: 25 Unnamed: 3 Unnamed: 4 Unnamed: 5 Unnamed: 6 Unnamed: 7 Unnamed: 8 Unnamed: 9 add_classes add_grades change_classes change_grades delete_classes delete_grades view_classes view_grades No rows and way too many columns and the values (1s and 0s) aren't there
type: Question
score: 3

http://stackoverflow.com/a/51184421
score: 8
has comment: http://stackoverflow.com/comment/89351004
answers question: http://stackoverflow.com/q/51184346
has body: You can shift rows by boolean mask: mask = pd.to_numeric(df['Name'], errors='coerce').notnull() df[mask] = df[mask].shift(axis=1) print (df) Name Val Rating 0 ABC 123 B + 1 DEF 234 B + 2 NaN 567 B- 3 GHI 890 D Detail: print (pd.to_numeric(df['Name'], errors='coerce')) 0 NaN 1 NaN 2 567.0 3 NaN Name: Name, dtype: float64 If really need replace index values to empty strings is possible create helper Series and reindex. But this is not recommended because performance problem and possible some function with this index should failed. i = df.index[~mask] df.index = pd.Series(range(len(i)), index=i).reindex(df.index, fill_value='') print (df) Name Val Rating 0 ABC 123 B + 1 DEF 234 B + NaN 567 B- 2 GHI 890 D
has comment: http://stackoverflow.com/comment/89387916
accepted answer of: http://stackoverflow.com/q/51184346
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/89351580
upvote count: 8
type: Answer

http://stackoverflow.com/comment/89354563
score: 0
has text: Thanks your very much! Yes. As your remind, It worked!
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51185735

http://stackoverflow.com/q/51203641
possible better answer: http://stackoverflow.com/a/68674243
has answer: http://stackoverflow.com/a/51204393
favorite count: 0
tagged with: python-3.x
has title: AttributeError: module 'alembic.context' has no attribute 'config'
has answer: http://stackoverflow.com/a/68674243
type: Question
tagged with: python
accepted answer: http://stackoverflow.com/a/52575218
score: 27
answer count: 3
upvote count: 27
linked to: http://stackoverflow.com/q/46050187
tagged with: python-import
downvote count: 0
has body: I have imported context from alembic. But the variables like config and configure are unavailable in the package. What could be the reason ?
has answer: http://stackoverflow.com/a/52575218
type: AnsweredQuestion
tagged with: alembic

http://stackoverflow.com/a/51312222
type: Answer
answers question: http://stackoverflow.com/q/51312108
has body: Actually, you are pretty close with your second attempt. Using regex sub for replacing, it can be done like this: import re regex = r"['()&amp;]" test_str = "\"Hi there Sam! Don't you know that Alex (the programmer) created something useful or &amp; easy to control\"" subst = "" # You can manually specify the number of replacements by changing the 4th argument result = re.sub(regex, subst, test_str, 0, re.MULTILINE) if result: print (result) If you want to replace the &amp; with and run another: result = re.sub(r" &amp; ", " and ", test_str, 0, re.MULTILINE) and remove the &amp; from the first regex character group ['()&amp;].
score: 0

http://stackoverflow.com/q/51280121
score: 1
type: Question
tagged with: indexing
has answer: http://stackoverflow.com/a/51280341
accepted answer: http://stackoverflow.com/a/51280341
has title: How to construct a table of frequency counts of items in a pandas dataframe?
tagged with: pandas
upvote count: 1
downvote count: 0
answer count: 1
favorite count: 0
tagged with: word-frequency
tagged with: python
has body: Say I have the following data in a csv file, example.csv: Word Score Dog 1 Bird 2 Cat 3 Dog 2 Dog 3 Dog 1 Bird 3 Cat 1 Bird 1 Cat 3 I want to count the frequency of each word for each score. The expected output is the following: 1 2 3 Dog 2 1 1 Bird 0 1 1 Cat 1 0 2 My code to do this is as follows: import pandas as pd x1 = pd.read_csv(r'path\to\example.csv') def getUniqueWords(allWords) : uniqueWords = [] for i in allWords: if not i in uniqueWords: uniqueWords.append(i) return uniqueWords unique_words = getUniqueWords(x1['Word']) unique_scores = getUniqueWords(x1['Score']) scores_matrix = [[0 for x in range(len(unique_words))] for x in range(len(unique_scores)+1)] # The '+1' is because Python indexing starts from 0; so if a score of 0 is present in the data, the 0 index will be used for that. for i in range(len(unique_words)): temp = x1[x1['Word']==unique_words[i]] for j, word in temp.iterrows(): scores_matrix[i][j] += 1 # Supposed to store the count for word i with score j But this gives the following error: IndexError Traceback (most recent call last) &lt;ipython-input-123-141ab9cd7847&gt; in &lt;module&gt;() 19 temp = x1[x1['Word']==unique_words[i]] 20 for j, word in temp.iterrows(): ---&gt; 21 scores_matrix[i][j] += 1 IndexError: list index out of range Also, even if I could fix this error, the scores_matrix would not show the headers (Dog, Bird, Cat as row indices, and 1, 2, 3 as column indices). I would want to be able to access the count for each word with each score - something to this effect: scores_matrix['Dog'][1] &gt;&gt;&gt; 2 scores_matrix['Cat'][2] &gt;&gt;&gt; 0 So, how would I solve/fix both these issues?
type: AnsweredQuestion
tagged with: frequency-distribution

http://stackoverflow.com/comment/89371056
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51194183
has text: is it the real code or you adapted ? The error comes from this code or the original one ?
score: 0

http://stackoverflow.com/comment/89589080
comment on: http://stackoverflow.com/q/51305831
score: 0
type: Comment
type: QuestionComment
has text: @JohnAnderson it didn't change anything

http://stackoverflow.com/q/51307573
has comment: http://stackoverflow.com/comment/89616353
has comment: http://stackoverflow.com/comment/89759970
has comment: http://stackoverflow.com/comment/89740164
score: 0
tagged with: google-cloud-platform
tagged with: google-api-client
has comment: http://stackoverflow.com/comment/89739924
has answer: http://stackoverflow.com/a/51384933
accepted answer: http://stackoverflow.com/a/51384933
has comment: http://stackoverflow.com/comment/89740545
answer count: 1
has comment: http://stackoverflow.com/comment/89861014
has comment: http://stackoverflow.com/comment/89914974
tagged with: snapshot
has body: I have written following code, which return me list of Snapshot, which have particular string, but this does not return snapshots whose Size is 0, https://cloud.google.com/compute/docs/reference/rest/v1/snapshots/list this API have following attributes: project_id filter I am trying to put some filter based on regular expression which will match all snapshot which have "intance-snap" in there name. def snapshotlist(): query = "name eq &lt;string&gt;.*" snaplist = compute.snapshots().list(project=project,filter=query).execute() snaplist = ast.literal_eval(json.dumps(snaplist)) for snap in snaplist['items']: print(snap['name']) Above code does not return Snapshots, which have size 0, is there way to get all snapshots, regardless of there SIZE ?
tagged with: python
has comment: http://stackoverflow.com/comment/89971884
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89592191
has title: Google API to get Snapshot using filter,
type: Question

http://stackoverflow.com/a/51183575
has comment: http://stackoverflow.com/comment/89353362
type: Answer
has comment: http://stackoverflow.com/comment/89352567
upvote count: 1
has comment: http://stackoverflow.com/comment/89353693
has body: You need first sort columns by sort_values and then groupby with custom function with numpy.split and return length of each group to new row of new DataFrame: Idea from perfect MaxU answer, thank you. Use for top 30-30-30: user = user.sort_values(['User','Count'], ascending=[True, False]) def f(x): #split to 4 groups, because 3 + 3 + 3 != 1 a, b, c, d = np.split(x, [int(.3*len(x)), int(.6*len(x)), int(.9*len(x))]) return pd.Series([len(a), len(b), len(c)], index=['30','30','30']) df = user.groupby('User').apply(f) df['sum'] = df.sum(axis=1) print (df) 30 30 30 sum User 101 1 2 1 4 102 2 2 2 6 and for 30-30-40: user = user.sort_values(['User','Count'], ascending=[True, False]) def f(x): #split to 3 groups, because 3 + 3 + 4 == 1 a, b, c = np.split(x, [int(.3*len(x)), int(.6*len(x))]) return pd.Series([len(a), len(b), len(c)], index=['30','30','40']) df = user.groupby('User').apply(f) df['sum'] = df.sum(axis=1) print (df) 30 30 40 sum User 101 1 2 2 5 102 2 2 3 7 EDIT: Groups should be created by list comprehension: def f(x): a, b, c = np.split(x.index, [int(.3*len(x)), int(.6*len(x))]) L = [a,b,c] return [i for i, y in zip(range(len(L),0,-1) ,L) for j in y] user['Groups'] = user.groupby('User')['User'].transform(f) print (user) User Country Count Groups 0 101 India 85 3 1 101 Japan 78 2 2 101 India 70 2 6 101 Austria 60 1 5 101 UK 8 1 7 102 Japan 30 3 4 102 Japan 6 3 9 102 UK 6 2 3 102 Brazil 5 2 8 102 Singapore 5 1 10 102 UK 5 1 11 102 UK 4 1
has comment: http://stackoverflow.com/comment/89353334
score: 1
answers question: http://stackoverflow.com/q/51183277
has comment: http://stackoverflow.com/comment/89352643
has comment: http://stackoverflow.com/comment/89353087
has comment: http://stackoverflow.com/comment/89354184
accepted answer of: http://stackoverflow.com/q/51183277
has comment: http://stackoverflow.com/comment/89353358
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/89381366
type: QuestionComment
comment on: http://stackoverflow.com/q/51198043
score: 0
has text: i don't see any link between the file app.py and models.py/view.py, how are you running the app ?
type: Comment

http://stackoverflow.com/comment/89322849
has text: @VivekKumar I added a part of my dataset and the code I put in the question is all the code I use. Locally I use the latest version of scikit-learn and numpy 14.4.4 instead of 14.4.5 and I do not use pandas. And in Azure ML Studio, it is Microsoft which manage the environment and it uses Anaconda4.0/python3.5
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51168298
score: 0

http://stackoverflow.com/q/51205071
downvote count: 1
score: 2
type: Question
answer count: 1
has answer: http://stackoverflow.com/a/51206440
has title: how to get the row number of an item in the qlistwidget using Pyqt5 in python
has body: How to get the row number of each item in the QlistWidget i a able to get the text of the item but not the row number. the expected result : current row ==> 1 checkpath Displayed Path => C:/Users/test/Downloads\cv.docx i don't know how to return the row number i tried the index but it return a wrong result. I think this is the line that must changed: print("current row ==&gt; {} \n checkpath Displayed Path =&gt; {}".format(index,self.fullPath)) where index is used in enumarate. code: def checkPath(self,folder): # Funtion to check the given path for the wanted extension (Files) try: directory=folder whichChecked="" for root,dirs,files in os.walk(directory): for index,filename in enumerate(files): if len(self.lineEdit_Ext.text())&gt;0: self.lineEdit_Ext.setStyleSheet("background-color:white") self.lineEdit_Ext.setPlaceholderText("Enter The Filetype Extention Here") if filename.endswith(self.lineEdit_Ext.text()): fullPath=os.path.join(root,filename) print(fullPath) self.fileList.append(fullPath) elif self.rdBtn_docx.isChecked() and filename.endswith("docx") or filename.endswith("doc") : self.fullPath=os.path.join(root,filename) index = +1 print("current row ==&gt; {} \n checkpath Displayed Path =&gt; {}".format(index,self.fullPath)) print("=========================================") self.fileList.append(self.fullPath) whichChecked="docx - doc Ext was Selected" if len(self.fileList) &gt; 0: self.lineEdit_Ext.setStyleSheet("bacground-color:white;") self.lineEdit_Ext.setPlaceholderText("{0}".format(whichChecked)) else: self.lineEdit_Ext.setStyleSheet("background-color:Red") self.lineEdit_Ext.setPlaceholderText("No Ext is Specified") self.ListFilesInViewer(self.fileList) # add the list into the listWidgetPDFlist return folder except Exception as e: print("this error occure {0}".format(e))
tagged with: python
favorite count: 0
upvote count: 3
tagged with: row-number
type: UnansweredQuestion
tagged with: pyqt5

http://stackoverflow.com/a/51244266
has body: There are a few ways to pass data to a server. What you here describe are the GET [Django-doc] parameters. If you in a view inspect the request.GET object, you get a (possibly empty) QueryDict [Django-doc] object. It acts more or less as a dictionary (except that a key can contain multiple values, etc.). For example: def some_view(request): paymentId= request.GET['paymentId'] token = request.GET['token'] payerID = request.GET['PayerID'] # do some processing # ... pass Besides the GET parameters, there are other ways to transfer data between the client and server: the URL itself (this can contain some data); request.POST (those are parameters that are not encoded in the URL, but the header of the request); request.FILES those contain ways to upload files; request.COOKIES cookie data, send in the header, we can send cookies back to store some data during a session; and request.META this contains headers in the request.
upvote count: 3
has comment: http://stackoverflow.com/comment/89473274
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89473425
accepted answer of: http://stackoverflow.com/q/51244194
answers question: http://stackoverflow.com/q/51244194
type: Answer
score: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/89473125
has comment: http://stackoverflow.com/comment/89473367

http://stackoverflow.com/q/51187180
type: Question
upvote count: 0
tagged with: flask
tagged with: int
accepted answer: http://stackoverflow.com/a/51187219
answer count: 1
favorite count: 0
score: -1
tagged with: python
has title: unsupported operand type(s) for +: 'project' and 'int'
tagged with: object
type: AnsweredQuestion
has body: I have one column just ID, so I used this query to get the last record &gt;&gt;&gt;obj = project.query.order_by(project.id.desc()).first() Now I want to increment last record by one &gt;&gt;&gt;obj+1 I got this error: TypeError: unsupported operand type(s) for +: 'project' and 'int' btw,obj return this value: &lt;project 3&gt; how can return just 3 value as int?
has answer: http://stackoverflow.com/a/51187219
tagged with: orm
downvote count: 1

http://stackoverflow.com/comment/89575139
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51299087
has text: @abarnert I wouldn't. I was just wondering how a computer would.
score: 0

http://stackoverflow.com/q/51279846
tagged with: dna-sequence
upvote count: 4
answer count: 2
has comment: http://stackoverflow.com/comment/89538046
has comment: http://stackoverflow.com/comment/89578391
has answer: http://stackoverflow.com/a/51282841
downvote count: 0
has comment: http://stackoverflow.com/comment/89538360
has comment: http://stackoverflow.com/comment/89538873
favorite count: 0
has comment: http://stackoverflow.com/comment/89576648
has comment: http://stackoverflow.com/comment/89539667
tagged with: python
tagged with: regex
has title: Analyze tandem repeat motifs in DNA sequences
possible better answer: http://stackoverflow.com/a/51280758
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51282841
has answer: http://stackoverflow.com/a/51280758
type: Question
has body: Hy Py-guys :). Since I am new in the coding world and as well in Python, I don’t have much experience with coding and thus any help would be appreciated. I am working with short tandem repeats in DNA sequences and I would like to have a code that reads and counts the repeated nucleotides based on the tandem motif of specified loci. Here is an example what I need: tandem motif: AGAT,AGAC,[AGAT],gat,[AGAT] input: TTAGTTCAGGATAGTAGTTGTTTGGAAGCGCAACTCTCTGAGAAACTTAGTTATTCTCTCATCTATTTAGCTACAGCAAACTTCATGTGACAAAAGCCACACCCATAACTTTTTTCCTCTAGATAGACAGATAGATGATAGATAGATAGATAGATAGATAGATAGATAGATAGATAGATAGATAGATATAGATTCTCTTTCTCTGCATTCTCATCTATATTTCTGTCTTTCTCTTAATTATGGGTAACTCTTAGCCTGCCAGGCTACCATGGAAAGACAACCTTTAT analyzed input: TTAGTTCAGGATAGTAGTTGTTTGGAAGCGCAACTCTCTGAGAAACTTAGTTATTCTCTCATCTATTTAGCTACAGCAAACTTCATGTGACAAAAGCCACACCCATAACTTTTTTCCTCTAGATAGACAGATAGATGATAGATAGATAGATAGATAGATAGATAGATAGATAGATAGATAGATAGATATAGATTCTCTTTCTCTGCATTCTCATCTATATTTCTGTCTTTCTCTTAATTATGGGTAACTCTTAGCCTGCCAGGCTACCATGGAAAGACAACCTTTAT output: AGAT AGAC (AGAT)2 GAT (AGAT)12 number of copies. (In output GAT is in upper case even if it doesn’t count viz Description) allele: 16 total number of copies of each motif (1 + 1 + 2 + 12) Description That tandem motif is different for each locus so I need to manually specify it for one and every locus (about 130 loci in total). So in this case whole motif begins with AGAT and end with the last copy of AGAT There is no unknown nucleotide (A/C/T/G) between those specified in tandem motif and everything what is before and after this defined motif should be ignored As you can see, when in tandem motif there are nucleotides written in lower case (gat), they are not included in the final allele value Those motifs that are in brackets, these can repeat multiple times Those that are not in brackets – these have only one copy in the sequence There can also be this case: tandem motif: [CTAT],CTAA,[CTAT],N30,[TATC] input: TTTGCATGATCTCTTCTTGATCATTTTCTTCCCCCTTTCCTAAAAAATTCTGGTCCTTTG…
has comment: http://stackoverflow.com/comment/89539423
score: 4

http://stackoverflow.com/q/51233383
tagged with: python
tagged with: regex
answer count: 4
favorite count: 0
possible better answer: http://stackoverflow.com/a/51233413
has body: I have many of this type of url : http://www.example.com/some-text-to-get/jkl/another-text-to-get I want to be able to get this : ["some-text-to-get", "another-text-to-get"] I tried this : re.findall(".*([[a-z]*-[a-z]*]*).*", "http://www.example.com/some-text-to-get/jkl/another-text-to-get") but it's not working. Any idea ?
upvote count: 2
has answer: http://stackoverflow.com/a/51233413
downvote count: 1
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51233405
score: 1
has answer: http://stackoverflow.com/a/51233523
type: Question
has title: regex : get part of text from url data
has answer: http://stackoverflow.com/a/51233651
accepted answer: http://stackoverflow.com/a/51233405

http://stackoverflow.com/comment/89553751
type: Comment
comment on: http://stackoverflow.com/a/51287668
type: AnswerComment
has text: so this is happening because it check all the variables bounding, but most of the time, if the variable is not found before, it will be assumed as a new variable creation, so that nothing will go wrong. But in this case, the `nonlocal` is suggesting "Do not create a new variable, but to look for an existing one to bound", and that will cause the problem. Am I understanding this corretly?
score: 0

http://stackoverflow.com/comment/90341748
score: 0
type: AnswerComment
type: Comment
has text: @user3005684 Please double check that you did setup everything as in my example. I rechecked the example and it works as intended. If your trigger element is not opening modal, first check that the ''id'' of the trigger element matches the one you select with jquery selector in script. In my example the ''id'' of the trigger element for modal opening is createTest and jquery selector for this element that the modalForm is bound to is $(''#createTest'').
comment on: http://stackoverflow.com/a/51628396

http://stackoverflow.com/a/51270789
score: 0
has body: You could run a single query and get everything: cursDev.execute( 'SELECT columnName FROM tableName WHERE columnName IN ({})'.format( ','.join(':p{}'.format(n) for n in range(len(d))), {'p{}'.format(n): k for n, k in enumerate(d)} ) or run the updates directly - they do nothing if the row is not found: for k, v in d.items(): cursDev.execute( 'UPDATE tableName SET columnName = {} WHERE columnName = :value', {'value': v} ) Note that both examples are using parameterized queries - the data is being passed separated from the query and it is the job of the database to do the parameter interpolation - thus freeing you from quote hell and preventing injection automatically, besides performing better. The code uses :value named-style parameter placeholders because that is what cx_Oracle uses - see documentation on cx_Oracle.paramstyle.
type: Answer
answers question: http://stackoverflow.com/q/51269817

http://stackoverflow.com/q/51314292
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89605753
has title: Turn list elements in dataframe into columns pandas
tagged with: list
type: Question
has comment: http://stackoverflow.com/comment/89605713
has comment: http://stackoverflow.com/comment/89605284
score: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/89605893
has body: I have this little issue. I have a Dataframe with the following shape: id d 1 [1,2,3] 2 [4,5,6] And I want to turn it into this: id d v1 v2 v3 1 [1,2,3] 1 2 3 2 [4,5,6] 4 5 6 I tried this: for i in A['d']: A['v1']=i[0] A['v2']=i[1] A['v3']=i[2] But this gets me the following: id d v1 v2 v3 1 [1,2,3] 4 5 6 2 [4,5,6] 4 5 6 (It's pasting the elements of the last list in every row). I'm sure my error is little but I can't find it. What am I doing wrong? Thanks in advance!
answer count: 0

http://stackoverflow.com/a/51244800
score: 1
has body: IIRC the second argument to putrequest() should be the path part of the url (/ for the root). But you're making it much more complicated than it has to be - you could use conn.request(method, path, params, headers) as showed here, or (even better) just use python-requests actually (even the official httplib doc recommend it).
upvote count: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51244554
accepted answer of: http://stackoverflow.com/q/51244554
has comment: http://stackoverflow.com/comment/89493139
type: Answer
downvote count: 0

http://stackoverflow.com/q/51252009
has comment: http://stackoverflow.com/comment/89482978
accepted answer: http://stackoverflow.com/a/51255333
has comment: http://stackoverflow.com/comment/89485088
downvote count: 0
has comment: http://stackoverflow.com/comment/104411973
has comment: http://stackoverflow.com/comment/89482996
favorite count: 0
score: 5
tagged with: python
has comment: http://stackoverflow.com/comment/89483729
has comment: http://stackoverflow.com/comment/89483853
tagged with: vectorization
has comment: http://stackoverflow.com/comment/89532526
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89483445
has answer: http://stackoverflow.com/a/51255333
has body: I have two 2D numpy arrays, for example: A = numpy.array([[1, 2, 4, 8], [16, 32, 32, 8], [64, 32, 16, 8]]) and B = numpy.array([[1, 2], [32, 32]]) I want to have all lines from A where I can find all elements from any of the lines of B. Where there are 2 of the same element in a row of B, lines from A must contain at least 2 as well. In case of my example, I want to achieve this: A_filtered = [[1, 2, 4, 8], [16, 32, 32, 8]] I have control over the values representation so I chose numbers where the binary representation has only one place with 1 (example: 0b00000001 and 0b00000010, etc...) This way I can easily check if all type of values are in the row by using np.logical_or.reduce() function, but I cannot check that the number of the same elements are bigger or equal in a row of A. I was really hoping that I could avoid simple for loop and deep copies of the arrays as the performance is a very important aspect for me. How can I do that in numpy in an efficient way? Update: A solution from here may work, but I think the performance is a big concern for me, the A can be really big (>300000 rows) and B can be moderate (>30): [set(row).issuperset(hand) for row in A.tolist() for hand in B.tolist()] Update 2: The set() solution is not working since the set() drops all duplicated values.
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/89483353
answer count: 2
upvote count: 5
tagged with: arrays
possible better answer: http://stackoverflow.com/a/51253331
linked to: http://stackoverflow.com/q/16548560
has title: How to check if all elements of a numpy array are in another numpy array
has answer: http://stackoverflow.com/a/51253331

http://stackoverflow.com/a/51315135
answers question: http://stackoverflow.com/q/51314956
has body: I would use regular expressions for this, e.g. import re import os search_pattern = 'unmapped_{}_([\w]+)_([0-9\-]+)_([0-9\-]+).csv' data_types = ['trades', 'positions'] pattern_dict = {data_type: search_pattern.format(data_type) for data_type in data_types} def find_matching_files(search_dir, fund_codes): if not os.path.isdir(search_dir): raise ValueError('search_dir does not specify a directory') search_files = os.listdir(search_dir) matching_files = {data_type: [] for data_type in pattern_dict} for fname in search_files: for data_type, pattern in pattern_dict.items(): m = re.match(pattern, fname) if m is not None and m.group(1) in fund_codes: matching_files[data_type].append(fname) return matching_files print(find_matching_files('file_location/', ['PUSFF', 'AGE', 'AIR'])) where file_location/ is the directory to search, and a dictionary of the matching files separated into data types is returned
score: 0
type: Answer

http://stackoverflow.com/q/51184001
has title: Run html2text using parallel
tagged with: terminal
tagged with: linux
accepted answer: http://stackoverflow.com/a/51184104
type: Question
has comment: http://stackoverflow.com/comment/89350608
tagged with: http://stackoverflow.com/tag/html
possible better answer: http://stackoverflow.com/a/51192654
tagged with: python
tagged with: parallel-processing
has body: I am using html2text from Github in-which I was able to run-it on all the .html files in my folder using for file in *.html; do html2text "$file" &gt; "$file.txt"; done but it's some-what slow. How can I use html2text with parallel on all my .html files?
has comment: http://stackoverflow.com/comment/89349707
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/51184104
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51192654

http://stackoverflow.com/comment/89541137
comment on: http://stackoverflow.com/a/51281259
has text: Sorry revised the typo, but that was the one I searched
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/51294138
type: Answer
answers question: http://stackoverflow.com/q/51293999
has comment: http://stackoverflow.com/comment/89567101
has body: I solved my problem. Surprisingly you cant call a dictionary by a string=key as a dataframe column for instance. The key needs to be casted as an integer. So what I did was the following for i,key in enumerate(stocks): stocks[i]=aux_matrix
downvote count: 1
score: -1
upvote count: 0
has comment: http://stackoverflow.com/comment/89565825

http://stackoverflow.com/a/71273925
has body: If suppose you want to mock a function from module inside function in another module in python you can try this. # application2.py def app2_func(a): print(a) # application1.py import application2 def app1_func(a): application2.app2_func(a) # func to be mocked the test file to test the function # application_test.py import application1 def test_app1_func(mocker): app2_mocker = mocker.patch('application1.application2.app2_func') application1.app1_func('mock call') app2_mocker.assert_called_once() # to check if mocked function is called once
upvote count: 1
answers question: http://stackoverflow.com/q/51311935
type: Answer
downvote count: 0
score: 1

http://stackoverflow.com/q/51292058
type: AnsweredQuestion
tagged with: mysql
type: Question
has body: I get the data from a table from an mysql database. I'm trying to filter a list of dictionaries with a specific value. When I execute the code I get the following error: Using IDE = PyCharm. Error: [x.append(k) for k in lst_cmp_helpdesk_dic if "Doble" in k[key]] TypeError: argument of type 'int' is not iterable import mysql.connector def test_initialize_test_data(): global lst_cmp_helpdesk global lst_cmp_helpdesk_dic cnx = mysql.connector.connect(user='User', password='Password', host='Srv Name or IP', database='DataBase Name') try: cursor_dic = cnx.cursor(dictionary=True,buffered=True) cursor_dic.execute("select * from Table_Name") lst_cmp_helpdesk_dic = cursor_dic.fetchall() x = [] for key in lst_cmp_helpdesk_dic[0].keys(): [x.append(k)for k in lst_cmp_helpdesk_dic if "Search_Text" in k[key]] count = len(([dict(t) for t in set([tuple(d.items()) for d in x])])) print("\n Length = " + str(count)) finally: cnx.close()
has title: Error when trying to filter a list of dictionaries with a specific value i get error
accepted answer: http://stackoverflow.com/a/51292119
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/89561883
has comment: http://stackoverflow.com/comment/89561821
possible better answer: http://stackoverflow.com/a/51292666
tagged with: python
has answer: http://stackoverflow.com/a/51292666
has answer: http://stackoverflow.com/a/51292119

http://stackoverflow.com/comment/89596115
type: AnswerComment
type: Comment
score: 1
comment on: http://stackoverflow.com/a/51308415
has text: Thank you, moving the timer to child did the trick! Also to clarify - the button was added to test whether I can stop the timer from outside. The 5 second sleep was to exaggerate the GUI freezing as I hadn't noticed it with 100ms.

http://stackoverflow.com/q/51270197
tagged with: pip
has comment: http://stackoverflow.com/comment/89518533
tagged with: python
has answer: http://stackoverflow.com/a/51270920
linked to: http://stackoverflow.com/q/49940813
has title: Cannot upgrade awscli: no module named _internal and other errors
has body: When I try to upgrade awsli: pip install awscli --upgrade, I get the following error: Traceback (most recent call last): File "/usr/local/bin/pip", line 7, in &lt;module&gt; from pip._internal import main ImportError: No module named _internal Following the instructions on Stackoverflow: pip: no module named _internal Then I get the following errors: python2.7 get-pip.py --user --force-reinstall Collecting pip Using cached https://files.pythonhosted.org/packages/0f/74/ecd13431bcc456ed390b44c8a6e917c1820365cbebcb6a8974d1cd045ab4/pip-10.0.1-py2.py3-none-any.whl botocore 1.9.22 requires docutils&gt;=0.10, which is not installed. awscli 1.14.69 requires colorama&lt;=0.3.7,&gt;=0.2.5, which is not installed. awscli 1.14.69 requires docutils&gt;=0.10, which is not installed. awscli 1.14.69 requires rsa&lt;=3.5.0,&gt;=3.1.2, which is not installed. awscli 1.14.69 requires s3transfer&lt;0.2.0,&gt;=0.1.12, which is not installed. Installing collected packages: pip Could not install packages due to an EnvironmentError: [Errno 13] Permission denied: '/home/porter/.local/lib/python2.7' Check the permissions. You are using pip version 8.1.1, however version 10.0.1 is available. You should consider upgrading via the 'pip install --upgrade pip' command. So, all in all it is a great mess. I don't think that upgrading to pip version 10.0.1 will do any good. Edit: I found the culprit: /home/porter/.local/lib/python3.5. In this folder, there are the site-packages that pip is asking about: colorama, docutils, rsa, s3 etc. What to do now? awscli is installed at: /usr/local/lib/python2.7/dist-packages/awscli but its dependencies are installed at: /home/porter/.local/lib/python2.7/ so upgrading awscli, even after changing the permissions, doesn't work. Maybe it is better to deinstall awscli alltogether? But how?
type: Question
has answer: http://stackoverflow.com/a/51298256
score: 0
answer count: 2
type: UnansweredQuestion

http://stackoverflow.com/a/51290940
score: 1
accepted answer of: http://stackoverflow.com/q/51289874
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51289874
type: Answer
has body: To break a composition into pieces, use two fundamental properties of a SymPy expression: func (the "outer" function) and args (its arguments). expr = sin(cos(x)) print(expr.func, expr.args) # prints sin and (cos(x), ) print(expr.func(x)) # sin(x) print(expr.args[0]) # cos(x) By the way, the chain rule logic is in the internal _eval_derivative method of the Function class. This is where the evaluation of the derivative of f(g(x)) eventually leads. You were looking at the Polys class. The general dispatching of derivative of all kinds of objects is in Derivative.__new_.
upvote count: 1

http://stackoverflow.com/a/51282785
type: Answer
answers question: http://stackoverflow.com/q/51282670
has body: You might just want to use arguments and argparse instead of interactive input. import argparse import os def peip(filenames): for filename in filenames: realname = os.path.realpath(filename) basename = os.path.basename(filename) # to get the filename only print(filename, basename, realname) with open(realname) as f: if basename == 'something.log': pass # do things! if __name__ == '__main__': ap = argparse.ArgumentParser() ap.add_argument('files', metavar='file', nargs='*') args = ap.parse_args() if not args.files: ap.error('no files!') peip(args.files) And a random example... $ python3 so51282670.py ../Pictures/*.jpg ../Pictures/citd.jpg citd.jpg /Users/akx/Pictures/citd.jpg ../Pictures/citd2.jpg citd2.jpg /Users/akx/Pictures/citd2.jpg ../Pictures/Goodboy.jpg Goodboy.jpg /Users/akx/Pictures/Goodboy.jpg ../Pictures/Prairie.jpg Prairie.jpg /Users/akx/Pictures/Prairie.jpg
has comment: http://stackoverflow.com/comment/89552704
score: 0
has comment: http://stackoverflow.com/comment/89553034

http://stackoverflow.com/q/51273743
type: Question
has answer: http://stackoverflow.com/a/51291741
upvote count: 1
answer count: 1
favorite count: 0
tagged with: pandas
has title: data.plot.bar() Mixing up index labels
tagged with: python
has body: I have the below code to provide me a graph in a jupyter notebook, however it seems to be mislabeling the categories. When I make a change in the data to a cell in the node outage column that should be classified as a low traffic cell, it is changing the bar labeled mid traffic. looking at the data it seems to me assiging the correct user_category based on my cut points, so I can not see why it is affecting the mid traffic bar when I change a 0 to a 1 in the node outage column. Anyone have any ideas? PS this is my 1st question on the forums here so let me know if im not providing what is needed to assist. Thanks! (Data thats X'd out is due to being proprietary but should be irrelevant to the question here) train.head(10) site past_alarms weather_event max_users node_outage xxxxxx xxxxxxxxxxxxxxxx Thunderstorm 341 N xxxxxx xxxxxxxxxxxxxxxx Tornado 71 Y xxxxxx xxxxxxxxxxxxxxxx None 294 N xxxxxx None None 395 N xxxxxx None None 422 N xxxxxx None None 331 N xxxxxx None Tornado 260 N xxxxxx None None 79 N xxxxxx None None 240 N xxxxxx None None 370 N def process_users(df,cut_points,label_names): df["user_categories"] = pd.cut(df["max_users"],cut_points,labels=label_names) return df cut_points = [1, 100, 350, 550] label_names = ["Low_Traffic","Mid_Traffic","High_Traffic"] train = process_users(train,cut_points,label_names) users_cat_pivot = train.pivot_table(index="user_categories",values="node_outage") users_cat_pivot.plot.bar() plt.show() &lt;graph shown here&gt;
tagged with: jupyter
downvote count: 0
tagged with: pivot-table
type: UnansweredQuestion
tagged with: kaggle
score: 1

http://stackoverflow.com/comment/89605086
type: AnswerComment
type: Comment
score: 1
comment on: http://stackoverflow.com/a/51314164
has text: @E.Sommer: Yes, use `~`.

http://stackoverflow.com/q/51170741
has answer: http://stackoverflow.com/a/51170978
type: Question
upvote count: 2
has title: headers response without location
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/89324090
type: UnansweredQuestion
tagged with: python
score: 2
has body: I need information about location from Network Response. When I send post method I tried print body of response, and i get for example : {"_id":"12313124", "name":"NameElement", "address":"AddressStreet"} I need separate only id, because I need this to my tests (edit and delete). How I can do this ? My code: r = requests.post(*args) print(r.response) print(r.headers)
downvote count: 0
tagged with: http://stackoverflow.com/tag/json

http://stackoverflow.com/comment/89424406
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51221945
type: Comment
has text: Or saving an indentation level by separating the logic of opening the file and iterating over its content (as demonstrated in my answer), at the cost of storing the entire file in memory.

http://stackoverflow.com/a/51238439
score: 3
downvote count: 0
has body: Three options to get your xpath: XPATH= //*[@id='reportList']//*[contains(text(), 'example text')] If your text is with tr: XPATH= //*[@id='reportList']/tbody//tr[contains(text(), 'example text')] If your text with td: XPATH= //*[@id='reportList']/tbody//tr//td[contains(text(), 'example text')]
answers question: http://stackoverflow.com/q/51194590
has comment: http://stackoverflow.com/comment/120613130
upvote count: 3
type: Answer

http://stackoverflow.com/comment/89370730
type: AnswerComment
type: Comment
has text: I'm using 1.8.0
comment on: http://stackoverflow.com/a/51192719
score: 0

http://stackoverflow.com/q/51171892
has body: I have an example dataframe like this: import pandas as pd df = pd.DataFrame({"id": [0]*5 + [1]*5, "time": ['2015-01-01', '2015-01-03', '2015-01-04', '2015-01-08', '2015-01-10', '2015-02-02', '2015-02-04', '2015-02-06', '2015-02-11', '2015-02-13'], 'hit': [0,3,8,2,5, 6,12,0,7,3]}) df.time = df.time.astype('datetime64[ns]') df = df'id', 'time', 'hit' df Will output: id time hit 0 0 2015-01-01 0 1 0 2015-01-03 3 2 0 2015-01-04 8 3 0 2015-01-08 2 4 0 2015-01-10 5 5 1 2015-02-02 6 6 1 2015-02-04 12 7 1 2015-02-06 0 8 1 2015-02-11 7 9 1 2015-02-13 3 Then I performed a groupby with time (per day): df.groupby(['id', pd.Grouper(key='time', freq='1D')]).hit.sum().to_frame() Resulted in: hit id time 0 2015-01-01 0 2015-01-03 3 2015-01-04 8 2015-01-08 2 2015-01-10 5 1 2015-02-02 6 2015-02-04 12 2015-02-06 0 2015-02-11 7 2015-02-13 3 However, I want to retain the daily hit even though the value = 0, and calculate the daily hit since the first day, per each id. My desired output: hit day_since id time 0 2015-01-01 0 1 2015-01-02 0 2 2015-01-03 3 3 2015-01-04 8 4 2015-01-05 0 5 2015-01-06 0 6 2015-01-07 0 7 1 2015-02-02 6 1 2015-02-03 0 2 2015-02-04 12 3 2015-02-05 0 4 2015-02-06 0 5 2015-02-07 0 6 2015-02-08 0 7 A cumcount does not work because it is numbering each item by group. But in my case, I wish to calculate the sequential date difference per group. Does anyone have any ideas?
tagged with: dataframe
has comment: http://stackoverflow.com/comment/89340805
has answer: http://stackoverflow.com/a/51182140
linked to: http://stackoverflow.com/q/23435270
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/89340523
tagged with: pandas
type: AnsweredQuestion
has title: Pandas pd.Grouper and Sequential Date Difference per group
tagged with: python
accepted answer: http://stackoverflow.com/a/51182140
favorite count: 0
type: Question
upvote count: 1
answer count: 1

http://stackoverflow.com/a/62219947
upvote count: 1
answers question: http://stackoverflow.com/q/51227601
downvote count: 0
type: Answer
has body: To enhance Mike's response a little: def parsephone(strphone): ''' Pull out just the digits. Then do some simple formating. ''' phn = "" for n in strphone: if n in "0123456789": phn += n if len(phn) == 10: # add a 1 in front phn = "1" + phn if len(phn) != 11: return phn # no hope of formating # format with dashes phn = phn[:1] + "-" + phn[1:4] + "-" + phn[4:7] + "-" + phn[7:] return phn
score: 1

http://stackoverflow.com/q/51249360
has body: How can I add a new line after each object in my generator or list? I tried .join('\n') and that didn't work. Trying to split a newline won't work because that's not an attribute of the generator or list datatype. My try with a generator = false to use a list using join: a = conn.extend.standard.paged_search('cn = All.DL Div Controllers - National Group, ou = Distribution Lists, ou = Exchange, dc=google,dc=corpad,dc=net', '(objectClass=*)', attributes=['member'], generator=False) b = map(str, a) #Stringify each a from generator b_str = '\n'.join(b) #Join the list of b with a newline with open ('test.txt', 'w') as file: file.write(b_str) #Write to file My output looks like this aaaa, aaaaa, aaaaaa,aaa,aaaaa,aaaaa I want my output to look like this: aaaa, aaaaa, aaaaaa, aaa, aaaaa, aaaaa, Here is my attempt using .split(), but it obviously wont' work as .split() is not an attribute of a generator or list datatype. #a= conn.extend.standard.paged_search('cn = All.DL Div Controllers - National Group, ou = Distribution Lists, ou = Exchange, dc=google,dc=corpad,dc=net', '(objectClass=*)', attributes=['member']) #for b in a.split('\n'): # with open ('test.txt', 'w') as file: # file.write (str(a)) The above is just an example the true output in the console including each print statement is the following: Code: national = conn.extend.standard.paged_search('cn = All.DL Div Controllers - National Group, ou = Distribution Lists, ou = Exchange, dc=google,dc=corpad,dc=net', '(objectClass=*)', attributes=['member'], generator=False) print(national) Output: [{'raw_dn': b'CN=All.DL Div Controllers - National Group,OU=Distribution Lists,OU=Exchange,DC=google,DC=corpad,DC=net', 'dn': 'CN=All.DL Div Controllers - National Group,OU=Distribution Lists,OU=Exchange,DC=google,DC=corpad,DC=net', 'raw_attributes': {'member': [b'CN=gji9847,OU=U02562,OU=02562,DC=google,DC=corpad,DC=net', b'CN=exx8092,OU=U06032,OU=06032,DC=google,DC=corpad,DC=net', b'CN=EWR8386,OU=U09373,OU=09373,DC=google,DC=cor…
has comment: http://stackoverflow.com/comment/89516050
has comment: http://stackoverflow.com/comment/89481902
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89499921
has comment: http://stackoverflow.com/comment/89512846
tagged with: python
has comment: http://stackoverflow.com/comment/89512927
has title: Python Alternative to .split() for generator/list
type: Question
has comment: http://stackoverflow.com/comment/89487109
has comment: http://stackoverflow.com/comment/89478292
has answer: http://stackoverflow.com/a/51249597
has answer: http://stackoverflow.com/a/51249496
has comment: http://stackoverflow.com/comment/89478700
has comment: http://stackoverflow.com/comment/89541809
score: 0
has comment: http://stackoverflow.com/comment/89477933
answer count: 2
has comment: http://stackoverflow.com/comment/89516880
has comment: http://stackoverflow.com/comment/89482611
has comment: http://stackoverflow.com/comment/89477640

http://stackoverflow.com/comment/89602329
type: QuestionComment
has text: it *does* ad a single item, every time you are add **the same list**.
comment on: http://stackoverflow.com/q/51312766
score: 0
type: Comment

http://stackoverflow.com/q/51173728
has comment: http://stackoverflow.com/comment/89330712
upvote count: 3
tagged with: pyqt
downvote count: 1
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/89331811
tagged with: python
score: 2
type: AnsweredQuestion
has body: I have a GUI with many check boxes (in python). users should click many check boxes to run the application. I want to create a button that automatically select and "clicks" some predefined check boxes. I know how to create the button, and also have the application "know" the check box is checked. however, when looking at the GUI, the check boxes are left empty, so the user doesn't know which check box is checked. see below the check box definition: class Ui_Dialog(object): def setupUi(self, Dialog): QtCore.QObject.connect(self.legacyrunsens, QtCore.SIGNAL(_fromUtf8("stateChanged(int)")), legacychecksens) so, I call legacychecksens(2) , but on the GUI the checkbox is not marked.
has title: python how can i display a checkbox as checked in
has answer: http://stackoverflow.com/a/51174126
type: Question
accepted answer: http://stackoverflow.com/a/51174126
tagged with: pyqt4

http://stackoverflow.com/comment/89540803
type: Comment
has text: Furthermore, where do you call `item_add`? It looks like you call it without a `request` object...
type: QuestionComment
comment on: http://stackoverflow.com/q/51281714
score: 0

http://stackoverflow.com/q/51185172
has title: How to get the current frame in a live stream with python and opencv?
tagged with: python
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89352297
has body: I am doing some real-time Computer vision work, like a live stream detection. The part of detection takes about 0.3s / frame. But the video FPS is higher, maybe 15 or 30 FPS. So, In my work now, I use cap = cv2.VideoCapture("rtsp url") ret, frame = cap.read() to get the first frame, and then after detection process I'll get the new frame and detect. But the detection process took about 0.3s, So how do I get the current frame after I done the detection(0.3s)? Not the frame just after I had detected.
type: Question
tagged with: opencv
has comment: http://stackoverflow.com/comment/89355017
accepted answer: http://stackoverflow.com/a/51275551
upvote count: 2
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/51275551
favorite count: 0

http://stackoverflow.com/q/51210433
tagged with: logging
has comment: http://stackoverflow.com/comment/89402197
type: Question
has title: Python logging debug level wont go away
has body: I'm trying to disable DEBUG logging in Python 2.6.6 that appears to be triggered when running certain commands... and I've tried what appears to be every solution out there and I still keep getting the unwanted output. I even included: logging.disable(logging.CRITICAL) Same results... When I run the same command (test.cmd) via the cmd prompt, I get the expected output. When I run the same command via a python Script, using this code: p = Popen([test, "report"], stdin=PIPE, stdout=PIPE, stderr=STDOUT) output = p.stdout.read() print output I get the following (and it keeps going): 07/06/18 08:13:16 DEBUG : Enter: HTTPSender::invoke Enter: HTTPSender::invoke 07/06/18 08:13:16 DEBUG : XML sent: XML sent: 07/06/18 08:13:16 DEBUG : --------------------------------------------------- --------------------------------------------------- 07/06/18 08:13:16 DEBUG : POST /awstestservice/soap HTTP/1.0 Content-Type: text/xml; charset=utf-8 Accept: application/soap+xml, application/dime, multipart/related, text/* User-Agent: Axis/1.4 Host: localhost Cache-Control: no-cache Pragma: no-cache SOAPAction: "awstestReport" Content-Length: 327 Any ideas?
score: 0
has answer: http://stackoverflow.com/a/51212491
answer count: 1
has comment: http://stackoverflow.com/comment/89402067
has comment: http://stackoverflow.com/comment/89402960
has comment: http://stackoverflow.com/comment/89402475
type: UnansweredQuestion
tagged with: scripting
tagged with: python
has comment: http://stackoverflow.com/comment/89403020
has comment: http://stackoverflow.com/comment/89402366

http://stackoverflow.com/q/51318081
has comment: http://stackoverflow.com/comment/89612425
has title: numpy argmax when values are equal
downvote count: 0
answer count: 2
has answer: http://stackoverflow.com/a/51325662
has comment: http://stackoverflow.com/comment/89612315
has comment: http://stackoverflow.com/comment/89612022
favorite count: 0
has comment: http://stackoverflow.com/comment/89612337
has comment: http://stackoverflow.com/comment/89612380
possible better answer: http://stackoverflow.com/a/51341966
tagged with: python
has answer: http://stackoverflow.com/a/51341966
accepted answer: http://stackoverflow.com/a/51325662
type: AnsweredQuestion
score: 3
upvote count: 3
has body: I got a numpy matrix and I want to get the index of the maximum value in each row. E.g. [[1,2,3],[1,3,2],[3,2,1]] will return [0,1,2] However, when there're more than 1 maximum value in each row, numpy.argmax will only return the smallest index. E.g. [[0,0,0],[0,0,0],[0,0,0]] will return [0,0,0] Can I change the default (smallest index) to some other values? E.g. when there're equal maximum values, return 1 or None, so that the above result will be [1,1,1] or [None, None, None] If I can do this in TensorFlow that'll be better. Thanks!
has comment: http://stackoverflow.com/comment/89612293
type: Question
tagged with: numpy

matplotlib-venn
tag name: matplotlib-venn
tags question: http://stackoverflow.com/q/51246740
tags question: http://stackoverflow.com/q/51290472
type: Tag

http://stackoverflow.com/q/51313086
type: Question
has comment: http://stackoverflow.com/comment/89603780
tagged with: numpy
upvote count: 1
answer count: 1
has answer: http://stackoverflow.com/a/51326189
favorite count: 0
has title: Solving non-linear coupled differential equations in python
has comment: http://stackoverflow.com/comment/89603882
has body: I am working on simulation of a system that contains coupled differential equations. My main aim is to solve the mass balance in steady condition and feed the solution of steady state as initial guess for the dynamic simulation. There are basically three state variables Ss,Xs and Xbh. The rate equations look like this: r1=µH(Ss/(Ks+Ss))(So/(Koh+So))Xbh+Kh( (Xs⁄Xbh)/(Xs⁄Xbh+Kx))(So/(Koh+So))Xbh r2=(1-fp)bH*Xbh-Kh( (Xs⁄Xbh)/(Xs⁄Xbh+Kx))(So/(Koh+So))Xbh r3=µH(Ss/(Ks+Ss))(So/(Koh+So))Xbh-bH*Xbh And the main differential equations derived from mole balance for CSTR are: dSs/dt = Q(Ss_in-Ss)+r1*V dXs/dt= Q(Xs_in-Xs)+r2*V dXbh/dt= Q(Xbh_in-Xbh)+r2*V Here is my code till now: import numpy as np from scipy.optimize import fsolve parameter=dict() parameter['u_h']=6.0 parameter['k_oh']=0.20 parameter['k_s']=20.0 parameter['k_h']=3.0 parameter['k_x']=0.03 parameter['Y_h']=0.67 parameter['f_p']=0.08 parameter['b_h']=0.62 Bulk_DO=2.0 #mg/L #influent components: infcomp=[56.53,182.9,16.625] #mgCOD/l Q=684000 #L/hr V=1040000 #l def steady(z,*args): Ss=z[0] Xs=z[1] Xbh=z[2] def monod(My_S,My_K): return My_S/(My_S+My_K) #Conversion rates #Conversion of Ss r1=((-1/parameter['Y_h'])*parameter['u_h']*monod(Ss,parameter['k_s'])\ +parameter['k_h']*monod(Xs/Xbh,parameter['k_x'])*monod(Bulk_DO,parameter['k_oh']))\ *Xbh*monod(Bulk_DO,parameter['k_oh']) #Conversion of Xs r2=((1-parameter['f_p'])*parameter['b_h']-parameter['k_h']*monod(Xs/Xbh,parameter['k_x']))*Xbh #Conversion of Xbh r3=(parameter['u_h']*monod(Ss,parameter['k_s'])*monod(Bulk_DO,parameter['k_oh'])-parameter['b_h'])*Xbh f=np.zeros(3) f[0]=Q*(infcomp[0]-Ss)+r1*V f[1]=Q*(infcomp[1]-Xs)+r2*V f[2]=Q*(infcomp[2]-Xbh)+r3*V return f initial_guess=(0.1,0.1,0.1) soln=fsolve(steady,initial_guess,args=parameter) print (soln) How can I plot steady condition like this? steady state plot The solution is also not what I want since the equations implies reduction in Ss and Xs and increase of Xbh values with time. Also one solution has negative …
type: UnansweredQuestion
tagged with: python
tagged with: simulation
has comment: http://stackoverflow.com/comment/89603624
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/89630447
has comment: http://stackoverflow.com/comment/89604704
has comment: http://stackoverflow.com/comment/89626808
tagged with: scipy

http://stackoverflow.com/q/51200019
has answer: http://stackoverflow.com/a/51200088
answer count: 1
has body: I am using following code to run a function in using multiprocessing in python: The input is a queue of dictionary elements. import multiprocessing as mp from multiprocessing import Pool from multiprocessing import Process def get_bio(urllink): r=requests.get(urllink) data=r.text soup=BeautifulSoup(data,'html.parser') a=soup.body.get_text() return a q=Queue() #contains dictionary elements. Ex:{'abc':['google.com','w3.org']} for authr,urls in q.get().items(): for url in urls: processes = [mp.Process(target=get_bio,args=(url,))] for proc in processes: proc.start() for proc in processes: proc.join() the code prints the output only for the first dictionary element but do not continue to the next element in the queue. Can someone tell me where I am wrong? Is the snippet of code for multiprocessing correct?
downvote count: 0
favorite count: 0
type: UnansweredQuestion
has title: Multiprocessing in python using queue of dictionary elements as input
tagged with: python
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/89381897
type: Question
tagged with: multiprocessing

http://stackoverflow.com/q/51316245
tagged with: nan
favorite count: 0
type: UnansweredQuestion
tagged with: python
upvote count: 2
downvote count: 2
has title: Remove NaN from 2D numpy array
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/51316291
score: 0
tagged with: array-broadcasting
has body: For example, if I have the 2D array as follows. [[1,2,3,NAN], [4,5,NAN,NAN], [6,NAN,NAN,NAN] ] The desired result is [[1,2,3], [4,5], [6] ] How should I transform? I find using x = x[~numpy.isnan(x)] can only generate [1,2,3,4,5,6], which has been squeezed into one dimensional array. Thanks!
answer count: 1

http://stackoverflow.com/a/51323838
type: Answer
accepted answer of: http://stackoverflow.com/q/51323781
has body: I think better is use Series.value_counts with filtering: s = got['Name'].value_counts() got['Name'] = np.where(got['Name'].isin(s.index[s &gt;= 2000]), got['Name'], 'Other') Or: got['Name'] = np.where(got['Name'].isin(s.index[s &lt; 2000]), 'Other', got['Name']) Sample: df = pd.DataFrame({'Name': ['John', 'Daenerys', 'Cersei', 'Hound', 'Joffrey', 'LittleF'], 'Count': [90000, 50000, 45000, 2000, 1500, 1200]}) got = pd.DataFrame({'Name':np.repeat(df['Name'].values, df['Count'])}) #check sizes print (got.groupby('Name').size().sort_values(ascending=False)) Name John 90000 Daenerys 50000 Cersei 45000 Hound 2000 Joffrey 1500 LittleF 1200 dtype: int64 s = got['Name'].value_counts() got['Name'] = np.where(got['Name'].isin(s.index[s &gt;= 2000]), got['Name'], 'Other') #check sizes print (got.groupby('Name').size().sort_values(ascending=False)) Name John 90000 Daenerys 50000 Cersei 45000 Other 2700 Hound 2000 dtype: int64
answers question: http://stackoverflow.com/q/51323781
score: 5
has comment: http://stackoverflow.com/comment/89654709
upvote count: 5
has comment: http://stackoverflow.com/comment/89651802
has comment: http://stackoverflow.com/comment/89648335
has comment: http://stackoverflow.com/comment/89648355
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/89700717

http://stackoverflow.com/a/57271748
answers question: http://stackoverflow.com/q/51283245
has body: Expanding on Graham Polley's answer: You can set this by setting the time_partitioning property. Something like this: import google.cloud.bigquery as bq bq_client = bq.Client() dataset = bq_client.dataset('dataset_name') table = dataset.table('table_name') table = bq.Table(table, schema=[ bq.SchemaField('timestamp', 'TIMESTAMP', 'REQUIRED'), bq.SchemaField('col_name', 'STRING', 'REQUIRED')]) table.time_partitioning = bq.TimePartitioning(field='timestamp') bq_client.create_table(table)
downvote count: 0
type: Answer
upvote count: 2
score: 2

http://stackoverflow.com/q/51174809
score: 0
has comment: http://stackoverflow.com/comment/89332408
linked to: http://stackoverflow.com/q/24319662
has answer: http://stackoverflow.com/a/58438925
type: UnansweredQuestion
has title: Docker and host bridging
tagged with: python
has answer: http://stackoverflow.com/a/51175019
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/89336926
has body: How to bridge docker container and localhost service? My service inside docker container cant talk with mongidb server, running on host machine
tagged with: docker

http://stackoverflow.com/a/51172353
answers question: http://stackoverflow.com/q/51171966
score: 0
has body: Using a simple iteration. Demo: res = {} temp = [] with open(filename, "r") as infile: for line in infile: #Iterate over each line line = line.strip() if line.startswith("["): #Check if line is header line = line.strip("[]") res[line] = [] #Create Key temp.append(line) else: res[temp[-1]].append(line) #Append Values. print(res) Output: {'workers': ['2.3.45.5', '3.5.6.7', '5.7.8.9'], 'managers': ['1.2.3.4']}
type: Answer

http://stackoverflow.com/comment/99415102
score: 0
comment on: http://stackoverflow.com/q/51193138
type: Comment
type: QuestionComment
has text: Well in my case the client does not have access to the source code, so I don't have to worry about them modifying the methods in the models.

http://stackoverflow.com/comment/89336801
has text: cur.execute("""INSERT INTO test1 (bid, q_bid, ask, q_ask, gmt) VALUES ({},{},{},{},{})""".format(bid, best_bid_quantity, ask, best_ask_quantity, target_date))
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51176444

http://stackoverflow.com/a/52183460
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/51227403
downvote count: 0
has body: You can check if the database container is running locally by running: docker ps You should see a database container listed in the output: ... example_db_1 You can check if the correct database is available and contactable from the web container with: docker-compose run --rm web psql -h postgres -U postgres db
score: 1

http://stackoverflow.com/q/51193749
score: 0
has body: Set-up My WooCommerce shop has 3 different languages with French as the default language. I'm using the Python wrapper for the WooCommerce REST API. Code wcapi.get('products/?per_page=100').json() gets up to 100 products in the default language (French). wcapi.get('products/?lang=en').json() gets up to 10 products in the English language. Question How do I combine to two above commands, such that I get up to 100 products in the English language? Here WPML shows how to do this in PHP, how can I do this in the Python wrapper?
answer count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/89369419
has comment: http://stackoverflow.com/comment/89369298
tagged with: wordpress
tagged with: php
type: AnsweredQuestion
tagged with: woocommerce
has answer: http://stackoverflow.com/a/51206063
accepted answer: http://stackoverflow.com/a/51206063
type: Question
has title: How to get up to 100 products in other language (WPML) from WooCommerce using REST API (python wrapper)
has comment: http://stackoverflow.com/comment/89370728

lstm
tags question: http://stackoverflow.com/q/51291080
tags question: http://stackoverflow.com/q/51257204
tags question: http://stackoverflow.com/q/51223936
tags question: http://stackoverflow.com/q/51296140
tags question: http://stackoverflow.com/q/51199232
tag name: lstm
tags question: http://stackoverflow.com/q/51216036
tags question: http://stackoverflow.com/q/51285559
tags question: http://stackoverflow.com/q/51211816
tags question: http://stackoverflow.com/q/51254577
tags question: http://stackoverflow.com/q/51254772
tags question: http://stackoverflow.com/q/51236338
tags question: http://stackoverflow.com/q/51199753
type: Tag
tags question: http://stackoverflow.com/q/51281140
tags question: http://stackoverflow.com/q/51309643
tags question: http://stackoverflow.com/q/51173801

http://stackoverflow.com/q/51184089
accepted answer: http://stackoverflow.com/a/51184279
possible better answer: http://stackoverflow.com/a/51184142
has comment: http://stackoverflow.com/comment/89350177
has comment: http://stackoverflow.com/comment/89350038
has comment: http://stackoverflow.com/comment/89350021
type: AnsweredQuestion
has body: I have a log file with following content. I like to read Iteration value and detection_eval value I0704 18:10:31.097334 2421 solver.cpp:433] Iteration 200, Testing net (#0) I0704 18:10:31.149454 2421 net.cpp:693] Ignoring source layer mbox_loss I0704 18:10:40.241916 2421 solver.cpp:546] Test net output #0: detection_eval = 0.00273318 I did accuracy_pattern = r"Iteration (?P&lt;iter_num&gt;\d+), Testing net \(#0\)\n.* detection_eval = (?P&lt;accuracy&gt;[+-]?(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?)" But nothing is read, what is the issue? EDIT: Then I read accuracy_pattern to array as for r in re.findall(accuracy_pattern, log): iteration = int(r[0]) accuracy = float(r[1]) * 100 log has all file content and read as follow with open(log_file, 'r') as log_file2: log = log_file2.read()
has title: Reading log file in Python
type: Question
has comment: http://stackoverflow.com/comment/89350150
answer count: 2
has answer: http://stackoverflow.com/a/51184279
tagged with: python-2.7
score: 0
has answer: http://stackoverflow.com/a/51184142
has comment: http://stackoverflow.com/comment/89349993
tagged with: python
has comment: http://stackoverflow.com/comment/89349943

http://stackoverflow.com/comment/89488745
type: Comment
type: QuestionComment
score: 0
has text: Just asking, but you do know you can do `dict(some_Ordered_Dict...)` to get a dict version?
comment on: http://stackoverflow.com/q/51253056

http://stackoverflow.com/a/51397018
type: Answer
answers question: http://stackoverflow.com/q/51252054
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/51252054
has comment: http://stackoverflow.com/comment/89790633
type: AcceptedAnswer
downvote count: 0
has body: Lots of things here. To use a fabfile.py and run commands using fab, you have to make sure to decorate your commands with @task. Here's an example: --- in fabfile.py --- from fabric.decorators import task @task def greet(): print('Hello, Matt!') When you want to make changes to the fabric environment within the fabfile.py (i.e., at run-time in python code), you have to use the execute pattern from fabric.decorator import task from fabric.operations import run from fabric.context_managers import env def touch_file(): run("touch /home/pi/Desktop/new_file65.txt") @task def manage_pis(): env.hosts = [ ... ] execute(touch_file) That should be enough of a starting point to use the env.

http://stackoverflow.com/q/51285853
tagged with: apache
downvote count: 0
tagged with: ubuntu
tagged with: flask
favorite count: 0
has comment: http://stackoverflow.com/comment/89549964
tagged with: python
has body: When i start flask app without apache server i don't have any problems, but when in apache he log's that no module named request. Tried to find solve in stack-overflow, but nothing helps. Ubuntu 16.04 Apache site config: &lt;VirtualHost *&gt; ServerName s4lat.me WSGIScriptAlias / /var/www/flask/headlines/headlines.wsgi WSGIDaemonProcess headlines python-path=/var/www/flask/headline:/var/www/flask/env/lib/python3.6/site-packages &lt;Directory /var/www/flask/headlines&gt; WSGIProcessGroup headlines WSGIApplicationGroup %{GLOBAL} AllowOverride all Require all granted &lt;/Directory&gt; &lt;/VirtualHost&gt; Apache2server error log: [Wed Jul 11 12:26:29.301337 2018] [wsgi:error] [pid 17014] [remote 188.19.172.55:22332] mod_wsgi (pid=17014): Target WSGI script '/var/www/flask/headlines/headlines.wsgi' cannot be loaded as Python module. [Wed Jul 11 12:26:29.301373 2018] [wsgi:error] [pid 17014] [remote 188.19.172.55:22332] mod_wsgi (pid=17014): Exception occurred processing WSGI script '/var/www/flask/headlines/headlines.wsgi'. [Wed Jul 11 12:26:29.301402 2018] [wsgi:error] [pid 17014] [remote 188.19.172.55:22332] Traceback (most recent call last): [Wed Jul 11 12:26:29.301427 2018] [wsgi:error] [pid 17014] [remote 188.19.172.55:22332] File "/var/www/flask/headlines/headlines.wsgi", line 3, in &lt;module&gt; [Wed Jul 11 12:26:29.301470 2018] [wsgi:error] [pid 17014] [remote 188.19.172.55:22332] from headlines import app as application [Wed Jul 11 12:26:29.301481 2018] [wsgi:error] [pid 17014] [remote 188.19.172.55:22332] File "/var/www/flask/headlines/headlines.py", line 3, in &lt;module&gt; [Wed Jul 11 12:26:29.301493 2018] [wsgi:error] [pid 17014] [remote 188.19.172.55:22332] import feedparser [Wed Jul 11 12:26:29.301499 2018] [wsgi:error] [pid 17014] [remote 188.19.172.55:22332] File "/var/www/flask/env/lib/python3.6/site-packages/feedparser.py", line 142, in &lt;module&gt; [Wed Jul 11 12:26:29.301510 2018] [wsgi:error] [pid 17014] [remote 188.19.172.55:22332] import url…
answer count: 0
type: UnansweredQuestion
score: 1
tagged with: python-requests
has comment: http://stackoverflow.com/comment/89550041
type: Question
has title: Apache ImportError: no module named request (urllib.request)
has comment: http://stackoverflow.com/comment/89549724
upvote count: 1

pyqt4
tags question: http://stackoverflow.com/q/51294979
tags question: http://stackoverflow.com/q/51306500
tags question: http://stackoverflow.com/q/51220132
tags question: http://stackoverflow.com/q/51238046
tags question: http://stackoverflow.com/q/51189055
tags question: http://stackoverflow.com/q/51295808
type: Tag
tags question: http://stackoverflow.com/q/51237591
tags question: http://stackoverflow.com/q/51196705
tags question: http://stackoverflow.com/q/51215635
tags question: http://stackoverflow.com/q/51288948
tags question: http://stackoverflow.com/q/51175841
tags question: http://stackoverflow.com/q/51173728
tags question: http://stackoverflow.com/q/51306169
tags question: http://stackoverflow.com/q/51256657
tags question: http://stackoverflow.com/q/51169958
tags question: http://stackoverflow.com/q/51192287
tag name: pyqt4

http://stackoverflow.com/comment/89560904
has text: @DGMS89 did some more looking around and testing on my end. See my updated text.
type: AnswerComment
comment on: http://stackoverflow.com/a/51287475
type: Comment
score: 1

http://stackoverflow.com/comment/89384012
score: 0
has text: @Y.Henni I have added an answer providing an example of how to do this.
type: Comment
comment on: http://stackoverflow.com/q/51200805
type: QuestionComment

linux-mint
type: Tag
tags question: http://stackoverflow.com/q/51286170
tag name: linux-mint

http://stackoverflow.com/comment/89341362
comment on: http://stackoverflow.com/q/51179414
has text: The terminal? The output is firstly the loading function and then the game
score: 0
type: Comment
type: QuestionComment

web-services
type: Tag
tags question: http://stackoverflow.com/q/51205137
tag name: web-services

http://stackoverflow.com/comment/89617103
comment on: http://stackoverflow.com/a/51316113
type: AnswerComment
type: Comment
score: 0
has text: Hi Alexander, thanks for your answer. I did try what you are suggesting written in "Capturing output written by q to standard streams" from https://github.com/KxSystems/pyq/blob/master/src/ipy/Magic.ipynb . Sadly, it didn't do the trick. Best, Yael

http://stackoverflow.com/q/51232799
has answer: http://stackoverflow.com/a/51232917
accepted answer: http://stackoverflow.com/a/51232917
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89447918
downvote count: 0
has body: I'm able to get the numbers out of this string: string_p= 'seven 5 blah 6 decimal 6.5 thousands 8,999 with dollar signs $9,000 and $9,500,001.45 end ... lastly.... 8.4% now end with this code: import re def extractVal2(s,n): if n &gt; 0: return re.findall(r'[0-9$,.%]+\d*', s)[n-1] else: return re.findall(r'[0-9$,.%]+\d*', s)[n] for i in range(1,7): print extractVal2(string_n,i) but I can't do negative numbers with it. The negative numbers are the ones in the parenthesis. string_n= 'seven (5) blah (6) decimal (6.5) thousands (8,999) with dollar signs $(9,000) and $(9,500,001.45) end lastly.... (8.4)% now end' I have tried to first replace the () with a negative sign like so string_n= re.sub(r"\((\d*,?\d*)\)", r"-\1", string_n) then these to get the negative number r'[0-9$,.%-]+\d*', s)[n] r'[0-9$,.%]+-\d*', s)[n] r'[-0-9$,.%]+-\d*', s)[n] And even using a different approach: words = string_n.split(" ") for i in words: try: print -int(i.translate(None,"(),")) except: pass
type: Question
has comment: http://stackoverflow.com/comment/89444811
has comment: http://stackoverflow.com/comment/89444709
upvote count: 2
has comment: http://stackoverflow.com/comment/89445097
answer count: 1
favorite count: 0
tagged with: python
has title: Regex extracting negative numbers with unknown number format
tagged with: regex

http://stackoverflow.com/comment/137933576
has text: Just to add to this, for me the issue was coming and going away as I would reinstall package in question. I realised that Mac is adding -icloud extension to some files and for that reason library gets corrupt. So solution to this is to either exclude folder from being uploaded to iclous or to turn off checkmark for optimization (Optimize Mac Storage) in Icloud setting.
comment on: http://stackoverflow.com/a/66028280
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/89441361
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51231036
score: 1
has text: You probably have multiple versions of Python installed. Try `python3.6 -m pip list` and verify that `cherrypi` is in the list. If not, run `python3.6 -m pip install -r requirements.txt`

http://stackoverflow.com/q/51204336
tagged with: list
tagged with: ipython
has answer: http://stackoverflow.com/a/51204380
accepted answer: http://stackoverflow.com/a/51204380
type: Question
has comment: http://stackoverflow.com/comment/89389741
score: 0
answer count: 1
has body: I am trying to get list of column headers from a panda data frame. I also want to remove one unwanted element in the list. I tried below code, and that works. features_list = list(data_panda.columns.values) features_list.remove('email_address') features_list Output: produces the list But when I try to do that in single line as below, I get nothing as output. features_list_1 = list(data_panda.columns.values).remove('email_address') features_list_1 Output: Nothing Screenshot: Why? I am using Py2 environment in Anaconda.
has title: python list() removing entire list when nested with another operation in ipython notebook
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/q/51287098
has title: Make SqlAlchemy put join result in separate classes
has body: I have a condition in which I have joined a table with itself. For getting result rows I need to have two separate attributes in the result rows each of which contain model items. order_sq1: Order = self._query_from(Order). \ filter(Order.status == OrderStatus.REGISTERED.value, Order.dispatch_date + Order.dispatch_time &gt; current_time, Order.who_added_role != UserRole.SHIPPER.value).subquery('Order1') order_sq2: Order = self._query_from(Order). \ filter(Order.status == OrderStatus.REGISTERED.value, Order.dispatch_date + Order.dispatch_time &gt; current_time, Order.who_added_role != UserRole.SHIPPER.value).subquery('Order2') query = self._query_from(order_sq1).join( order_sq2, and_(order_sq1.c.tracking_code != order_sq2.c.tracking_code, func.ST_DistanceSphere(order_sq1.c.destination_location, order_sq2.c.source_location) &lt; 0.15 * order_sq1.c.distance , func.ST_DistanceSphere(order_sq2.c.destination_location, order_sq1.c.source_location) &lt; 0.15 * order_sq1.c.distance , between(((order_sq1.c.dispatch_date + order_sq1.c.dispatch_time) - (order_sq2.c.dispatch_date + order_sq2.c.dispatch_time) - (order_sq1.c.distance / 60) * timedelta(hours=1)), timedelta(hours=2), timedelta(hours=20)) , order_sq1.c.source_region_id != order_sq1.c.destination_region_id , order_sq2.c.source_region_id != order_sq2.c.destination_region_id , order_sq1.c.vehicle_type == order_sq2.c.vehicle_type )).add_columns(order_sq2) I need the result in the form of (Order1, Order2) fields, each as Order class. I tried many ways with no success!
answer count: 0
tagged with: orm
tagged with: sqlalchemy
type: Question
score: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89560122
has comment: http://stackoverflow.com/comment/89556186
tagged with: python

http://stackoverflow.com/a/51181859
has comment: http://stackoverflow.com/comment/96209298
type: Answer
score: -5
has body: If you want to install a specific wheel, you give pip the path or URL for that wheel: pip install https://example.com/url/of/wheel.whl
answers question: http://stackoverflow.com/q/51181840
has comment: http://stackoverflow.com/comment/104221527
has comment: http://stackoverflow.com/comment/104215161
has comment: http://stackoverflow.com/comment/96210849
downvote count: 6
upvote count: 1

http://stackoverflow.com/comment/89407351
has text: The expected output is one of the strings listed in the question. As for @Wiktor Stribiżew's question, yes, I would like the sentences to be grammatically correctly in the sense that the first letter should be capitalized.
score: 0
comment on: http://stackoverflow.com/q/51212853
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/89599496
has text: Do you need this to be persistent across runs? If so, have you considered using a key-value database (even a simple one like `dbm/shelve`) or a relational database (like `sqlite3`), possibly through a simple ORM (like SqlAlchemy)? A dbm is basically a hash table on disk, and a relational database is basically a bunch of b trees on disk.
comment on: http://stackoverflow.com/q/51311183
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89525208
type: AnswerComment
has text: When I print `test`, it outputs `1`. Shouldn't it output `1, 2, 3, 4, 5, 6`?
type: Comment
comment on: http://stackoverflow.com/a/51273500
score: 0

http://stackoverflow.com/comment/89367958
type: AnswerComment
has text: @JtenBulte: this list comprehension, I very much doubt it will be _any_ faster than the for loops (it's the same loops with a pretty face), but now it also takes much more memory (need to build and store all the urls at once).
type: Comment
comment on: http://stackoverflow.com/a/51191433
score: 0

http://stackoverflow.com/comment/89431383
comment on: http://stackoverflow.com/a/51224988
type: AnswerComment
has text: Wow, this solved everything. I have tried so many ways and read so many answers here on StackOverflow but your answer solved at least 5 days of struggling. Thank you very very much!
score: 0
type: Comment

http://stackoverflow.com/comment/89445226
has text: No, you should not because someone might get help from your approach If he tries using a parser.
type: AnswerComment
comment on: http://stackoverflow.com/a/51232861
score: 0
type: Comment

http://stackoverflow.com/comment/89606675
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51303110
has text: Certain characters have very similar or identical appearances but are encoded differently. There is a Latin, Cyrillic, and Greek versions of A - all three are encoded differently.
score: 0

http://stackoverflow.com/a/74796560
upvote count: 6
has body: The first argument taken by the url_for() function is the name of one of the (decorated) functions but it can also take additional arguments as described here Although this is not relevant to the OP, I had trouble making url_for() accept that first argument while using 'Blueprints' The solution with flask 'Blueprints' is that url_for() wants the name of the blueprint then the name of the function separated my a dot, ie return redirect(url_for('my_blueprint.my_function'))
has comment: http://stackoverflow.com/comment/133310086
type: Answer
downvote count: 0
score: 6
answers question: http://stackoverflow.com/q/51234212

http://stackoverflow.com/comment/89346025
has text: Change flask to listen on `0.0.0.0`, localhost/127.0.0.1 in container != localhost outside of container.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51181638

http://stackoverflow.com/q/51231755
tagged with: python-3.5
has comment: http://stackoverflow.com/comment/89442681
score: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/89442575
has title: How to import pandas for python3?
has answer: http://stackoverflow.com/a/53372378
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/70821227
has comment: http://stackoverflow.com/comment/89442660
tagged with: python
linked to: http://stackoverflow.com/q/14295680
has body: I have a python script that uses pandas library. But when I try to install pandas using: pip install pandas It says: Installing collected packages: pytz, six, python-dateutil, numpy, pandas Successfully installed numpy-1.14.5 pandas-0.23.3 python-dateutil-2.7.3 pytz-2018.5 six-1.11.0 You are using pip version 8.1.1, however version 10.0.1 is available. You should consider upgrading via the 'pip install --upgrade pip' command When I try to run my script again, it tells again that no module named pandas. Traceback (most recent call last): File "test.py", line 6, in &lt;module&gt; import pandas as pd ImportError: No module named 'pandas' After using the suggestion, I tried again pip install pandas but i get an error Traceback (most recent call last): File "/usr/bin/pip", line 9, in &lt;module&gt; from pip import main ImportError: cannot import name main
has comment: http://stackoverflow.com/comment/89442726
has comment: http://stackoverflow.com/comment/89442770
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/89443446

http://stackoverflow.com/q/51281208
tagged with: python
tagged with: annotate
has comment: http://stackoverflow.com/comment/89540924
type: AnsweredQuestion
tagged with: django
has comment: http://stackoverflow.com/comment/89540229
has title: django annotate related fields at once with Count()
has answer: http://stackoverflow.com/a/51282354
type: Question
score: 0
has comment: http://stackoverflow.com/comment/89540632
answer count: 1
has body: My Profile model have two m2m fields in one model - region and country. And as you know, country has there own region with foreignkey. I want to try counting profiles per region - not only include region but also in country__region. i.e.) If some have only has Africa region, and other has only Congo country (with the region Africa), I want to filter them at one. I try to solve it using annotate. I can find count of region individually like below profiles = Profile.objects.all() region_count = profiles.values('region').annotate(region_count=Count('region')) country_count = profiles.values('region').annotate(region_count=Count('country__region')) But how can I count queryset with specific region, filtering with region and region__country at once? Is there any possible method? Here's my profile / country model. The region model just has name field. class Profile(models.Model): region = models.ManyToManyField( Region, verbose_name="Region(s) of interest", blank=True, ) country = models.ManyToManyField( Country, related_name="country", verbose_name="Countries of interest", blank=True, ) ... class Country(models.Model): region = models.ForeignKey( Region, null=True, blank=True, ) ... Thanks for any help. Summary I want to count queryset with region and country__region at once with annotate.
accepted answer: http://stackoverflow.com/a/51282354
has comment: http://stackoverflow.com/comment/89540790

http://stackoverflow.com/comment/89597760
has text: You mean just skip the step of saving the data to a local file?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51305905

http://stackoverflow.com/comment/89452760
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51234440
has text: You're right, you cannot (currently) set the order directly, but implicitely, by providing the data in the correct order you are aiming at.

http://stackoverflow.com/comment/101216251
score: 0
comment on: http://stackoverflow.com/a/56919528
type: Comment
has text: Im using TF2. This seems to work better for me than the accepted answer.
type: AnswerComment

http://stackoverflow.com/a/51204026
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51203772
has body: Assuming that the decimal is the fraction of the year that has passed (and in the example given 1949.083 would then correspond to January 31, not Feb 1), you can do the following (this will work for leap years as well): import datetime fl = 1949.083 year = int(fl) days_in_year = (datetime.datetime(year=year+1, month=1, day=1) - datetime.datetime(year=year, month=1, day=1)).days days = int((fl - int(fl))*days_in_year) d = datetime.datetime(year=year, month=1, day=1) + datetime.timedelta(days=days)

http://stackoverflow.com/comment/89404082
has text: I honestly can't see why you'd want `cmp` over explicit comparison operators though. Surely you'll need to test the result of `cmp` to do anything useful with it anyway. If it's absolutely neccessary, use `cmp = lambda x, y: (x > y) - (x < y)`
type: QuestionComment
comment on: http://stackoverflow.com/q/51211437
type: Comment
score: 5

http://stackoverflow.com/q/51214103
tagged with: keras
favorite count: 0
has answer: http://stackoverflow.com/a/51214181
has answer: http://stackoverflow.com/a/51300262
type: UnansweredQuestion
has title: TensorFlow - expected global_average_pooling2d_1_input to have shape (1, 1, 2048) but got array with shape (7, 7, 2048)
upvote count: 1
tagged with: python
has body: I'm fairly new to TensorFlow and Image Classification, so I may be missing key knowledge and is probably why I'm facing this issue. I've built a ResNet50 model in TensorFlow for the purpose of image classification of Dog Breeds, using the ImageNet library and I have successfully trained a neural network which can detect various Dog Breeds. I'm now at the point in which I would like to pass a random image of a dog to my model for it to spit out an output on what it thinks the dog breed is. However, when I run this function, dog_breed_predictor("dogImages/dogImages/valid/016.Beagle/Beagle_01126.jpg"), I get the error expected global_average_pooling2d_1_input to have shape (1, 1, 2048) but got array with shape (7, 7, 2048) when it tries to execute the line Resnet50_model.predict(bottleneck_feature) and I don't know how to get around this. Here's the code. I've provided all that I feel is relevant to the problem. #import tensorflow as tf, etc. from sklearn.datasets import load_files np_utils = tf.keras.utils # define function to load train, test, and validation datasets def load_dataset(path): data = load_files(path) dog_files = np.array(data['filenames']) dog_targets = np_utils.to_categorical(np.array(data['target']), 133) return dog_files, dog_targets # load train, test, and validation datasets train_files, train_targets = load_dataset('dogImages/dogImages/train') valid_files, valid_targets = load_dataset('dogImages/dogImages/valid') test_files, test_targets = load_dataset('dogImages/dogImages/test') #define Resnet50 model Resnet50_model = ResNet50(weights="imagenet") def path_to_tensor(img_path): #loads RGB image as PIL.Image.Image type img = image.load_img(img_path, target_size=(224, 224)) #convert PIL.Image.Image type to 3D tensor with shape (224, 224, 3) x = image.img_to_array(img) #convert 3D tensor into 4D tensor with shape (1, 224, 224, 3) return np.expand_dims(x, axis=0) from keras.applications.resnet50 import preprocess_input, decode_predictions def ResNet50_…
score: 1
tagged with: tensorflow
type: Question
answer count: 2
downvote count: 0

http://stackoverflow.com/comment/89457784
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51214136
has text: I found the solution, Thanks for your answer,

http://stackoverflow.com/q/51228131
score: 1
accepted answer: http://stackoverflow.com/a/51228861
answer count: 2
linked to: http://stackoverflow.com/q/33810990
downvote count: 0
favorite count: 0
has title: Model inference running time increases after repeated inferences
tagged with: python
has body: I am coding a tensorflow project in which I am editing each weight and bias manually so I set up the weights and biases like in old tensorflow with dictionaries rather then using tf.layers.dense and letting tensorflow take care of updating weights. (This is the cleanest way I came up with although it might not be ideal) I feed a fixed model the same data in each iteration, but the running time increases throughout program execution. I cut out almost everything from my code so I can see where the issue lies but I cannot understand what is causing the increase in running time. ---Games took 2.6591222286224365 seconds --- ---Games took 3.290001153945923 seconds --- ---Games took 4.250034332275391 seconds --- ---Games took 5.190149307250977 seconds --- Edit: I have managed to reduce the running time by using a placeholder that doesn't add additional nodes to the graph but the running time still increases as a slower rate. I'd like to remove this running time growth. (It goes from 0.1 to over 1 second after a while) Here is my whole code: import numpy as np import tensorflow as tf import time n_inputs = 9 n_class = 9 n_hidden_1 = 20 population_size = 10 weights = [] biases = [] game_steps = 20 #so we can see performance loss faster # 2 games per individual games_in_generation = population_size/2 def generate_initial_population(my_population_size): my_weights = [] my_biases = [] for key in range(my_population_size): layer_weights = { 'h1': tf.Variable(tf.truncated_normal([n_inputs, n_hidden_1], seed=key)), 'out': tf.Variable(tf.truncated_normal([n_hidden_1, n_class], seed=key)) } layer_biases = { 'b1': tf.Variable(tf.truncated_normal([n_hidden_1], seed=key)), 'out': tf.Variable(tf.truncated_normal([n_class], seed=key)) } my_weights.append(layer_weights) my_biases.append(layer_biases) return my_weights, my_biases weights, biases = generate_initial_population(population_size) data = tf.placeholder(dtype=tf.float32) #will add shape later def model(x): out_layer = tf.add(tf.m…
possible better answer: http://stackoverflow.com/a/51228411
has answer: http://stackoverflow.com/a/51228411
upvote count: 1
tagged with: tensorflow
type: Question
has answer: http://stackoverflow.com/a/51228861
type: AnsweredQuestion
tagged with: performance

http://stackoverflow.com/a/51167996
score: 1
answers question: http://stackoverflow.com/q/51167811
upvote count: 1
has body: I think that values of entities found key are tuples, therefore you can't update single value of tuple. You have to either change tuple to list, or update tuple with another tuple. data['entities_found'][0] = ('loc', data['entities_found'][0][1]) data['entities_found'][1] = ('period', data['entities_found'][1][1]) ^ This is second way described above.
downvote count: 0
type: Answer

http://stackoverflow.com/q/51232019
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/89443441
tagged with: numpy-ndarray
answer count: 2
has body: I have three arrays of shapes: A = a = np.random.exponential(1, [10, 1000000]) # of shape (10, 1000000) B = a = np.random.exponential(1, [10, 1000000]) # of shape (10, 1000000) I computed another array IND[ ] as below. Each element of IND[ ] is index of the maximum element of A (maximum of each 10 values in a column) , IND = np.argmax(snr_sr, axis=0) # of shape (1000000,) I want to calculate another array C, which contains the element-wise minimum values of A and B at row# specified by values of IND[ ]. Thus the C array should be of the shape (1, 1000000). I want to avoid for loops. I tried the below, but the values of C are not correct. for j in range(0, A.shape[1]): m = ind[j] C = minimum(A[m,:], B[m,:]) # return 1x1000000 array Sorry, as the arrays are large, could not post it. You can take any arrays of the same shapes. First Edit: Somebody provided me with the right answer, but he deleted it (don't know why?) Anyhow, I copied the answer before he deleted it. Please post it again so that I can mark it correct. (To him: Who took arrays of 1,100 for simplicity).
has title: Element-wise minimum of two numpy arrays indexed by another array
has answer: http://stackoverflow.com/a/51232231
score: 0
tagged with: array-broadcasting
upvote count: 1
has answer: http://stackoverflow.com/a/51232248
accepted answer: http://stackoverflow.com/a/51232248
downvote count: 1
has comment: http://stackoverflow.com/comment/89443331
has comment: http://stackoverflow.com/comment/89443384
favorite count: 0
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/51232231
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/122447170
has text: This is a terrible answer, which results in `AttributeError: 'DataFrame' object has no attribute 'plt'`. `pandas` imports `matplotlib` as a dependency, and the correct way to use `pandas.DataFrame.plot` to adjust `figsize` is shown in the [accepted answer](https://stackoverflow.com/a/51174822/7758804). `kind='line'` is not required, because it is the default. As the answer is blatantly incorrect, the fact it has any upvotes undermines the credibility of voting system. The correct import is `import matplotlib.pyplot as plt` as shown in the matplotlib Usage Guide.
score: 6
comment on: http://stackoverflow.com/a/64450048
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/89454883
type: Comment
type: QuestionComment
has text: Have you confirmed if the same issue exists in the latest release (2.8.0)?
comment on: http://stackoverflow.com/q/51237804
score: 1

http://stackoverflow.com/comment/89529894
type: QuestionComment
has text: Thanks a lot Till, looks like a very stupid questions i was asking, I wasnt familiar with classmethod
comment on: http://stackoverflow.com/q/51263233
score: 0
type: Comment

http://stackoverflow.com/q/51298670
has body: I am trying to develop a process that automatically scales each Series in a pandas df to zero. For instance, if we use the df below: import pandas as pd d = ({ 'A' : [0,1,2,3], 'B' : [6,7,8,9], 'C' : [10,11,12,13], 'D' : [-4,-5,-4,-3], }) df = pd.DataFrame(data=d) I'm manually adjusting each Column so it begins at zero. You'll notice the increments are either +1 or -1 but the starting integers vary. df['B'] = df['B'] - 6 df['C'] = df['C'] - 10 df['D'] = df['D'] + 4 Output: A B C D 0 0 0 0 0 1 1 1 1 -1 2 2 2 2 -2 3 3 3 3 -3 This isn't very efficient as I have to go through each series to determine the scaling factor. Is there a more efficient way to determine this?
type: AnsweredQuestion
score: 1
type: Question
has answer: http://stackoverflow.com/a/51298696
downvote count: 0
answer count: 1
favorite count: 0
has title: Efficiently scale df columns to zero
tagged with: pandas
tagged with: python
accepted answer: http://stackoverflow.com/a/51298696
upvote count: 1

http://stackoverflow.com/q/51279973
type: UnansweredQuestion
downvote count: 2
has comment: http://stackoverflow.com/comment/89537794
has title: Python: Create structured numpy structured array from two columns in a DataFrame
tagged with: python
has answer: http://stackoverflow.com/a/51280005
upvote count: 10
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/51280303
score: 8
tagged with: arrays
tagged with: dataframe
has answer: http://stackoverflow.com/a/51280608
has comment: http://stackoverflow.com/comment/89537684
answer count: 3
linked to: http://stackoverflow.com/q/27995110
tagged with: pandas
has body: How do you create a structured array from two columns in a DataFrame? I tried this: df = pd.DataFrame(data=[[1,2],[10,20]], columns=['a','b']) df a b 0 1 2 1 10 20 x = np.array([([val for val in list(df['a'])], [val for val in list(df['b'])])]) But this gives me this: array([[[ 1, 10], [ 2, 20]]]) But I wanted this: [(1,2),(10,20)] Thanks!
favorite count: 0

http://stackoverflow.com/a/51319876
downvote count: 0
has body: pip3 -m venv yourprojectname Are you trying my command. I got the error like you did with this command I got the problem but, you can apply the following commands py -m pip install --user virtualenv py -m virtualenv env OR python3 -m pip install --user virtualenv python3 -m virtualenv env
type: Answer
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/51319189

http://stackoverflow.com/q/51260992
tagged with: python
tagged with: node.js
favorite count: 0
answer count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: machine-learning
tagged with: tensorflow
score: 1
has body: I am having ML code written in Python. I want to use child_process in Node JS and leverage Python's Machine Learning capabilities for predictions. I used NUMPY, Pandas, Tensorflow, Scipy python libraries. My question is, if I want to run this using NODE, where and how I will load python libraries.
type: Question
tagged with: numpy
downvote count: 0
has title: How to consume python machine learning libraries like Numpy, Scipy, Pandas, Tensorflow through Node JS

http://stackoverflow.com/comment/89514237
score: 2
comment on: http://stackoverflow.com/q/51267858
type: Comment
type: QuestionComment
has text: Perhaps, `print(f)`?

http://stackoverflow.com/a/51182555
has body: yes its possible: import matplotlib.pyplot as plt for k in range(len(b)): plt.plot(a, b) plt.ylabel(r'$\sqrt{| R(a, {%s}) |}$' % k) plt.show() output
type: Answer
has comment: http://stackoverflow.com/comment/89347309
score: 0
answers question: http://stackoverflow.com/q/51182464

http://stackoverflow.com/comment/89558272
has text: Did you try reading any Python resources before posting your question?
type: Comment
score: 2
comment on: http://stackoverflow.com/q/51289838
type: QuestionComment

http://stackoverflow.com/q/51227351
score: -2
possible better answer: http://stackoverflow.com/a/51227367
tagged with: mysql
duplicate of: http://stackoverflow.com/q/902408
has body: Edit => Problem resolve : I changed my query to this and now it's working thank you yall: query_update = ("UPDATE comments SET label = '%s' WHERE id = %s"%(new_label, id)) I'm working on a school project to update a mysql database thru a form in a flask app. While I run my query updating a column to an integer it works, but when my query is a string it doesn't. I only know a little about mysql and even less about mysql workench. Thanking in advance. Here is my code : cur_update = cnx.cursor(buffered=True) #working query_update = ("UPDATE comments SET label = %s WHERE id = %s"%(1, id)) #working query_update = ("UPDATE comments SET label = %s WHERE id = %s"%("1", id)) #not working query_update = ("UPDATE comments SET label = %s WHERE id = %s"%("test", id)) #returing the following error mysql.connector.errors.ProgrammingError: 1054 (42S22): Unknown column 'test' in 'field list' cur_update.execute(query_update) cnx.commit() cur_update.close() cnx.close() I tried several datatype for the concern column but every one of them return the same error.
has comment: http://stackoverflow.com/comment/89434717
has answer: http://stackoverflow.com/a/51227376
answer count: 2
linked to: http://stackoverflow.com/q/775296
upvote count: 1
tagged with: flask
favorite count: 0
downvote count: 3
linked to: http://stackoverflow.com/q/902408
has answer: http://stackoverflow.com/a/51227367
tagged with: python
type: AnsweredQuestion
tagged with: mysql-workbench
duplicate of: http://stackoverflow.com/q/775296
has comment: http://stackoverflow.com/comment/89434701
has title: While I'm able to update my mysql database to an int but I can't input a string
type: Question
accepted answer: http://stackoverflow.com/a/51227376

http://stackoverflow.com/comment/89450114
comment on: http://stackoverflow.com/a/51228612
type: AnswerComment
score: 0
has text: OK, and will I have to create the links after creating the edge class? e.g. client.command("create property Own.out LINK Customer") client.command("create property Own.in LINK Account") Is this correct in your case?
type: Comment

http://stackoverflow.com/q/51281729
upvote count: 0
has comment: http://stackoverflow.com/comment/89541771
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89541480
score: -1
favorite count: 0
type: Question
has title: python to search separated words
tagged with: python
tagged with: regex
answer count: 1
has comment: http://stackoverflow.com/comment/89541596
has comment: http://stackoverflow.com/comment/89541387
has answer: http://stackoverflow.com/a/51283153
has body: I am trying to extract separated multi words from a python list with two different list as a query string. My sentences list is lst = ['we have the terrible HIV epidemic that takes down the life expectancy of the African ','and I take the regions down here','The poorest are down'] lst_verb = ['take','go','wake'] lst_prep = ['down','up','in'] import re output=[] item = 'down' p = re.compile(r'(?:\w+\s+){1,20}'+item) for i in lst: output.append(p.findall(i)) for item in output: print(item) with this i am able to extract word from the list, However I am only want to extract separated multiwords, i.e it should extract the word from the list "and I take the regions down here". furthermore, I want to use the word from lst_verb and lst_prep as query string. for example re.findall(r \lst_verb+'*.\b'+ \lst_prep) Thank you for your answer.
has comment: http://stackoverflow.com/comment/89542032
downvote count: 1

http://stackoverflow.com/q/51311305
has title: Hi, I am doing a RGB image using python for GOES16 Air Mass product, I extract the information for the range of interest like this
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/89599350
tagged with: python
has body: I am doing a RGB image using python for GOES16 Air Mass product, I extract the information for the range of interest like this: RED[RED &lt; -26.2] = -26.2 RED[RED &gt; 0.6] = 0.6 GREEN[GREEN &lt; -43.2] = -43.2 GREEN[GREEN &gt; 6.7] = 6.7 BLUE[BLUE &lt; 243.9] = 243.9 BLUE[BLUE &gt; 208.5] = 208.5 And makes the RGB: RGB = np.zeros((5424,5424,3)) RGB[:,:,0] = (RED-np.min(RED))/(np.max(RED)-np.min(RED)) RGB[:,:,1] = (GREEN-np.min(GREEN))/(np.max(GREEN)-np.min(GREEN)) RGB[:,:,2] = (BLUE-np.min(BLUE))/(np.max(BLUE)-np.min(BLUE)) I think it's ok because it works in the generation of other products, like S02 or Volcanic Ash. The problem is that I am getting a yellowish image (like there is no contribution for the blue color), and I don't know what is wrong.
favorite count: 0
score: 2
upvote count: 2
has answer: http://stackoverflow.com/a/51311942
accepted answer: http://stackoverflow.com/a/51311942
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89599835
tagged with: satellite
has comment: http://stackoverflow.com/comment/89600409
tagged with: rgb
tagged with: image
type: Question

http://stackoverflow.com/q/51315123
has comment: http://stackoverflow.com/comment/89607308
type: UnansweredQuestion
score: 1
tagged with: multithreading
has comment: http://stackoverflow.com/comment/89607484
has comment: http://stackoverflow.com/comment/89607065
type: Question
has comment: http://stackoverflow.com/comment/89606822
has comment: http://stackoverflow.com/comment/89607015
tagged with: performance
has comment: http://stackoverflow.com/comment/89607072
has comment: http://stackoverflow.com/comment/89607599
tagged with: disk
has comment: http://stackoverflow.com/comment/89607301
has comment: http://stackoverflow.com/comment/89607237
has title: Python disk writing speed different on two computers
upvote count: 1
has comment: http://stackoverflow.com/comment/89607271
favorite count: 0
has body: I am trying to run a python script to take data from an input .csv file and print it to an output .csv file, using an ID and column headers to cross reference. They are very large files so I've included multiprocessing and the first step is to split the output file into parts so they can be processed in parallel. I tried executing this on Computer A and the disk speed to split up the output file is 0 mb/s (or a very slow trickle) and the program never get executed. Meanwhile on Computer B the program runs correctly and the disk speed splits the output file into parts at a rate of ~40mb/s. It is the same exact files and the same exact code, why is Computer A not responding properly? Is it an operating system error? Am I missing a driver on Computer A? Something else? The input and output files are located on the WD 4TB external HDD. Computer A specs: Windows 10 Pro 64-bit, Intel i9 7920X 12-core, 8 x 8GB Geil Evo Potenza RAM, Samsung 850 Evo 500GB local SSD, WD 4TB external HDD, ASRock X299 Killer motherboard Copmuter B specs: Windows 10 Pro 64-bit, Intel i7 6700K 4-core, 2 x 16GB Geil Evo Forza RAM, PNY CS1311 240GB SSD, WD 4TB external HDD, MSI B250M Gaming Pro motherboard # std lib imports import csv import multiprocessing import os import os.path import shutil import sqlite3 import sys import tempfile import timeit # third party imports # our imports buffer_size = 8192000 # 8.192 MB, 10x the default (io.DEFAULT_BUFFER_SiZE) # working_dir = tempfile.gettempdir() working_dir = "E:\\temp_files" def return_csv_header(filename): """ Returns the first column of the csv file filename as a list. """ with open(filename, "r", newline="", encoding="utf-8") as csvfile: reader = csv.reader(csvfile) return next(reader) def return_input_mapping(input_file, identifier): """ Returns a {identifier:record} dictionary where identifier is the value of the identifier column for each row in the input file. record is a dictionary of {column:value} representing a row in a csv file. """ t…
has comment: http://stackoverflow.com/comment/89607478
has comment: http://stackoverflow.com/comment/89607467
tagged with: python
has comment: http://stackoverflow.com/comment/89608059
answer count: 0
downvote count: 0

http://stackoverflow.com/q/51275717
answer count: 4
has comment: http://stackoverflow.com/comment/89529522
score: 1
has comment: http://stackoverflow.com/comment/89529364
type: Question
has title: How to run a function inside of an if-statement in Python
has answer: http://stackoverflow.com/a/51275902
upvote count: 3
downvote count: 2
has comment: http://stackoverflow.com/comment/89529560
has body: I am trying to add variable information from an input to a text document. The document is in the place it should be. I have this code so far: import time import os print("Welcome!") name = input("Please enter your name: ") print("Hello",name, "! I am going to guess your most favorite type of music.") time.sleep(2) print("Please, choose from one of the following: ") listening_time = ["1 - One hour a day", "2 - About two hours per day", "3 - three to four hours per day", "4 - Most of the day"] print(listening_time) how_often = int(input("I find myself listening to music...")) def add_file_1(new_1): f = open("music.txt", "a") f.write("1 Hour") def add_file_2(new_2): f = open("music.txt", "a") f.write("2 Hours") def add_file_3(new_3): f = open("music.txt", "a") f.write("3 - 4 Hours") def add_file_4(new_4): f = open("music.txt", "a") f.write("Most of the day") if how_often == str('1'): add_file_1(new_1) elif how_often == str('2'): add_file_2(new_2) elif how_often == str('3'): add_file_3(new_3) else: add_file_4(new_4)
has answer: http://stackoverflow.com/a/51275968
has answer: http://stackoverflow.com/a/51276009
has comment: http://stackoverflow.com/comment/89529597
favorite count: 0
linked to: http://stackoverflow.com/q/6159900
has comment: http://stackoverflow.com/comment/89529540
has answer: http://stackoverflow.com/a/51275780
has comment: http://stackoverflow.com/comment/89529609
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89529356
tagged with: python

http://stackoverflow.com/a/51270565
type: Answer
score: 4
upvote count: 4
answers question: http://stackoverflow.com/q/51248813
has comment: http://stackoverflow.com/comment/89526015
type: AcceptedAnswer
downvote count: 0
has body: Usually this error fires up when some stateful operation in tensorflow is never passed to session.run or used as a control dependency, which means some updates will get silently dropped leading to wrong behavior. That said, try upgrading to see if the fault is some internal library and not your code.
accepted answer of: http://stackoverflow.com/q/51248813

http://stackoverflow.com/q/51244360
has answer: http://stackoverflow.com/a/51262718
has comment: http://stackoverflow.com/comment/89467404
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89472750
type: Question
upvote count: 4
tagged with: server
has comment: http://stackoverflow.com/comment/89467246
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/51262718
score: 4
has title: Run python script as a service on Windows with an interface
favorite count: 0
has body: I have a problem where I think that I already have a solution. The only thing I need to know is a bit of knowledge and a rough direction how to do it. My problem: A script is running via PyCharm on a server. When the server is rebooting, because of updates or something similar, I need to restart PyCharm and start the script. I don't get any information that the process has stopped. Moreover without logon via remote desktop and starting PyCharm, the script would not be up again. Solution: Start the script as a service and write another script that checks if the process is running. trains of thought My problem is, that by running the script as a service I will loose my IDE (my interface that I have with PyCharm). The way I interact with the script is then moved to my two logging files. How will I know if the script is still running? What will happen if an error occurs, that is not handled by my logging setup. What if an exception raises? Will it be printed to the logfile? It's hard for me to disengage from an interface and do everything in a console. I am then dependent on the log files. That's pretty new to me. I think that if I start the script as a service, that it becomes a blackbox. Notes: I read this guide here, how I can set up a windows service and I set up my logging. How can I run my script as a service without loosing information?
linked to: http://stackoverflow.com/q/4438020
tagged with: pycharm
tagged with: python

instance-variables
tags question: http://stackoverflow.com/q/51196405
tag name: instance-variables
type: Tag

http://stackoverflow.com/comment/89499785
score: 0
type: Comment
type: QuestionComment
has text: I tried restarting pyCharm but the problem persists. But I've also noticed that PyCharm sometimes shows false unresolved imports. I'll try ignoring and see if it works.
comment on: http://stackoverflow.com/q/51260177

http://stackoverflow.com/q/51309176
answer count: 0
score: 1
upvote count: 1
tagged with: scipy
type: Question
has comment: http://stackoverflow.com/comment/89595096
has title: scipy.integrate.quad Missing Arguments
tagged with: numerical-integration
has body: I know this sounds like I just need to input an 'a' and 'b' but as far as I can tell, my syntax looks correct. When hovering over the integrate.quad, PyCharm is telling me "Expected type 'float', got 'Tuple[float, float, dict, Any, Any]' instead." When I run the code, it gives me a type error: "quad() missing 2 required positional arguments: 'a' and 'b'." Here's my code: t0 = 1. pt = 20. p0 = .00002 pressRef = (pt**2)/(p0**2) SEL = 10*log10((1./t0)*integrate.quad((pressRef, -inf, inf))) print(SEL[0]) This is my first time writing an SEL function for Digital Signal Processing so, admittedly, I'm fairly new to integration in python.
downvote count: 0
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89634256
type: UnansweredQuestion
tagged with: quad
tagged with: python
has comment: http://stackoverflow.com/comment/89595576

pose-estimation
tag name: pose-estimation
tags question: http://stackoverflow.com/q/51234114
type: Tag

http://stackoverflow.com/comment/89521343
comment on: http://stackoverflow.com/q/51268504
has text: If you were to use two inputs simultaneously into a stative=True RNN, it would not be able to properly keep track of the sequence, the states would be messed up. You should have two separate layers for two inputs so their states don't get mixed.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51205194
upvote count: 0
score: -4
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/23294658
has comment: http://stackoverflow.com/comment/89391477
tagged with: python
has comment: http://stackoverflow.com/comment/89391391
has comment: http://stackoverflow.com/comment/89391525
has title: How to make a function restart depend on answer(Python 2.7)
answer count: 1
has answer: http://stackoverflow.com/a/51205262
has comment: http://stackoverflow.com/comment/89391428
has comment: http://stackoverflow.com/comment/89391349
accepted answer: http://stackoverflow.com/a/51205262
tagged with: python-2.7
downvote count: 4
has body: from random import randint def roll_the_dice(): dice = randint(1, 6) dice2 = randint(1, 6) print dice , dice2 x = raw_input('If you want to reroll press 1 if not press 2:\n') if x == int(1): continue elif x == int(2): break else: print 'Invalid input' roll_the_dice() The problem is where i put the continue , how do i make it restart depend on the answer
type: AnsweredQuestion

http://stackoverflow.com/q/51253586
favorite count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51254562
tagged with: python
has title: Fastest way to mask rows of a 2D numpy array given a boolean vector of same length?
score: 1
upvote count: 1
type: Question
tagged with: numpy
tagged with: arrays
tagged with: data-science
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/89486148
has body: I have a numpy boolean vector of shape 1 x N, and an 2d array with shape 160 x N. What is a fast way of subsetting the columns of the 2d array such that for each index of the boolean vector that has True in it, the column is kept, and for each index of the boolean vector that has False in it, the column is discarded? If you call the vector mask and the array features, i've found the following to be far too slow: np.array([f[mask] for f in features]) Is there a better way? I feel like there has to be, right?

http://stackoverflow.com/q/51247169
has comment: http://stackoverflow.com/comment/89473232
tagged with: python
has answer: http://stackoverflow.com/a/51247462
has body: I'm creating a JSON (taking the data from another JSON). when I dump to JSON it's dumping the data unsorted. when I'm trying to sort it, it sorts it not in the way I want. This is the json I'm taking my data from: {"Logs":[{"Type":"VersionInfo","WorldTime":"11:22:04.9668710","SimulationTime":0,"FrameID":1,"XXXX":"XXXX XXX. XXXXX. ","Version":"XXXX","UnityVersion":"XXXXX"},{"Type":"GPS","WorldTime":"11:22:31.4395530","SimulationTime":0.0333333350718021,"FrameID":2,"Latitude":-0.000142197197419591,"Longitude":-0.00304042384959757,"Heading":89.3402404785156,"Speed":0,"Name":""},{"Type":"Gyro","WorldTime":"11:22:31.4395530","SimulationTime":0.0333333350718021,"FrameID":2,"Gyroscope":{"pitch_rate":0.00257105240598321,"yaw_rate":0.00034347633481957,"roll_rate":0.00864287838339806}},{"Type":"Accelerometer","WorldTime":"11:22:31.4395530","SimulationTime":0.0333333350718021,"FrameID":2,"Accelerometer":{"x":0.000268936157226563,"y":-4.93995867145713E-06,"z":500.000091552734}},{"Type":"CarTelemetries","WorldTime":"11:22:31.4395530","SimulationTime":0.0333333350718021,"FrameID":2,"Speed":10.0000019073486,"SteeringAngle":0,"Wheels_Spin":{"WheelFL":0,"WheelFR":0,"WheelRL":0,"WheelRR":0}},{"Type":"GPS","WorldTime":"11:22:36.6162530","SimulationTime":0.0666666701436043,"FrameID":3,"Latitude":-0.000142171658808365,"Longitude":-0.00303750648163259,"Heading":89.3430862426758,"Speed":0,"Name":""},{"Type":"Gyro","WorldTime":"11:22:36.6162530","SimulationTime":0.0666666701436043,"FrameID":3,"Gyroscope":{"pitch_rate":0.0431044436991215,"yaw_rate":0.00210362509824336,"roll_rate":-0.128382220864296}},{"Type":"Accelerometer","WorldTime":"11:22:36.6162530","SimulationTime":0.0666666701436043,"FrameID":3,"Accelerometer":{"x":-0.0327728018164635,"y":0.764712631702423,"z":-9.8843936920166}},{"Type":"CarTelemetries","WorldTime":"11:22:36.6162530","SimulationTime":0.0666666701436043,"FrameID":3,"Speed":9.80248165130615,"SteeringAngle":0.000244324823142961,"Wheels_Spin":{"WheelFL":250.613662719727,…
type: UnansweredQuestion
type: Question
has comment: http://stackoverflow.com/comment/89475518
has comment: http://stackoverflow.com/comment/89473182
has title: Python Json dunp sorting
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/89473169
has comment: http://stackoverflow.com/comment/89484584
score: 0
answer count: 1

http://stackoverflow.com/comment/89414358
score: 0
type: Comment
type: QuestionComment
has text: any reason I haven't seen anyone mention that dictionary.keys() returns a list of the keys in a dictionary?
comment on: http://stackoverflow.com/q/51216292

http://stackoverflow.com/q/51188286
tagged with: ibm-cloud
downvote count: 0
type: UnansweredQuestion
tagged with: sentry
score: 1
has answer: http://stackoverflow.com/a/51269586
favorite count: 0
type: Question
has title: How to add virtualenv to IBM cloud with Python
upvote count: 1
tagged with: python
answer count: 1
has body: I'm trying to add sentry to my project to capture errors. To use sentry I need to install raven with pip install raven. The problem is when I want to upload it to IBM as ibm function. As the docs says I need to upload .zip file with all .py files that I use including virtualenv. If I do it as follows (including all in virtualenv): zip -r ascrawler.zip venv __main__.py common.py db.py the zip file is bigger than allowed 48MB. Thus following the tutorial here, I can add only those virtualenv packages that I need. Thus I did it as follows: zip -r ascrawler.zip venv/bin/activate_this.py venv/lib/python3.6/site-packages/raven venv/lib/python3.6/site-packages/raven-6.9.0.dist-info __main__.py common.py db.py But when I try to invoke that function with: ibmcloud wsk action invoke --result ascrawler --param make Audi --param model A3 --param mileage 2500 I get an error that raven couldn't be found: ..... &lt;module&gt;", "2018-07-04T12:55:56.590718898Z stderr: from raven import Client", "2018-07-04T12:55:56.590724452Z stderr: ModuleNotFoundError: No module named 'raven'" Any idea what I do wrong?

http://stackoverflow.com/a/51217809
upvote count: 1
downvote count: 1
has body: Your code isn't easy to read, but I don't think you can do much in terms of efficiency. The fn = path is unnecessary if you change the following line to xl = pd.ExcelFile(path), that saves you one extra step. You could delete the prints, they take up a (very small) amount of time. Other than that you could have a look at using a VBA script to convert your Excel to CSV files. pd.read_csv is faster than reading from excel. I suppose this is your best option. That's all I can give you. Maybe someone wiser will come along and give you a better answer.
has comment: http://stackoverflow.com/comment/89416874
accepted answer of: http://stackoverflow.com/q/51216952
has comment: http://stackoverflow.com/comment/89417257
has comment: http://stackoverflow.com/comment/89416962
answers question: http://stackoverflow.com/q/51216952
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89417005
has comment: http://stackoverflow.com/comment/89417334
score: 0
type: Answer

http://stackoverflow.com/q/51179583
type: Question
tagged with: django-apps
answer count: 1
tagged with: bootstrap-4
favorite count: 0
has comment: http://stackoverflow.com/comment/89341700
upvote count: 2
has body: (venv) E:\Studia Materialy\Semestr 4\IO\l02-nr-6-cyber-mechanik-l02team- master&gt;python manage.py makemigrations L02 Traceback (most recent call last): File "manage.py", line 15, in &lt;module&gt; execute_from_command_line(sys.argv) File "C:\Users\keray\venv\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\keray\venv\lib\site-packages\django\core\management\__init__.py", line 357, in execute django.setup() File "C:\Users\keray\venv\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\keray\venv\lib\site-packages\django\apps\registry.py", line 89, in populate app_config = AppConfig.create(entry) File "C:\Users\keray\venv\lib\site-packages\django\apps\config.py", line 116, in create mod = import_module(mod_path) File "E:\Programowanie\Python\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "&lt;frozen importlib._bootstrap&gt;", line 994, in _gcd_import File "&lt;frozen importlib._bootstrap&gt;", line 971, in _find_and_load File "&lt;frozen importlib._bootstrap&gt;", line 941, in _find_and_load_unlocked File "&lt;frozen importlib._bootstrap&gt;", line 219, in _call_with_frames_removed File "&lt;frozen importlib._bootstrap&gt;", line 994, in _gcd_import File "&lt;frozen importlib._bootstrap&gt;", line 971, in _find_and_load File "&lt;frozen importlib._bootstrap&gt;", line 953, in _find_and_load_unlocked ModuleNotFoundError: No module named 'snowpenguin' Can't run python manage.py runserver because of this problem, python 3.7, Django 2.0.7. I have tried many versions of python, and Django, I have also reinstalled bootstrap.
type: UnansweredQuestion
tagged with: django
tagged with: python
downvote count: 1
has answer: http://stackoverflow.com/a/54072209
has title: ModuleNotFoundError: No module named 'snowpenguin'
score: 1

seq2seq
tag name: seq2seq
type: Tag
tags question: http://stackoverflow.com/q/51221525

http://stackoverflow.com/comment/89456115
has text: @qwww look this link for getting more information about 'content-type': https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/51238384
score: 0

http://stackoverflow.com/comment/89507423
has text: That's what I'm having problems with, I don't know how to reconfigure it properly.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51264680

http://stackoverflow.com/a/51291533
has comment: http://stackoverflow.com/comment/89563367
has comment: http://stackoverflow.com/comment/89563250
has comment: http://stackoverflow.com/comment/89629417
has comment: http://stackoverflow.com/comment/89615958
score: 0
type: AcceptedAnswer
has body: An easy syntax to do multiprocessing with function having severals parameters is using Pool() and starmap() import multiprocessing as mp def f(x, y): return x+y with mp.Pool(processes = mp.cpu_count()) as p: p.starmap(f, [(x, y) for x in range(10) for y in range(10)]) To do so, the function f must perform an elementary step. In your code: def firstLoop(r1, r2, d): count = 0 for i in range(r1): for j in range(r2): if(findDistance(dat1[i, 0], dat2[j, 0], dat1[i, 1], dat2[j, 1]) &lt;= d): count = count + 1 return count The elementary step is findDistance(dat1[i, 0], dat2[j, 0], dat1[i, 1], dat2[j, 1]) &lt;= d). A possible function f could be: def f(i, j, d): if findDistance(dat1[i, 0], dat2[j, 0], dat1[i, 1], dat2[j, 1]) &lt;= d): return 1 else: return 0 Then we initialize the result array and the variables: r1 = r2 = d = 100 results = np.zeros(shape=(1,r1*r2)) # Compute with mp.Pool() as p: results = p.starmap(f, [(i, j, d) for i in range(r1) for j in range(r2)]) Then to count you simply need to sum the array. I didn't test the code, the idea is here, but some adaptation might be needed especially in the way to return the result from the map function and to store them. I'm not using this syntax often since I'm mainly storing the results in a file at the end of the function multiprocessing. Maybe the creation of results is not actually needed beforehand. Not sure.
has comment: http://stackoverflow.com/comment/89603339
has comment: http://stackoverflow.com/comment/89603378
accepted answer of: http://stackoverflow.com/q/51291460
type: Answer
answers question: http://stackoverflow.com/q/51291460

http://stackoverflow.com/a/51248198
upvote count: 3
answers question: http://stackoverflow.com/q/51248109
type: AcceptedAnswer
has body: You are not passing any arguments to super(Practice, self).__init__(). Try this class Practice(models.Model): ... def __init__(self, *args, **kwargs): super(Practice, self).__init__(*args, **kwargs) self.value_cleaner()
downvote count: 0
score: 3
type: Answer
accepted answer of: http://stackoverflow.com/q/51248109

http://stackoverflow.com/comment/121965330
type: Comment
has text: Corroborating this, I created connectors and lines in python-pptx. For lines at least I had to be careful which end was which. Getting it wrong and python-pptx was happy but PowerPoint thought the file corrupt and deleted the lines. I never got connectors to work - with similar PowerPoint "corruption" issues. I would blame PowerPoint for being overly picky - unless the OOXML spec suggests otherwise. Has anyone tried this with eg LibreOffice?
type: AnswerComment
comment on: http://stackoverflow.com/a/51899285
score: 0

linkedin-api
tags question: http://stackoverflow.com/q/51195121
tag name: linkedin-api
type: Tag

http://stackoverflow.com/q/51309033
has comment: http://stackoverflow.com/comment/89594990
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/51309294
has comment: http://stackoverflow.com/comment/89594779
has title: Importing seaborn causes code to run twice
score: 0
has comment: http://stackoverflow.com/comment/89594819
tagged with: python
tagged with: python-3.x
type: UnansweredQuestion
tagged with: seaborn
has comment: http://stackoverflow.com/comment/89594888
has comment: http://stackoverflow.com/comment/89594904
has answer: http://stackoverflow.com/a/51309512
has body: I'm running seaborn on Python 3.6.5 (32-bit), Windows 10. So long as I import seaborn, it causes my code in shell to run twice. My code: import seaborn print('Load success!') for x in range(5): print(x) Load success! 0 1 2 3 4 Load success! 0 1 2 3 4 When commenting out or removing the import of seaborn it goes back to normal. #import seaborn print('Load success!') for x in range(5): print(x) Load success! 0 1 2 3 4 I can't recreate this bug with any other module and I've restarted my computer already. My question is how can I fix this bug, has this happened to anyone else, and where can I file a bug report with seaborn?

http://stackoverflow.com/q/51171328
tagged with: python
has body: I am trying to merge two dataframes per group in order to fill time for each user. Consider the following pyspark dataframes, df = sqlContext.createDataFrame( [ ('2018-03-01 00:00:00', 'A', 5), ('2018-03-01 03:00:00', 'A', 7), ('2018-03-01 02:00:00', 'B', 3), ('2018-03-01 04:00:00', 'B', 2) ], ('datetime', 'username', 'count') ) #and df1 = sqlContext.createDataFrame( [ ('2018-03-01 00:00:00',1), ('2018-03-01 01:00:00', 2), ('2018-03-01 02:00:00', 2), ('2018-03-01 03:00:00', 3), ('2018-03-01 04:00:00', 1), ('2018-03-01 05:00:00', 5) ], ('datetime', 'val') ) which produce, +-------------------+--------+-----+ | datetime|username|count| +-------------------+--------+-----+ |2018-03-01 00:00:00| A| 5| |2018-03-01 03:00:00| A| 7| |2018-03-01 02:00:00| B| 3| |2018-03-01 04:00:00| B| 2| +-------------------+--------+-----+ #and +-------------------+---+ | datetime|val| +-------------------+---+ |2018-03-01 00:00:00| 1| |2018-03-01 01:00:00| 2| |2018-03-01 02:00:00| 2| |2018-03-01 03:00:00| 3| |2018-03-01 04:00:00| 1| |2018-03-01 05:00:00| 5| +-------------------+---+ The column val from df1 is irrelevant and not needed in the final outcome so we can drop it. At the end, the expected result would be, +-------------------+--------+-----+ | datetime|username|count| +-------------------+--------+-----+ |2018-03-01 00:00:00| A| 5| |2018-03-01 01:00:00| A| 0| |2018-03-01 02:00:00| A| 0| |2018-03-01 03:00:00| A| 7| |2018-03-01 04:00:00| A| 0| |2018-03-01 05:00:00| A| 0| |2018-03-01 00:00:00| B| 0| |2018-03-01 01:00:00| B| 0| |2018-03-01 02:00:00| B| 3| |2018-03-01 03:00:00| B| 0| |2018-03-01 04:00:00| B| 2| |2018-03-01 05:00:00| B| 0| +-------------------+--------+-----+ I have tried to groupBy() and join but that did not work. I have also tried to create a function and register it as pandas_udf(), but still did not work, i.e. df.groupBy('usernames').join(df1, 'datetime', 'right') and @pandas_udf('datetime string, username string, count double', F.PandasUDFType.GROUPED_MAP) def f…
type: AnsweredQuestion
score: 3
upvote count: 3
type: Question
tagged with: pyspark
has answer: http://stackoverflow.com/a/51175376
tagged with: apache-spark
answer count: 1
downvote count: 0
favorite count: 0
has title: Merge per group to fill time series
accepted answer: http://stackoverflow.com/a/51175376

http://stackoverflow.com/q/51212489
has answer: http://stackoverflow.com/a/51212703
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89406155
has answer: http://stackoverflow.com/a/51212814
has comment: http://stackoverflow.com/comment/89406078
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89406114
type: Question
has comment: http://stackoverflow.com/comment/89409397
answer count: 2
tagged with: python
tagged with: coding-style
has comment: http://stackoverflow.com/comment/89406245
accepted answer: http://stackoverflow.com/a/51212814
has title: What is a good Pythonic way to handle complicated for loops with many functions?
score: 0
tagged with: for-loop
has body: I have a relatively complicated script that requires functions to be executed within a for loop and in some cases the result of one function is read into the next function. I can handle this relatively easy with a for loop, but the execution speed is significantly less than with list comprehension. I am not sure how to execute this problem with list comprehension. Is there a better vectorized way to do this in python. I am attaching an example that is significantly simpler than my actual problem, but it I think it highlights the problem. Any thoughts would be appreciated. def func1(i): return i + 1 def func2(j): return j + 2 def func3(k): return k + 3 class test: def __init__(self, one, two, three): self.one = one self.two = two self.three = three if __name__ == "__main__": obj = [] for i in range(10): if i !=3 and i != 7: value1 = func1(i) value2 = func2(i) value3 = func3(value2) one1 = value1 + value2 two1 = value1 + value2 + value3 three1 = value1 + value3 obj.append(test(one1, two1, three1))
possible better answer: http://stackoverflow.com/a/51212703

http://stackoverflow.com/comment/89386878
type: QuestionComment
comment on: http://stackoverflow.com/q/51202370
has text: Did you mean like this: `{k: matrix[k] for k in k}`
score: 0
type: Comment

http://stackoverflow.com/comment/89410705
has text: You are right: the OP did say that. But I'm almost certain that that's *not* what was really wanted: the specification was incomplete.
comment on: http://stackoverflow.com/a/51172766
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/51172798
accepted answer: http://stackoverflow.com/a/51172886
has answer: http://stackoverflow.com/a/51173007
tagged with: python
type: AnsweredQuestion
has title: Unexpected KeyError: in Python 2.7.10
has comment: http://stackoverflow.com/comment/89328403
type: Question
possible better answer: http://stackoverflow.com/a/51173007
has body: I am new to coding in Python and I have encountered an unexpected error with my code. Any help with this would be much appreciated import json from urllib2 import urlopen response = urlopen("https://finance.yahoo.com/webservice/v1/symbols/allcurrencies/quote?format=json") source = response.read() # print(source) data = json.loads(source) # print(json.dumps(data, indent=2)) usd_rates = dict() for item in data['list']['resources']: name = item['resource']['fields']['name'] price = item['resource']['fields']['price'] usd_rates[name] = price print name, price
tagged with: python-2.7
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/51172886

http://stackoverflow.com/a/51225556
type: Answer
has comment: http://stackoverflow.com/comment/89431430
score: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/89431446
has comment: http://stackoverflow.com/comment/89436909
has comment: http://stackoverflow.com/comment/89431695
has body: The time to do arithmetics (9**(N**N+N)) scales very nicely (and exponentially) with N, as you can see from the following chart. It would take my comp approximately 48 minutes to calculate the answer for N=9. However, at some point the literal representation of your number would not fit into the RAM, and that's where swapping/paging kicks in and slows the whole thing down by an unpredictable factor. (I understand that this does not answer your question, but I still wanted to share the chart. Feel free to flag/downvote.)
upvote count: 3
answers question: http://stackoverflow.com/q/51225423
has comment: http://stackoverflow.com/comment/89432464
has comment: http://stackoverflow.com/comment/89432468
has comment: http://stackoverflow.com/comment/89431599

http://stackoverflow.com/comment/89456510
has text: @A1122 I tried concating three dataframes with unequal length but same columns, it worked with your piece of code, only you will see NaN for the rows which are not available in either of the dataframes
comment on: http://stackoverflow.com/q/51236768
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/q/51272799
type: Question
has comment: http://stackoverflow.com/comment/89523840
accepted answer: http://stackoverflow.com/a/51273299
has body: Q1. If I have a very general class, with an attribute whose name could be better represented in more specific inherited classes, how can I access the same methods from the parent class if the attribute has changed its name? For example (not my real scenario, but it shows what I mean). class Entity(object): def __init__(self): self.members= {} ... # Methods that use self.members class School(Entity): def __init__(self): super(Entity,self).__init__(self) class Company(Entity): def __init__(self): super(Entity,self).__init__(self) for class School and for class Company, I would like to be able to use attributes that are more specific, such as self.students and self.employees, but that still work with the methods that were defined for self.members in the class Entity. Q2. Would this be bad practice? What would be the best way to approach this? In my real case, the word I used for self.members is too general.
has comment: http://stackoverflow.com/comment/89523686
has comment: http://stackoverflow.com/comment/89523809
tagged with: python-2.7
score: 0
answer count: 1
has title: Attribute name change for inherited classes. Possible/Bad practice?
tagged with: python
has answer: http://stackoverflow.com/a/51273299
type: AnsweredQuestion

http://stackoverflow.com/q/51240939
tagged with: python
accepted answer: http://stackoverflow.com/a/51241049
score: 0
has answer: http://stackoverflow.com/a/51241011
has title: Why unordered JSON values?
type: AnsweredQuestion
has body: I've got the next code on python that convert two lists to json: JSONRules = json.dumps( [{'RuleAction':action, 'RuleName':name} for action, name in zip(RulesAction, RulesName)] ) But the output it's totally random, why? out[1]: [{"RuleAction": "0", "RuleName": "Policy4"}, {"RuleAction": "0", "RuleName": "Policy5"}] out[2]: [{"RuleName": "Policy4", "RuleAction": "0"}, {"RuleName": "Policy5", "RuleAction": "0"}]
has answer: http://stackoverflow.com/a/51240988
tagged with: http://stackoverflow.com/tag/json
type: Question
possible better answer: http://stackoverflow.com/a/51240988
has answer: http://stackoverflow.com/a/51241049
answer count: 3
has comment: http://stackoverflow.com/comment/89460797

http://stackoverflow.com/comment/89540970
score: 0
has text: That is way too specific question to answer here. Image preprocessing is a separate issue from image uploading, unrelated with your original question. Also, you did not provide any details what kind of preprocessing you need to do for the images. Hence, it is impossible to help you further.
type: Comment
comment on: http://stackoverflow.com/a/51278695
type: AnswerComment

http://stackoverflow.com/q/51299354
has answer: http://stackoverflow.com/a/51310043
answer count: 6
has answer: http://stackoverflow.com/a/51299578
type: Question
has answer: http://stackoverflow.com/a/51299750
has answer: http://stackoverflow.com/a/51299511
downvote count: 0
favorite count: 0
tagged with: python
upvote count: 2
type: UnansweredQuestion
has title: Lists from a list based on specific key
has answer: http://stackoverflow.com/a/51299696
has answer: http://stackoverflow.com/a/51299855
score: 2
has body: Hi I am new in programming. I am having a problem. I don't know what is better solution for this issue. The problem is like this.. I have a list say, list = ['a', '123', '643', 'b', '890', '234', '123', 'd', '432', '678' ] So I want to make 3 lists or a json object, what actually possible please suggest better option. the idea is list_a = ['123', '643'] list_b = ['890', '234', '123'] list_d = ['432', '678'] or, list_ob = {"a": ["123", "643"], "b": ["890", "234", "123"], "d": ["432", "678"] } Here a, b, d are only some specific character or can be words. Please help me out.
tagged with: list

http://stackoverflow.com/comment/89424827
type: Comment
type: QuestionComment
has text: Thank you for your input sir
comment on: http://stackoverflow.com/q/51222060
score: 0

http://stackoverflow.com/comment/89391835
has text: Ok I solved the problem. The frame changes inbetween. A new frame is being loaded. I have to check the title...
type: Comment
comment on: http://stackoverflow.com/a/51188441
score: 0
type: AnswerComment

http://stackoverflow.com/a/69088669
answers question: http://stackoverflow.com/q/51312300
has comment: http://stackoverflow.com/comment/122136195
has body: What I did was to make sure it was running either the script or the IDE in Administrator mode. For some reason, games I wrote scripts for like Black Desert Online or CSGO only detect key presses when I am running it in Administrator.
has comment: http://stackoverflow.com/comment/122110701
score: 0
type: Answer

http://stackoverflow.com/q/51193743
downvote count: 0
type: Question
has answer: http://stackoverflow.com/a/51194939
has body: How to get the last matching dictionary from list of dictionaries: Example: test_dict={'user'='xxx','tasks':[{'id':'01','age':'60'},{'id':'02','age':'50'},{'id':'01','age':'65'},{'id':'02','age':'65'}]} How do I get the last dict from tasks whose 'id' is '01'? Do I need to iterate through entire list - test_dict['tasks'] or is there any good approach? Thanks
upvote count: 2
tagged with: python-2.7
answer count: 3
has title: python: get the last matching dictionary from list
has answer: http://stackoverflow.com/a/51194370
tagged with: iteration
favorite count: 0
possible better answer: http://stackoverflow.com/a/51194536
has comment: http://stackoverflow.com/comment/89369099
has answer: http://stackoverflow.com/a/51194536
tagged with: python
tagged with: dictionary
score: 2
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51194939
tagged with: list

http://stackoverflow.com/a/51264766
type: Answer
has body: In the current development version of matplotlib this should work due to the fix provided. With the current released version of matplotlib, would need to reestablish the sharing e.g. like import matplotlib.pyplot as plt import pickle fig, axes = plt.subplots(ncols=3, sharey="row") axes[0].plot([0,1],[0,1]) axes[1].plot([0,1],[1,2]) axes[2].plot([0,1],[2,3]) pickle.dump(fig, file('fig1.pkl', 'wb')) plt.close("all") fig2 = pickle.load(file('fig1.pkl','rb')) ax_master = fig2.axes[0] for ax in fig2.axes: if ax is not ax_master: ax_master.get_shared_y_axes().join(ax_master, ax) plt.show() This has the drawback that you need to know which axes to share. In the case of all axes being shared this is of course easy, as shown above.
has comment: http://stackoverflow.com/comment/89507657
accepted answer of: http://stackoverflow.com/q/51264460
type: AcceptedAnswer
downvote count: 0
score: 8
answers question: http://stackoverflow.com/q/51264460
upvote count: 8

http://stackoverflow.com/a/51207438
has comment: http://stackoverflow.com/comment/89396080
accepted answer of: http://stackoverflow.com/q/51207309
type: Answer
has body: Built-in functions such as eval() are written in C, not Python, so the source code can't be retrieved here.
has comment: http://stackoverflow.com/comment/89395699
score: 0
answers question: http://stackoverflow.com/q/51207309
type: AcceptedAnswer

http://stackoverflow.com/q/51243094
tagged with: django
tagged with: python
answer count: 0
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/89464991
type: Question
has title: Django - Show shell output command while process is running
upvote count: 1
has body: I'm building a django-based web application that needs to run a shell command. For example: I need to show a live output of ping command. With some structures below: Django view: OUTPUT HERE Run Command Javascript: function runCommand() { $.ajax({ type: 'POST', url: '/api/runCommand', success: function(data) { $(".live-output").html(data); } }); } Django function (/api/runCommand url goes to api.runCommand): import subprocess def runCommand(request): cmd = "ping google.com" process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) while True: nextline = process.stdout.readline() if nextline == '' and process.poll() is not None: break sys.stdout.write(nextline) sys.stdout.flush() Is there any way to send the sys.stdout back to my view everytime it generates a new output line ? (Not when the process DONE, but ALONGSIDE with the running process).
tagged with: shell
favorite count: 0
type: UnansweredQuestion

http://stackoverflow.com/q/51168744
tagged with: python
has comment: http://stackoverflow.com/comment/89320441
type: Question
score: 0
has title: Different behaviours of printing strings (sys.stderr.write) in Jupyter Notebook and Linux terminal
has answer: http://stackoverflow.com/a/51168970
answer count: 1
has comment: http://stackoverflow.com/comment/89320654
tagged with: jupyter
tagged with: string
tagged with: jupyter-notebook
has body: In Jupyter Notebook, when running the following Python codes, the number from 2 to 9 is printed, one after one. import time for i in range(1,10): time.sleep(1) sys.stderr.write('\r %d' % i) sys.stderr.flush() Q1: Why is 1 not printed? Q2: Why the numbers are printed one after one, I mean, when a larger number is printed, the immediate smaller number disappears (which is awesome)? Why sys.stderr.write('\r %d' % i) works in this way but sys.stderr.write('%d \r' % i) works in a "normal" way which displays all the numbers? When running the exact above codes in Linux terminal. The output is different again: 13 23 33 43 53 63 73 83 93 If I change the line sys.stderr.write('\r %d' % i) to sys.stderr.write('%d \r' % i), the output becomes: 3 3 3 3 3 3 3 3 3 This is so strange. Q3: Why running the above codes in Linux terminal has different output?
tagged with: terminal
type: UnansweredQuestion

http://stackoverflow.com/comment/89348147
type: AnswerComment
type: Comment
score: 1
comment on: http://stackoverflow.com/a/51182140
has text: Thanks. A quick question on possible simplifications: `chunk = pd.Series(df.loc[df.id == i, 'hit']) #, index=df.loc[df.id == i].index)` and `chunk = pd.DataFrame(chunk).reset_index().fillna(0)` I can't see the difference even if I omit the index values when creating Series or DataFrame?

http://stackoverflow.com/q/51237804
has body: I'm running CKAN 2.6.3 locally on my mac. I've tried replicating this instance from a database dump on the remote instance. The rest of the site seems to work just fine, but hitting /group leads to an infinite redirect. If I try and visit a specific group, I can view that just fine. Adding a group gives me the following stack trace. IntegrityError: (IntegrityError) duplicate key value violates unique constraint "group_name_key" DETAIL: Key (name)=() already exists. 'INSERT INTO "group" (id, name, title, type, description, image_url, created, is_organization, approval_status, state, revision_id) VALUES (%(id)s, %(name)s, %(title)s, %(type)s, %(description)s, %(image_url)s, %(created)s, %(is_organization)s, %(approval_status)s, %(state)s, %(revision_id)s)' {'description': u'', 'created': datetime.datetime(2018, 7, 8, 19, 57, 57, 297647), 'title': u'', 'approval_status': u'approved', 'is_organization': False, 'state': u'active', 'image_url': u'', 'revision_id': u'339d9b92-cfc3-4a0b-9bb7-cd8e53f15f62', 'type': u'group', 'id': 'a827e08b-9afd-4e3a-98c3-a78e4247b377', 'name': u''} Having followed a few troubleshooting paths, I've come up dry, except discovering that the initial request to /group serves a 301 redirect back to /group. Other tidbits: The remote instance does not have the same issue running under the paster httpserver Locally served with the standard paster httpserver with paster serve /etc/ckan/development.ini I also can't add datasets. As I'm just discovered while posting this. Looks to me like a related error. (stacktrace posted below) IntegrityError: (IntegrityError) null value in column "name" violates not-null constraint DETAIL: Failing row contains (b7b54c05-cbb7-4f15-ac05-2d8caf442eb4, null, null, null, null, null, null, 0c61de41-bd40-4f7a-b639-16a2f2aea503, null, null, null, null, active, dataset, null, f, 2018-07-09 03:08:37.42187, null, 2018-07-09 03:08:37.421862). 'INSERT INTO package (id, name, title, version, url, author, author_email, maintainer…
has comment: http://stackoverflow.com/comment/89497912
favorite count: 0
has comment: http://stackoverflow.com/comment/89454883
has comment: http://stackoverflow.com/comment/89455363
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89569169
tagged with: python
tagged with: ckan
answer count: 0
score: 0
has title: What would cause an infinite redirect on the /group route?
has comment: http://stackoverflow.com/comment/89530691
upvote count: 1
downvote count: 1
type: Question

http://stackoverflow.com/comment/89616637
has text: k-means is not a classifier. What are you trying to achieve here?
type: Comment
comment on: http://stackoverflow.com/q/51320227
type: QuestionComment
score: 0

http://stackoverflow.com/q/51304892
type: Question
has body: $ cd python_test_venv/ $ python3.6 -m venv env $ . env/bin/activate $ which pip ~/python_test_venv/env/bin/pip $ pip -V pip 9.0.1 from [...]/python_test_venv/env/lib64/python3.6/site-packages (python 3.6) $ pip install javapackages Requirement already satisfied: javapackages in [...]/python2.7/site-packages Why is is that 1) It reads from site-packages at all? Per the documentation, the flag that determines whether or not this should be accessible is False. 2) It reads from site-packages from an older version of Python?
tagged with: virtualenv
tagged with: python-3.6
score: 0
has comment: http://stackoverflow.com/comment/89588771
type: UnansweredQuestion
tagged with: pip
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/89589052
has title: Disable reading from site-packages

http://stackoverflow.com/comment/89501437
type: QuestionComment
type: Comment
has text: well i have read it with python and generated a csv file with x,y,z and intensity. But all the existing examples i see on github use the pcd, bin or ply formats. So I am confused how to use the csv in python itself or if it is possible to use the struct file in matlab.
comment on: http://stackoverflow.com/q/51261563
score: 0

http://stackoverflow.com/comment/89342208
score: 1
comment on: http://stackoverflow.com/a/51179460
has text: Alternatively just import the module itself like so: `import turtle`.
type: AnswerComment
type: Comment

http://stackoverflow.com/q/51236028
has comment: http://stackoverflow.com/comment/89451070
tagged with: python
has comment: http://stackoverflow.com/comment/89451130
has comment: http://stackoverflow.com/comment/89451110
tagged with: pickle
has title: Trouble analyzing pickled data in Python 3
score: 2
type: AnsweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/51236055
accepted answer: http://stackoverflow.com/a/51236055
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/89451548
has comment: http://stackoverflow.com/comment/89451044
answer count: 1
favorite count: 0
has body: I have a dataset which I want to analyze (I cant put it here due to its size but I can describe it) its a dictionary in pickled form, which looks like this: name:(salary: x, bonus: y, email_address: z, etc.) each name has 21 attributes with 21 values (some are numbers, some are booleans, some are strings) I have used pandas to store the data in a dataframe df = pd.read_pickle('data.pkl') but unlike pandas dataframes which I have manipulated before, I cannot seem to be able to traverse through this one. head() function does not work, keys() does work but it displays only names in the file. Getting other data by specifying name also works (ex. printing df['john smith']). I tried doing this to access other data without manually writing all names, but it does not work names = df.keys() for i in range(len(df.keys())): name = names[i] print(df[name]) I get error saying ''dict_keys' object does not support indexing'. I guess dictionaries cannot be traversed in same way as the array or a list. Any help would be appreciated.
tagged with: pandas

http://stackoverflow.com/a/51310385
downvote count: 0
has body: I just had this problem. shmee's proposed solution is what worked for me: The load_user() function should not be a part of the User class, but instead its own standalone function. The load_user() function should call User.query.get(user_id), not User.get(user_id). I think this confusion comes from the fact that Flask-Login's documentation has it the latter way as of today: return User.get(user_id). Example code: class User(db.Model, UserMixin): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(80), unique=True, nullable=False) password = db.Column(db.String(80)) def __repr__(self): return '&lt;User %r&gt;' % self.username @login_manager.user_loader def load_user(user_id): return User.query.get(user_id)
score: 9
type: Answer
upvote count: 9
answers question: http://stackoverflow.com/q/51209763

http://stackoverflow.com/q/51265813
favorite count: 0
tagged with: quad
tagged with: python
type: AnsweredQuestion
downvote count: 0
linked to: http://stackoverflow.com/q/30913664
score: 1
has title: scipy.integrate.tplquad gives wrong result for integral over large volume
tagged with: scipy
type: Question
has body: I'm trying to integrate a function of 3 variables f(x,y,z) over all space. When I integrate over a small volume, I get roughly the right result. However, when I increase the volume of integration, python says that the integral is zero. I'm fairly confident that the issue here is that the function f is only non-zero in a small region of space, and tplquad dosen't sample over this region enough when the integration volume is large. I found an answer to a similar problem in 1D at this link; scipy.integrate.quad gives wrong result on large ranges. The solution in 1D was to pass an argument 'points' to scipy.integrate.quad, and this helped quad focus on the interval where the integral was non-zero. My question is; is there a similar argument to 'points' for tplquad? Or perhaps some other way I can instruct tplquad to focus on a particular region of space?
tagged with: numerical-integration
upvote count: 1
answer count: 1
has answer: http://stackoverflow.com/a/51267057
accepted answer: http://stackoverflow.com/a/51267057

http://stackoverflow.com/comment/89611112
comment on: http://stackoverflow.com/q/51317280
score: 0
type: Comment
type: QuestionComment
has text: Oh word well that cleared that up. Use np as much as possible unless dealing with sparse matrices or anything that scipy handles of that nature

http://stackoverflow.com/q/51218152
accepted answer: http://stackoverflow.com/a/51219111
type: AnsweredQuestion
type: Question
has body: in my vps i have run 4 Python Script and its been 60 days that i don't reboot my vps and now i have to, but if i reboot vps my python Variables &amp; data will be removed because i don't store them in file and they are store in variables in python script. my OS is Ubuntu Server 16.04 LTS and i was run my python codes with nohup command until they can run in background. Now i need a way to stop my scripts without removing they variables and start them with same variables and data after i reboot my vps. Is There Any Way That I Can Do This? In Addition, I'm sorry for writing mistakes in my question.
tagged with: ubuntu-server
score: 0
tagged with: backup
answer count: 1
has title: Save a Script Variables inside code and reset them after reboot
tagged with: python-3.x
tagged with: vps
tagged with: python
has answer: http://stackoverflow.com/a/51219111

http://stackoverflow.com/q/51230090
has answer: http://stackoverflow.com/a/51230512
has answer: http://stackoverflow.com/a/51230339
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51230145
tagged with: django-views
score: 1
accepted answer: http://stackoverflow.com/a/51230339
upvote count: 1
has title: For filtering data in Django, build dynamic query for multiple columns
has body: I have to filter data from model based on the run time values. I am getting 5 values via query string. My querystring is like below: http://127.0.0.1:8000/personal/search/?month=&amp;year=&amp;account=&amp;deliveryManagedFrom=&amp;marketmName= So, I want to include all or none of the values in the filter so that it displays the desired result. Below is the filter query which I am writing: sum_tt_count = NetworkRelatedInformation.objects.filter(month=month, year=year, account_id=account, account__deliveryManagedFrom=deliveryManagedFrom, account__marketName=market).aggregate(Sum('tt_count')) totalttcount = sum_tt_count['tt_count__sum'] It is working well in case, all the values have been provided. In case, if any value is blank, it should not consider that value and display output as per other filter criteria. Pls suggest how to implement an OR filter with 5 data inputs. It is not necessary that all 5 data inputs have values . So the value can be None or the value in the querystring
possible better answer: http://stackoverflow.com/a/51230145
type: Question
linked to: http://stackoverflow.com/q/51202612
tagged with: django-filter
answer count: 3
tagged with: django-queryset
downvote count: 0
favorite count: 0
tagged with: django
tagged with: python

http://stackoverflow.com/q/51289280
has comment: http://stackoverflow.com/comment/89556699
tagged with: python
type: AnsweredQuestion
upvote count: 0
tagged with: conv-neural-network
tagged with: tensorflow
type: Question
has answer: http://stackoverflow.com/a/51289730
accepted answer: http://stackoverflow.com/a/51289730
has body: I have a dataset with each data point having 4 images (different pixel sizes for each) that are correlated to each other. I want to do convolutions on them separately, and then combine the information for the 4 images and feed it to 1 dense network. How can I do this in keras functional API? I also have 10 other features that are not images. I plan to feed it directly to the dense end of the network. So what I want is: 4 independent conv layers flatten concatenate Dense layers 1 Output How can I provide the input to keras in such a way?
has title: Convolutions on 4 images separately
score: -1
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/89556828
tagged with: keras
favorite count: 0

http://stackoverflow.com/q/51282165
type: AnsweredQuestion
has body: I am trying to sort an array by several criteria. Python's sorted function can take a tuple as a key for this purpose. It can also take a lambda argument as key. I've tried a lambda returning a tuple as key and got TypeError: &lt;lambda&gt;() takes exactly 1 argument (2 given) and a tuple of lambdas and got TypeError: 'tuple' object is not callable. I am using Python 2.7.13 on windows. Does anybody know why I get this error and how to fix it? Example: In [1]: message = {'tcu':1,'timestamps':{'device':23432}} In [2]: message_array = [message, message] In [3]: key = lambda message: (message['tcu'], message['timestamps']['device']) In [4]: sorted(message_array,key) --------------------------------------------------------------------------- TypeError Traceback (most recent call last) &lt;ipython-input-4-45bd2b89f64b&gt; in &lt;module&gt;() ----&gt; 1 sorted(message_array,key) TypeError: &lt;lambda&gt;() takes exactly 1 argument (2 given) In [5]: key = (lambda message: message['tcu'], lambda message: message['timestamps']['device']) In [6]: sorted(message_array,key) --------------------------------------------------------------------------- TypeError Traceback (most recent call last) &lt;ipython-input-6-45bd2b89f64b&gt; in &lt;module&gt;() ----&gt; 1 sorted(message_array,key) TypeError: 'tuple' object is not callable
possible better answer: http://stackoverflow.com/a/51282322
type: Question
accepted answer: http://stackoverflow.com/a/51282318
tagged with: sorting
has title: sorted not taking lambda returning tuple as key argument
tagged with: python-2.7
score: 0
answer count: 2
tagged with: python
has answer: http://stackoverflow.com/a/51282318
has answer: http://stackoverflow.com/a/51282322

http://stackoverflow.com/comment/89476943
has text: @Joel I hope not, because that's completely wrong
type: QuestionComment
type: Comment
score: 3
comment on: http://stackoverflow.com/q/51249024

http://stackoverflow.com/q/51214404
type: Question
has comment: http://stackoverflow.com/comment/89409984
answer count: 1
tagged with: arrays
tagged with: string
has answer: http://stackoverflow.com/a/51214494
tagged with: python
has comment: http://stackoverflow.com/comment/89409924
has comment: http://stackoverflow.com/comment/89409776
favorite count: 0
tagged with: parsing
downvote count: 2
tagged with: keyword
upvote count: 1
has body: I have a variable abc="[&lt;Result id:af2af0&gt;, &lt; Result id:5ebb65&gt;, &lt; Result id:ee0f90&gt;, &lt; Result id:e8ced6&gt;]" abcd=str(abc) if isinstance(abc, str): print("GOOD") else: print("NOT GOOD") I want to parse this string after keywork="id:" to stock the six value number into array array[0]=af2af0 array[1]=5ebb65 ...
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51214494
score: -1
has title: Python3 parse string after keyword

http://stackoverflow.com/comment/89329321
type: Comment
comment on: http://stackoverflow.com/a/51173202
has text: thank you for your reply, but would it be possible to get an example code on how to do this?
type: AnswerComment
score: 0

http://stackoverflow.com/q/51224557
score: 2
answer count: 0
has body: hi this is my first post so i will try my best to explain what i need. My problem is that i'm using a specific mic that might disconnect at any time if so i need it to connect to my pc's mic. here is the code mic = None for i in sr.Microphone.list_microphone_names(): print(i) for index, name in enumerate(sr.Microphone.list_microphone_names()): print("Microphone with name \"{1}\" found for `Microphone(device_index={0})`".format(index, name)) if str(name) == "Microphone (Blue Snowball)": print("\n\n\n\n\n") mic = sr.Microphone(sample_rate = 18000, device_index= index) print("using Microphone with name \"{1}\" found for `Microphone(device_index={0})`".format(index, name)) print(mic) if mic == None: for index, name in enumerate(sr.Microphone.list_microphone_names()): print("Microphone with name \"{1}\" found for `Microphone(device_index={0})`".format(index, name)) if str(name) == "Microphone (Realtek High Defini": print("\n\n\n\n\n") mic = sr.Microphone(sample_rate = 18000, device_index= index) print("using Microphone with name \"{1}\" found for `Microphone(device_index={0})`".format(index, name)) print(mic) print(mic) the code above is ran 1 every 5 seconds or so now the problem is when i disconnect the mic it still says it there it seems like the sr.Microphone.list_microphone_names()get the all the audio devices when the program starts then during operation when it is called again it does not update that list it just retrieves this list that was made at the start. now i need a way to either update this list or see which mics are operational. i know pyaudio does see this mic is missing cause the device indexes changes but it does not update the list thanks from sir snibbles p.s i have research this for 4 hours and i don't have any experience with pyaudio
downvote count: 0
has title: python speech recognition library / pyaudio: refresh list of mics
type: Question
upvote count: 2
tagged with: pyaudio
favorite count: 0
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/89362427
type: QuestionComment
comment on: http://stackoverflow.com/q/51181368
has text: As far as I know there is no option to set the tab size of the ttk.Notebook.
score: 0
type: Comment

http://stackoverflow.com/q/51294237
type: Question
has body: I am currently extracting columns in a file by using awk in os.system(): os.system("awk '{print $'%i'}' &lt; infile &gt; outfile"%some_column) np.loadtxt('outfile') Is there an equivalent way to accomplish this using regex? Thanks. Edit: I want to clarify that I am looking for the most optimal way to extract specific columns of large files.
has answer: http://stackoverflow.com/a/51295064
score: 0
has comment: http://stackoverflow.com/comment/89566005
answer count: 1
has comment: http://stackoverflow.com/comment/89568136
type: UnansweredQuestion
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/89566745
has title: Python: Use regex to extract a column of a file

http://stackoverflow.com/comment/89395372
score: 0
comment on: http://stackoverflow.com/a/51207248
type: Comment
has text: This would result in white pixels having the value of 1, whereas the question wants 1 for black pixels.
type: AnswerComment

http://stackoverflow.com/comment/89555430
type: Comment
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/51288530
has text: Please paste the actual input of the file, in its actual format. Also you need to fix your indentation, your current code won't run because of it. Also a link to the Turbidity equation would help since you're current;y just overwriting the values and not storing them anywhere. Plus you never define `x` and `y`!

http://stackoverflow.com/q/51236585
type: UnansweredQuestion
has title: Unable to assign value
tagged with: python
tagged with: dictionary
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/89452175
upvote count: 0
score: -1
has answer: http://stackoverflow.com/a/51236626
answer count: 1
has body: I am having trouble trying to assign a value to a "Grocery List" Specifically, given a .txt doc, which contains: Grocery Apple: 12 egg: 10 milk: 11 I am trying to open the file, and compute the total price for it. What I have so far: shoplist={} line=0 for item in open ("lab3demo.txt","r"): item= item.split(":") line+=1 if line ==1: continue print (item) So far it does return ['Apple',12\r\n'], etc. However, I am then trying to assign the price as a value price = shoplist[item], which does not work. Since I need it to output the item : price item : price item : price total: total price which I am not able to do. What should I be looking to do so? I have tried starting as a dictionary, but haven't got too far.
favorite count: 0

http://stackoverflow.com/q/51284627
tagged with: matplotlib
type: Question
upvote count: 4
downvote count: 0
has answer: http://stackoverflow.com/a/51284756
score: 4
accepted answer: http://stackoverflow.com/a/51284756
answer count: 1
favorite count: 0
tagged with: python-3.x
tagged with: python
has body: I create a scatter plot with an annotation with the following code: import numpy as np import matplotlib.pyplot as plt np.random.seed(12) plt.scatter(np.random.random(10), np.random.random(10), zorder = 2) bbox_props = dict(boxstyle = "circle, pad = 10", fc = "w", ec = "k") plt.annotate("interesting", (0.6, 0.8), bbox = bbox_props, zorder = 1) plt.show() Sample output: How do you prevent that the annotation is shown outside the graph? I searched for it but could only find the opposite case that people want to print an annotation/text/legend outside the graph.
type: AnsweredQuestion
has title: Prevent that an annotation is shown outside the graph area

http://stackoverflow.com/q/51251288
has answer: http://stackoverflow.com/a/51252509
has body: I have a custom storage class I'm using and I am trying to set a different path to upload the file to but I keep getting "Str object is not callable". Here's the code where I call my custom class: fs = DGStorage(user_login=user_login, name=name, content=content, csv=True) fs.path = os.path.join("/u/vnc/web", "docs", "upload", "csv") When fs.save is called, I get the str object error (very annoying). I don't set the path in the storage class because it's set somewher else. Custom Storage Model: class DGStorage(FileSystemStorage): def __init__(self, name=None, content=None, user_login=None, location=None, base_url=None, file_permissions_mode=None, directory_permissions_mode=None, csv=False): # FileSystemStorage.__init__(self, self.location) self._location = location self._base_url = base_url self._file_permissions_mode = file_permissions_mode self._directory_permissions_mode = directory_permissions_mode self.name = name self.content = content self.user_login = str(user_login) self.user_dir = self.user_login + datetime.now().strftime('_%Y%m%d') self.csv = csv super(DGStorage, self).__init__() @property def user_directory(self): return safe_join(self.location, 'uploads', self.user_dir) @property def get_filename(self): if not self.name: self.name = self.content.name name = self.name name = name.replace(' ', '_') return name def path(self, name=None): if not name: name = self.content.name else: name = name.replace(' ', '_') #if self.csv: # return os.path.join("/u/vnc/web", "docs", "upload", "csv") return safe_join(self.location, 'uploads', self.user_dir, name) The self.csv doesn't seem to work either, it just halts when I set the path that way as well.
type: Question
has comment: http://stackoverflow.com/comment/89481495
score: 0
answer count: 1
has title: Django Setting Custom Path for Storage ('str object is not callable')
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89481818
tagged with: django
tagged with: python

http://stackoverflow.com/comment/89431602
score: 0
comment on: http://stackoverflow.com/a/51220695
type: AnswerComment
has text: @임종훈 Well, the code in that example passes a dict every time it calls `write`. You're passing a set. My answer explains why that makes a difference. I still don't know what you're trying to graph here. Maybe you want the dict `{'dateTime': dateTime, 'tempt': tempt, 'humty': humty}`, maybe you want something different. Only you know what you're trying to do.
type: Comment

http://stackoverflow.com/comment/123162937
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51247419
type: Comment
has text: any luck with this ? I am having the same problem.

http://stackoverflow.com/q/51169958
has body: I am writing a GUI. My GUI receives an integer input through QLineEdit and the input should be transferred to another python script where it performs calculations. The GUI.py file calls the python file Calculation.py through subprocess.call. When I try to send arguments to Calculation.py, it throws an error : error "TypeError: Unsupported operand type for /: 'str' and 'int'". Any help would be much appreciated.
linked to: http://stackoverflow.com/q/2376464
type: UnansweredQuestion
tagged with: python
tagged with: qlineedit
answer count: 0
has comment: http://stackoverflow.com/comment/89353680
has comment: http://stackoverflow.com/comment/89322961
duplicate of: http://stackoverflow.com/q/67291743
has comment: http://stackoverflow.com/comment/89354036
type: Question
duplicate of: http://stackoverflow.com/q/20449427
tagged with: pyqt4
has title: Getting an input from QLineEdit and sending it to another python file for calculation
score: 0
tagged with: pyqt
has comment: http://stackoverflow.com/comment/89355344
tagged with: python-module

http://stackoverflow.com/q/51217775
has comment: http://stackoverflow.com/comment/89417011
has answer: http://stackoverflow.com/a/51217990
accepted answer: http://stackoverflow.com/a/51217990
has answer: http://stackoverflow.com/a/51218123
has answer: http://stackoverflow.com/a/51218003
has body: So far i've got : s = 'azcbobobegghakl' i = 0 j = 1 temp = '' #temporary variable I use to change longest longest = '' for b in range(len(s)): if s[i] &lt;= s[j]: #checks if it's in alphabetical order temp+=s[i] if len(longest) &lt; len(temp): longest = temp else: temp = '' #reset temp after every substring if len(longest) &lt; len(temp): longest += temp #update longest if the new substring is longer i +=1 if j &lt; len(s) - 1 : # because otherwise i get an IndexError j +=1 print('Longest substring in alphabetical order is:', longest) Now my problem is that I always get the correct string BUT without the last letter . (for example here instead of "beggh" i get "begg"). I also have to make it so that if it's a tie, the first one counts as the longest (if s = abcbcd, abc should be the longest ) And lastly I know this question has been asked several times here already but i want to fix the code I came up with if possible, not just use someone else's code entirely.
has comment: http://stackoverflow.com/comment/89416845
favorite count: 0
tagged with: python-3.x
tagged with: longest-substring
possible better answer: http://stackoverflow.com/a/51217988
has answer: http://stackoverflow.com/a/51825073
answer count: 5
tagged with: python
has comment: http://stackoverflow.com/comment/89417064
score: 2
type: AnsweredQuestion
has title: Find the longest substring in alphabetical order. What is wrong with my code
downvote count: 0
has comment: http://stackoverflow.com/comment/89417369
has comment: http://stackoverflow.com/comment/89438571
tagged with: alphabetical
type: Question
upvote count: 2
has answer: http://stackoverflow.com/a/51217988
has comment: http://stackoverflow.com/comment/89416921

http://stackoverflow.com/a/51221582
type: Answer
has body: You can use collections.Counter and isolate items appearing only once. then use list comprehensions for your desired results. The solution is O(n) overall, although it involves 3 passes. x = ['Gaga', 'Gaga', 'Lam', 'Reem', 'Pal', 'Gaga','Lam'] from collections import Counter singles = {k for k, v in Counter(x).items() if v == 1} y = [i for i in x if i not in singles] loc = [int(i in singles) for i in x] print(y, loc, sep='\n') ['Gaga', 'Gaga', 'Lam', 'Gaga', 'Lam'] [0, 0, 0, 1, 1, 0, 0]
score: 0
answers question: http://stackoverflow.com/q/51221526

http://stackoverflow.com/comment/89327956
has text: I ended up avoiding this package. But it works great to install normal packages!
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/51171994

http://stackoverflow.com/q/51217704
type: UnansweredQuestion
has title: python Point-In-Polygon operation. Join gridded data with point data, based on those points falling inside the grid
has answer: http://stackoverflow.com/a/51377816
tagged with: dataframe
type: Question
answer count: 1
tagged with: python-xarray
score: 0
tagged with: geopandas
tagged with: geospatial
tagged with: python
has body: I want to know how to select values from the xarray DataArray based on the location (geo_df.geometry) and time (geo_df.plant_date &amp; geo_df.cut_date) of rows in the geopandas GeoDataFrame. I want to join them as 'features' in an output GeoDataFrame. My datasets: Packages I'm using: import numpy as np import pandas as pd import geopandas as gpd import matplotlib.pyplot as plt from shapely import geometry import xarray as xr I have a geodataframe storing lat/lon POINTS which corresponds to households. The index column is the id of the households. geo_df.head() Out[]: crop_name xxx cut_date plant_date geometry 0 SORGHUM 0.061029 2011-11-10 2011-11-10 POINT (37.89087631 14.35381619) 1 MILLET -0.104342 2011-10-19 2011-10-19 POINT (37.89087631 14.35381619) 2 SORGHUM -0.031697 2013-11-26 2013-11-26 POINT (37.89087631 14.35381619) I have an xarray object storing GRIDDED vegetation health data (NDVI). ndvi_df = xr.open_dataset(geo_data_dir+ndvi_dir).ndvi Out[]: &lt;xarray.DataArray 'ndvi' (time: 212, lat: 200, lon: 220)&gt; [9328000 values with dtype=float32] Coordinates: * lon (lon) float32 35.024994 35.074997 35.125 35.174988 35.22499 ... * lat (lat) float32 14.974998 14.924995 14.875 14.824997 14.775002 ... * time (time) datetime64[ns] 2000-02-14 2000-03-16 2000-04-15 ... Attributes: long_name: Normalized Difference Vegetation Index units: 1 _fillvalue: -3000 I have a geodataframe storing a POLYGON which corresponds to a country. world = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres')) ethiopia = world.loc[world["name"] == "Ethiopia"] Visual Summary: My datasets plotted on top of one another look as follows (plotted annually for demonstration purposes). (ndvi_df.loc[f'{year}-01-16T00:00:00.000000000':f'{year}-12-16T00:00:00.000000000'] .mean(dim='time') .plot(cmap='gist_earth_r', vmin=-0.1, vmax=1) ) ax = plt.gca() ethiopia.plot(alpha=0.2, color='black', ax=ax) (geo_df .loc[ (lsms_geo_1["cut_date"] &gt; f'{year}-01-01') &amp; (lsms_geo_1["cut_date"] &lt; f'{…

http://stackoverflow.com/comment/89410368
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51214599
has text: What is the logic behind what has a true department and what doesn't? Most are blank after joining the two dataframes.
score: 0

http://stackoverflow.com/a/51261571
has comment: http://stackoverflow.com/comment/89501220
answers question: http://stackoverflow.com/q/51261520
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/89501199
has comment: http://stackoverflow.com/comment/89501138
has body: Can you try doing python "C:\Users\Asus\Google Drive\Lifestyle\Technicals\Programming\Python\Python Scripts\Test.py" Command line does not like the " " (white space) character. Thus breaking your command. You need to cd directory in the correct directory or either execute your command wrapped in double quotes
has comment: http://stackoverflow.com/comment/101521033
accepted answer of: http://stackoverflow.com/q/51261520

http://stackoverflow.com/q/51202055
score: 2
has title: How to aggregate groups of only more than 1 in a pandas pivot table
upvote count: 2
type: Question
has answer: http://stackoverflow.com/a/51215297
has comment: http://stackoverflow.com/comment/89385473
answer count: 2
tagged with: pandas
has comment: http://stackoverflow.com/comment/89385674
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: pivot-table
has answer: http://stackoverflow.com/a/51202421
tagged with: python
has body: I have the following code but I only want to aggregate on groups of two or more: pivot = pd.pivot_table(pct, values = ['CERT'], index= 'ST', aggfunc={'CERT': [min, max, np.mean]}).reset_index(level = 0).set_index('ST', drop = False) Tried Grouper but realized later that this only worked for time series. Sample Data Input: ST CERT AL 8909 TX 9805 TX 7890 Sample Data Output: ST Min_Cert Max_Cert Mean_Cert TX 7890 9805 X As can be seen above only TX data is aggregated as it has more than two entries.

http://stackoverflow.com/q/51204269
upvote count: 3
linked to: http://stackoverflow.com/q/34663539
tagged with: scipy
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/51211708
tagged with: optimization
possible better answer: http://stackoverflow.com/a/51211708
has title: Scipy won't find the optimum (simple cosine function)
has answer: http://stackoverflow.com/a/51210934
downvote count: 0
has comment: http://stackoverflow.com/comment/89400300
favorite count: 0
has comment: http://stackoverflow.com/comment/89395170
accepted answer: http://stackoverflow.com/a/51210934
has comment: http://stackoverflow.com/comment/89390723
tagged with: python
type: AnsweredQuestion
score: 3
has body: I am trying to estimate the argument of a cosine function using the scipy optimizer (yes I am aware arc cos could be used, but I don't want to do that). The code + a demonstration: import numpy import scipy def solver(data): Z=numpy.zeros(len(data)) a=0.003 for i in range(len(data)): def minimizer(b): return numpy.abs(data[i]-numpy.cos(b)) Z[i]=scipy.optimize.minimize(minimizer,a,bounds=[(0,numpy.pi)],method="L-BFGS-B").x[0] return Z Y=numpy.zeros(100) for i in range(100): Y[i]=numpy.cos(i/25) solver(Y) The result is not good, when the argument of the cos function reaches values above 2, the estimation "skips over" the values and returns the maximum argument value instead. array([0. , 0.04 , 0.08 , 0.12 , 0.16 , 0.2 , 0.24 , 0.28 , 0.32 , 0.36 , 0.4 , 0.44 , 0.48 , 0.52 , 0.56 , 0.6 , 0.64 , 0.67999999, 0.72 , 0.75999999, 0.8 , 0.83999999, 0.88 , 0.92 , 0.95999999, 1. , 1.04 , 1.08 , 1.12 , 1.16 , 1.2 , 1.24 , 1.28 , 1.32 , 1.36 , 1.4 , 1.44 , 1.48 , 1.52 , 1.56 , 1.6 , 1.64 , 1.68 , 1.72 , 1.76 , 1.8 , 1.84 , 1.88 , 1.91999999, 1.95999999, 2. , 2.04 , 3.14159265, 3.14159265, 3.14159265, 3.14159265, 3.14159265, 3.14159265, 3.14159265, 3.14159265,... What causes this phenomenon? Are there some other optimizers/ settings that could help with the issue?
has comment: http://stackoverflow.com/comment/89400143

sphinx-apidoc
tag name: sphinx-apidoc
tags question: http://stackoverflow.com/q/51300744
type: Tag

http://stackoverflow.com/comment/89545008
type: QuestionComment
has text: please edit your question with correct indentation and we will try and help
comment on: http://stackoverflow.com/q/51283811
score: 0
type: Comment

http://stackoverflow.com/comment/89364828
type: QuestionComment
has text: well there is no module called `networkx`. If you try to run `myclass.py` you'll get the same error. It's nothing to do with import myclass into myscript.
score: 0
comment on: http://stackoverflow.com/q/51191627
type: Comment

http://stackoverflow.com/comment/89403466
comment on: http://stackoverflow.com/q/51210929
type: Comment
has text: its not working Mufeed . I tried it , the output of string aftr tokenize could not compared. at least i m unable to do so , can u look into code ?
score: 0
type: QuestionComment

http://stackoverflow.com/comment/89347627
has text: You miscopied the code from the book - you have `lab.grid()` twice, the second one should be `ent.grid()`.
score: 3
comment on: http://stackoverflow.com/q/51182470
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51225292
tagged with: file
tagged with: loops
upvote count: 1
answer count: 1
accepted answer: http://stackoverflow.com/a/51225461
tagged with: conditional-statements
tagged with: if-statement
has comment: http://stackoverflow.com/comment/89431076
has title: Python writing a .txt file
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89431091
downvote count: 0
score: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/89430951
has answer: http://stackoverflow.com/a/51225461
type: Question
tagged with: python
linked to: http://stackoverflow.com/q/5214578
has body: print('Welcome, I am Sam. I am ABMs personal assistant, today we will be pooling tips together!') file = open(“tipsdate.txt”,”w”) name=str(input('Who do I have the pleasure of working with? ')) tips=int(input('How many tips did we collect today? ')) workers=int(input('How many people worked today? ')) cars=int(input('How many cars did we park today?')) if workers == 1: print('Worker 1 earned $',tips) elif workers == 2: a=int(input('How many hours did worker 1 work? ')) b=int(input('How many hours did worker 2 work? ')) totalhrs=a+b tipsa= (a/totalhrs)* tips tipsb= (b/totalhrs)*tips print('Worker one earned $',tipsa) print('Worker two earned $',tipsb) elif workers == 3: a=int(input('How many hours did worker 1 work? ')) b=int(input('How many hours did worker 2 work? ')) c=int(input('How many hours did worker 3 work? ')) totalhrs=a+b+c tipsa= (a/totalhrs)* tips tipsb= (b/totalhrs)*tips tipsc= (c/totalhrs)*tips print('Worker one earned $',tipsa) print('Worker two earned $',tipsb) print('Worker three earned $',tipsc) elif workers == 4: a=int(input('How many hours did worker 1 work? ')) b=int(input('How many hours did worker 2 work? ')) c=int(input('How many hours did worker 3 work? ')) d=int(input('How many hours did worker 4 work? ')) totalhrs=a+b+c+d tipsa= (a/totalhrs)* tips tipsb= (b/totalhrs)*tips tipsc= (c/totalhrs)*tips tipsd= (d/totalhrs)*tips print('Worker one earned $',tipsa) print('Worker two earned $',tipsb) print('Worker three earned $',tipsc) print('Worker four earned $', tipsd) elif workers &gt; 4: print('I am not programmed to calculate tips beyond 4 workers, I am a work in progress!') cartips=tips/cars print('Our tips per car average today was $ ',cartips) file.close() print('Thank you for your help',name,'I hope we work together again soon! :) ') Hi there, thanks for taking your time to help me. I am an amateur, self taught python coder. I am trying to figure out how to write a .txt file with conditional loops and various user inputs. I realize that th…

http://stackoverflow.com/q/51241197
tagged with: python
has answer: http://stackoverflow.com/a/51241274
has answer: http://stackoverflow.com/a/51241365
downvote count: 3
has answer: http://stackoverflow.com/a/51241446
has comment: http://stackoverflow.com/comment/89461292
answer count: 5
type: UnansweredQuestion
has title: How to change a nested list's list into a string?
score: -3
upvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/51241431
has answer: http://stackoverflow.com/a/51241501
type: Question
has body: For example, if my nested list is: [['2HC'], ['4BB'], ['4BB'], ['2HC']] How would I have the ['2HC']'s refer to 'A' and the ['4BB']'s refer to 'B', so that my result would be: ['A', 'B', 'B', 'A']

http://stackoverflow.com/comment/89378155
comment on: http://stackoverflow.com/a/51198108
score: 0
type: AnswerComment
type: Comment
has text: @juanpa.arrivillaga sounds good, I will try that. Appreciate the advice.

http://stackoverflow.com/comment/89348496
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51183014
score: 1
has text: so if there is no assertion error message, maybe the sheet really is open. But maybe not because an error was raised which stopped execution. What happens if put try: the line before spread_sheet= (which now gets indented) and after it put except gspread.SpreadsheetNotFound as fnf_error: and then on the next line print fnf_error?

http://stackoverflow.com/a/51261250
type: Answer
score: 7
answers question: http://stackoverflow.com/q/51261111
has comment: http://stackoverflow.com/comment/89529353
upvote count: 7
has comment: http://stackoverflow.com/comment/89538563
has body: 1==0 &lt;= 1/0 1/0 is never evaluated. The expression triggers chained comparison in Python. It is evaluated as: (1 == 0) and (0 &lt;= 1/0) Logical and short-circuits when a False value is reached, so the second condition is never tested. Since 1 == 0 evaluates to False, the result is False. 1==1 &lt;= 1/0 In the same vein, this is evaluated as: (1 == 1) and (1 &lt;= 1/0) Since the first expression is True, the second one is evaluated. This leads to ZeroDivisionError. (1==0) &lt;= 1/0 Parentheses have higher priority than comparison operators. So chained comparisons are not triggered here. The expression is evaluated as False &lt;= 1/0. Of course, the comparison will fail with ZeroDivisionError. 1==1 &lt;= 1/1, 1==0 &lt;= 1/1 Here you are defining a tuple of results. A tuple is implicit by the existence of a comma separating your two expressions. The first, 1==1 &lt;= 1/1, evaluates to True since True &lt;= 1. The second, 1==0 &lt;= 1/1, evaluates to True since False &lt;= 1. These comparisons work since bool is a subclass of int, so True is equivalent to 1 and False is equivalent to 0.
has comment: http://stackoverflow.com/comment/89500522
has comment: http://stackoverflow.com/comment/89500559
downvote count: 0
has comment: http://stackoverflow.com/comment/89537999

http://stackoverflow.com/q/51239251
type: Question
upvote count: 46
tagged with: concurrency
has body: I'm learning about python concurrency and I was introduced with the concept of futures. I read that as_completed() takes an iterable of futures and yields them as they are done. I want to know how it works internally. Is it yielding completed tasks (futures) immediately? A naive approach would be to iterate all futures and examine each and every future using done(), but this is inefficient. So what's the magic behind this function? Thanks!
downvote count: 0
answer count: 1
tagged with: concurrent.futures
favorite count: 0
tagged with: python-3.x
tagged with: python
has answer: http://stackoverflow.com/a/51239587
accepted answer: http://stackoverflow.com/a/51239587
type: AnsweredQuestion
tagged with: multithreading
has title: How does concurrent.futures.as_completed work?
score: 46

http://stackoverflow.com/comment/89629567
has text: @MitchellWalls thank you for your help, I forgot the `name` attribute for my input objects. Everything is working fine now.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51311861

http://stackoverflow.com/comment/89518902
score: 3
has text: Following up on @MSeifert's comment, `np.logical_and.reduce((red_mask, green_mask, blue_mask))` would do what you're expecting.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51270309

http://stackoverflow.com/q/51206933
tagged with: hive
tagged with: syntax
has answer: http://stackoverflow.com/a/51207358
has title: Use python 3 to connect to hive
accepted answer: http://stackoverflow.com/a/51207358
type: AnsweredQuestion
downvote count: 0
possible better answer: http://stackoverflow.com/a/56782673
score: 1
has answer: http://stackoverflow.com/a/56782673
favorite count: 0
has body: i am trying to access hive using python 3.7 i am using pyhive to do it when i try to use pyhive in python 3.7 i am getting the following error from pyhive import hive Traceback (most recent call last): File "code_sample.py", line 2, in <module> import pyhive.hive File "/usr/local/lib/python3.7/site-packages/pyhive/hive.py", line 337 def execute(self, operation, parameters=None, async=False): ^ SyntaxError: invalid syntax but when i do the same in python 2.6 version i am not facing any errors can you please help me with this, if its not possible with pyhive can you suggest some better options to connect to hive with python 3.6 or 3.7
type: Question
answer count: 2
upvote count: 1
tagged with: python

http://stackoverflow.com/q/51230874
answer count: 1
downvote count: 0
tagged with: keras
favorite count: 0
has answer: http://stackoverflow.com/a/51233784
accepted answer: http://stackoverflow.com/a/51233784
has body: Let's say one wants to train two slightly different networks simultaneously with the same dataset. A way to go is through the functional API: https://keras.io/getting-started/functional-api-guide/. Here is how it would work on a simple architecture (just two multilayer dense networks with same input/output): same_input = Input(shape=(n_feat, ), name='input') x = Dense(n_feat//2, kernel_initializer='uniform', activation='relu')(same_input) x = Dense(n_feat//128, kernel_initializer='uniform', activation='elu')(x) x = Dropout(dropout_val)(x) x = BatchNormalization()(x) x = Dense(n_feat//256, kernel_initializer='uniform', activation='relu')(x) x_out = Dense(out_dim, kernel_initializer='normal', name='output_x')(x) y = Dense(n_feat//2, kernel_initializer='uniform', activation='relu')(same_input) y = Dropout(dropout_val)(y) y = Dense(n_feat//128, kernel_initializer='uniform', activation='elu')(y) .... (some difference) y = Dropout(dropout_val)(y) y = BatchNormalization()(y) y_out = Dense(out_dim, kernel_initializer='uniform', name='output_y')(y) model = Model(inputs=same_input, outputs=[x_out, y_out]) model.compile(optimizer='rmsprop', loss={'output_x': 'mean_squared_error', 'output_y': 'mean_absolute_error'}, loss_weights={'output_x': 1, 'output_y': 1.}) model.fit({'input': X}, {'output_x': Y, 'output_x': Y}, epochs=fit_pars['num_ep'], batch_size=b_size, validation_split=valid_split, callbacks=callbacks, verbose=2) network_predict = np.array(model.predict(X_test, batch_size=b_size)) However, I am not absolutely sure whether this is correct, and whether there is a way to do it right on Keras. The total loss that is used to optimize the network will be the sum of the two losses, and that imposes an interference between the two networks. Can someone tell if this is right or wrong, and whether there is a way to train the networks independently yet concurrently?
tagged with: python
score: 2
type: AnsweredQuestion
tagged with: tensorflow
type: Question
has title: Training two networks simultaneously with keras
upvote count: 2

http://stackoverflow.com/comment/89527829
comment on: http://stackoverflow.com/q/51274541
has text: Writing log records to a queue is possible by attaching a `QueueHandler` to the logger; I would then init and start a `QueueListener`, passing the same queue to the listener that was passed to `QueueHandler`. However, all file handlers from stdlib keep logfile opened as you've already found out; you will have to write a custom `FileHandler` impl that opens the file on emit and closes it immediately after the emit is done. Then pass an instance of the custom handler on `QueueListener` init and you should be good to go.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51281619
score: 4
favorite count: 0
tagged with: python
type: UnansweredQuestion
has body: Say there is a file tree of: sample_module |___ file1.py |___ file2.py How can I get file2's __file__, from a function in file1? file1.py: def get_file_path(): return __file__ file2.py from sample_module.file1 import get_file_path print(get_file_path()) # C:/.../sample_module/file1.py How can I make it give me C:/.../file2.py? I understand that the function get_file_path is saving the __file__ into its namespace, and is not generating a new __file__. Is there a way to make __file__ callable, or get the __file__ at runtime? Why I need it? I have a library, with a logging module, that generates a logger. I want the location of that logger to be e.g. 2 folders above file importing generate_logger. I'd rather not the user have to specify __file__ each time they want to use it. Is there a better way? i.e. in mylibrary/logs.py def generate_logger(logname=__name__, level=logging.DEBUG, path=''): """Creates a logger instance. Set level of file handler. """ logger = logging.getLogger(logname) if path == '': path = os.path.abspath(os.path.join(os.path.dirname(__file__), '../../logs')) fh = logging.FileHandler(f'{path}/{logname}.log') ## rest of logging code. return logger - project |___ project | |__ log | |__ loads_generate_logger (code that does the import) |_______logs |_logname.log (creates a log folder 2 folders above where it was imported). in loads_generate_logger from mylibrary import generate_logger() logger = generate_logger() # logger path = C:/.../venv/lib/site-packages/mylib-0.10/logs
has comment: http://stackoverflow.com/comment/89540746
has answer: http://stackoverflow.com/a/51281765
has comment: http://stackoverflow.com/comment/89541010
has title: Get __file__ of the IMPORTING file
type: Question
upvote count: 4
has comment: http://stackoverflow.com/comment/89540619
answer count: 1
downvote count: 0

http://stackoverflow.com/a/51196652
has comment: http://stackoverflow.com/comment/89446166
has body: import multiprocessing import subprocess def executeCommand(exeArgs, output): commandProcess = subprocess.Popen(exeArgs.split(), stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = commandProcess.communicate() output.put(out) command = "Your command Here" output = multiprocessing.Queue() p = multiprocessing.Process(target=executeCommand, args=(command, output) ) p.start() p.join() #print output.get() As you can see the last line is commented. That way I don't show anything in the terminal, but if you want to print it you always can uncomment it. I think that is what you want.
accepted answer of: http://stackoverflow.com/q/51195951
score: 0
has comment: http://stackoverflow.com/comment/89421869
answers question: http://stackoverflow.com/q/51195951
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/89437920

http://stackoverflow.com/comment/89367884
has text: No CMS. according to actual flow work , such request -> approval by p1 -> approval by p2 -> flow work end. user make flow chart based workflow engine, it creates workflow automaticly.
comment on: http://stackoverflow.com/q/51192402
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51303187
has body: Assuming a list of dictionaries, the goal is to iterate through all the distinct values in all the dictionaries. Example: d1={'a':1, 'c':3, 'e':5} d2={'b':2, 'e':5, 'f':6} l=[d1,d2] The iteration should be over 1,2,3,5,6, does not matter if it is a set or a list.
favorite count: 0
has answer: http://stackoverflow.com/a/51303248
possible better answer: http://stackoverflow.com/a/51303233
has answer: http://stackoverflow.com/a/51303270
tagged with: python
accepted answer: http://stackoverflow.com/a/51303270
tagged with: dictionary
type: AnsweredQuestion
upvote count: 2
downvote count: 2
tagged with: value-iteration
type: Question
has answer: http://stackoverflow.com/a/51303233
answer count: 6
has title: Iterate through all distinct dictionary values in a list of dictionaries
has answer: http://stackoverflow.com/a/51303362
score: 0
has answer: http://stackoverflow.com/a/51303515
has answer: http://stackoverflow.com/a/51303369

http://stackoverflow.com/comment/89481170
has text: Please post a [minimal, complete and verifiable example](https://stackoverflow.com/help/mcve).
type: Comment
type: QuestionComment
score: 3
comment on: http://stackoverflow.com/q/51250644

http://stackoverflow.com/a/51280508
downvote count: 0
score: 3
has body: I can define more kernels just by changing the parameters such as theta,lamda that is frequency and orientation.I can generate Gabor filter bank then I will apply various machine learning algorithm for classification. code after batch processing: import cv2 import os import glob import numpy as np img_dir = "C://Users//USER//Pictures//Saved Pictures" data_path = os.path.join(img_dir,'*g') files = glob.glob(data_path) data = [] for f1 in files: img = cv2.imread(f1,0) data.append(img) img = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)[1] ret, labels = cv2.connectedComponents(img) label_hue = np.uint8(179*labels/np.max(labels)) blank_ch = 255*np.ones_like(label_hue) labeled_img = cv2.merge([label_hue, blank_ch, blank_ch]) labeled_img = cv2.cvtColor(labeled_img, cv2.COLOR_HSV2BGR) labeled_img[label_hue==0] = 0 cv2.imshow('labeled.png', labeled_img) cv2.waitKey() def build_filters(): filters = [] ksize = 31 for theta in np.arange(0, np.pi, np.pi / 16): kern = cv2.getGaborKernel((ksize, ksize), 4.0, theta, 10.0, 0.5, 0, ktype=cv2.CV_32F) kern /= 1.5*kern.sum() filters.append(kern) return filters def process(img, filters): accum = np.zeros_like(img) for kern in filters: fimg = cv2.filter2D(img, cv2.CV_8UC3, kern) np.maximum(accum, fimg, accum) return accum filters=build_filters() res1=process(img,filters) cv2.imshow('result',res1) cv2.waitKey(0) cv2.destroyAllWindows() cv2.imwrite("checking.tif",res1)
answers question: http://stackoverflow.com/q/51277949
upvote count: 3
type: Answer

http://stackoverflow.com/comment/89686766
score: 0
has text: Error logging and process counters are always used in processes. Consecutive calls do not increase performance, only the execution priority of your process. I think friends who wrote the module missed this point.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51210305

http://stackoverflow.com/comment/89459975
has text: Cool. As easy as genial. I will time it. Thank you!
type: AnswerComment
comment on: http://stackoverflow.com/a/51240579
score: 0
type: Comment

http://stackoverflow.com/q/51264210
has comment: http://stackoverflow.com/comment/89506747
upvote count: 1
has answer: http://stackoverflow.com/a/51264786
tagged with: python
has comment: http://stackoverflow.com/comment/89507267
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89521816
has body: I am trying to compare two nested lists of strings with each other and searching for the fastest way possible. To do that I am currently calculating the Jaccard-index (intersection / union) between each of the elements of the nested lists. Example: list1=[["abc","def","ghi"],["jkl","mno"]] list2=[["pqr","def","stu"],["jkl","mno","vwx"]] In this example, the first "cluster" of the first list is compared with each of the cluster of the second list, which results in 4 (2*2) different jaccard indeces. However, my problem is, that my two lists each contain about 500.000 clusters/elements (sublists) each. With my current code, it will take me about 2 weeks to compute. At this point I am not able decrease the computing time and asking for help. Current code: for i1 in list1: for i2 in list2: intersection = set(i1) &amp; set(i2) union = set(i1) | set(i2) jaccard = (len(intersection) / len(union)) * 100 if jaccard &gt; 1: #write to file....
has comment: http://stackoverflow.com/comment/89506648
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/89506866
tagged with: comparison
has comment: http://stackoverflow.com/comment/89506712
type: Question
has comment: http://stackoverflow.com/comment/89507213
has comment: http://stackoverflow.com/comment/89506596
answer count: 1
has title: Fast way of comparing nested lists of strings
has comment: http://stackoverflow.com/comment/89507087
tagged with: optimization

http://stackoverflow.com/comment/89571526
type: QuestionComment
comment on: http://stackoverflow.com/q/51297121
type: Comment
has text: Also please explain what you mean by "won't compute".
score: 1

http://stackoverflow.com/comment/89690475
has text: python -c "with open('D:\Project\text.evt.gz', 'rb') as f: print(f.read1(2)). output is pk
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51173274
type: Comment

http://stackoverflow.com/comment/89399705
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51209015
has text: `RUN python3 manage.py runserver 0.0.0.0:8000 &` will not do what you expect it to do. Each `RUN` instruction is executed as its own container; once conpleted, the container stops and changes are written in a separate layer of the built image. So, the server starts, but the `RUN` command exits immediately, so the cobtainer is stopped, the layer is committed, and a new container starts for running `pytest` command, with no Django server running.
score: 0

http://stackoverflow.com/a/54277645
has comment: http://stackoverflow.com/comment/117792369
type: Answer
has comment: http://stackoverflow.com/comment/117799445
has comment: http://stackoverflow.com/comment/95415831
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/117791756
has body: Maybe already be too late, but what you need to do is send a message directly to the channel or group the application is listening to. Channels will route your message to the appropriate consumer method. So assuming you want to call the send_message method in the consumer serving your other app(say channel1): you should do this: from channels.layers import get_channel_layer from asgiref.sync import async_to_sync channel_layer = get_channel_layer() sync_to_async(channel_layer.send)("channel1", { "type": "send.message", "text": "Hello there!", }) This can be done, anywhere in your code. The question you linked uses tornado websockets which is quite different from Django channels. I don't know if it is possiblle using tornado but it definitely is, using Channels
has comment: http://stackoverflow.com/comment/117788405
accepted answer of: http://stackoverflow.com/q/51251515
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51251515
has comment: http://stackoverflow.com/comment/117783232

amazon-elastic-beanstalk
tag name: amazon-elastic-beanstalk
type: Tag
tags question: http://stackoverflow.com/q/51265595

http://stackoverflow.com/comment/89501083
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51261361
type: AnswerComment
has text: I think you're right about standard methods being more efficient, but regex gives you more flexibility. For example, your answer would return a closing bracket if there was any character after the final closing bracket

http://stackoverflow.com/q/51240243
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89459431
downvote count: 2
has title: Ranking in python
type: Question
accepted answer: http://stackoverflow.com/a/51240390
tagged with: python-3.6
tagged with: rank
tagged with: ranking
possible better answer: http://stackoverflow.com/a/51240619
answer count: 2
upvote count: 0
has answer: http://stackoverflow.com/a/51240619
favorite count: 0
tagged with: python
score: -2
has comment: http://stackoverflow.com/comment/89459612
has body: Good day guys, I am struggling to write a function to rank numbers. The code is working but two things ain't working well. We know if two numbers are the same, they get the same position (or rank) but from my code, the two same numbers have different rankings. Also when it gets to 21st, the code prints 21th in instead of 21st. How can I solve this issue. This the code a = [20,50,67,100,93,89,72,81,79,66,49,73,29,50,52,69,71,70,71,84,67] def ranker(zed): prefixes = ["st", "nd", "rd" ,"th"] zed.sort(reverse =True) found = [ ] for dig in zed: pre = len(found) + 1 if len(found) &gt; 3: found.append(str(dig) + " " + str(pre) + prefixes[ 3 ]) else: found.append(str(dig) + " " + str(pre) + prefixes[ len(found) ]) print(found) ranker(a)
has answer: http://stackoverflow.com/a/51240390

http://stackoverflow.com/comment/107807903
has text: For future readers of this thread. Mouse-over with Selenium python bindings (stackoverflow.com/a/8261754/9083077) describes the soltuion with ActionChains.
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51251328
score: 2

code-generation
tag name: code-generation
tags question: http://stackoverflow.com/q/51227947
type: Tag

http://stackoverflow.com/comment/89367806
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/51177430
type: Comment
has text: I can actually make the executable but I get about 90 of the above missing module error

http://stackoverflow.com/comment/89492412
type: Comment
comment on: http://stackoverflow.com/q/51256738
score: 2
has text: Try running `export OPENBLAS_NUM_THREADS=1` from the command line.
type: QuestionComment

http://stackoverflow.com/q/51227077
has comment: http://stackoverflow.com/comment/89435375
tagged with: python
has comment: http://stackoverflow.com/comment/89434191
has title: Django 2.0 use ORM in Python script in parent directory of django folder
type: UnansweredQuestion
tagged with: django
has body: I have the following structure for my project: . ├── py_file_i_want_to_use_core_models_in.py ├── web_app ├── core │ ├── __init__.py │ ├── __pycache__ │ ├── admin.py │ ├── apps.py │ ├── core_settings.py │ ├── forms.py │ ├── migrations │ ├── models.py │ ├── static │ ├── templates │ ├── tests.py │ ├── urls.py │ └── views.py ├── web_app │ ├── __init__.py │ ├── __pycache__ │ ├── settings.py │ ├── urls.py │ └── wsgi.py └── manage.py I want to access some models define in web_app/core/models.py from inside the python script py_file_i_want_to_use_core_models_in.py but I cant seem to get the code I am finding to work: Here is what I am trying: import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "web_app.web_app.settings") import django django.setup() But these imports give me the following error: ModuleNotFoundError: No module named 'core' Any ideas on how I can solve this issue?
type: Question
tagged with: django-models
has comment: http://stackoverflow.com/comment/89434247
answer count: 1
score: 0
has answer: http://stackoverflow.com/a/51227163

http://stackoverflow.com/comment/89619257
has text: You mean the table name inside each subsheet?
type: QuestionComment
comment on: http://stackoverflow.com/q/51319407
score: 0
type: Comment

http://stackoverflow.com/a/51307914
has body: You have to create the menu in the slot and use the position to obtain the data through indexAt() that returns the QModelIndex ... self.ui_search = QtGui.QLineEdit() # lay main lay_main = QtGui.QVBoxLayout() lay_main.addWidget(self.ui_search) lay_main.addWidget(self.ui_table) self.setLayout(lay_main) # connections self.ui_table.customContextMenuRequested.connect(self.open_context_menu) def open_context_menu(self, point): context_menu = QtGui.QMenu() ix = self.ui_table.indexAt(point) val = ix.data() context_menu.addAction("Search: {}".format(val)) action = context_menu.exec_(self.ui_table.mapToGlobal(point)) if action: self.ui_search.setText(val)
score: 1
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/51306366
upvote count: 1
answers question: http://stackoverflow.com/q/51306366

lemmatization
type: Tag
tag name: lemmatization
tags question: http://stackoverflow.com/q/51267166

http://stackoverflow.com/a/51223939
has body: I am not sure if this is the best solution, but it gets the job done. import re try: from itertools import zip_longest except ImportError: from itertools import izip_longest as zip_longest def grouper(n, iterable, fillvalue=None): args = [iter(iterable)] * n return zip_longest(fillvalue=fillvalue, *args) def split_by_date(input_data): splitted = re.split(r'([0-9]{2}:[0-9]{2} (AM|PM))', input_data) splitted.remove('') return ['{}{}'.format(a, c).strip() for a, _, c in grouper(3, splitted)] Sample usage: &gt;&gt;&gt; split_by_date('01:00 AM ART Partly Cloudy 14C 01:00 PM ART Mostly Sunny 25C 06:00 PM ART Mostly Cloudy 23C') ['01:00 AM ART Partly Cloudy 14C', '01:00 PM ART Mostly Sunny 25C', '06:00 PM ART Mostly Cloudy 23C'] &gt;&gt;&gt; split_by_date('01:35 PM some very random string 16:65 AM Yet another string') ['01:35 PM some very random string', '16:65 AM Yet another string'] The try block is just to ensure python2/3 compatibility. The grouper function is a recipe from the itertools module documentation (https://docs.python.org/3/library/itertools.html#itertools-recipes). Edit I was able to get rid of the grouper function by changing the regex a little and using itertools.islice. I hope it makes the code more legible. import re from itertools import islice def split_by_date(input_data): splitted = re.split(r'([0-9]{2}:[0-9]{2} AM|[0-9]{2}:[0-9]{2} PM)', input_data) splitted.remove('') iter_a = islice(splitted, 0, None, 2) iter_b = islice(splitted, 1, None, 2) return ['{}{}'.format(a, b).strip() for a, b in zip(iter_a, iter_b)] Usage is the same.
answers question: http://stackoverflow.com/q/51223511
has comment: http://stackoverflow.com/comment/89428328
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/89428257

http://stackoverflow.com/a/51191398
type: Answer
has comment: http://stackoverflow.com/comment/89365055
has body: This is possible by passing the scatter a color as found here in the documentation. import plotly.graph_objs as go from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot init_notebook_mode(connected=True) data = [ go.Scatter( y=[5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5], marker=dict( size=16, cmax=39, cmin=0, color=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39], colorbar=dict( title='Colorbar' ), colorscale='Viridis' ), mode='markers') ] fig = go.Figure(data=data) iplot(fig) There are a few built in colorscale options: 'Blackbody', 'Bluered', 'Blues', 'Earth', 'Electric', 'Greens', 'Greys’, 'Hot', 'Jet', 'Picnic', 'Portland', 'Rainbow', 'RdBu', 'Reds', 'Viridis', 'YlGnBu', 'YlOrRd' You also have the ability to create your own colorscale. As per the documentation: Sets the colorscale and only has an effect if marker.color is set to a numerical array. The colorscale must be an array containing arrays mapping a normalized value to an rgb, rgba, hex, hsl, hsv, or named color string. At minimum, a mapping for the lowest (0) and highest (1) values are required. For example, [[0, 'rgb(0,0,255)', [1, 'rgb(255,0,0)']]. To control the bounds of the colorscale in color space, use marker.cmin and marker.cmax. Alternatively, colorscale may be a palette name string of the following list: Greys, YlGnBu, Greens, YlOrRd, Bluered, RdBu, Reds, Blues, Picnic, Rainbow, Portland, Jet, Hot, Blackbody, Earth, Electric, Viridis, Cividis
answers question: http://stackoverflow.com/q/51187704
has comment: http://stackoverflow.com/comment/89365324
score: 0

http://stackoverflow.com/q/51251217
answer count: 0
has comment: http://stackoverflow.com/comment/89481432
has title: How to I convert a sqlite command to a python-sqlite command
linked to: http://stackoverflow.com/q/4253804
type: Question
has comment: http://stackoverflow.com/comment/89481402
linked to: http://stackoverflow.com/q/228912
score: 0
duplicate of: http://stackoverflow.com/q/228912
tagged with: sqlite
type: UnansweredQuestion
has body: How would I implement the following command in python: ALTER TABLE {tableName} ADD COLUMN COLNew {type}; Taken from this post I assume it would look something like the following: cursor.execute('ALTER TABLE my_table ADD COLUMN COLNEW ... ??? The problem is there are lots of sqlite tutorials for python and lots of sqlite examples. How does one convert a sqlite command to python?
has comment: http://stackoverflow.com/comment/89481361
tagged with: python

http://stackoverflow.com/comment/89325885
type: AnswerComment
score: 0
type: Comment
has text: In each row, will be same column be a number? Choosing *which column* to convert is likely beyond the scope of your question. I'd advise you [post a new question](https://stackoverflow.com/questions/ask) with *exactly* the scenario you want to handle.
comment on: http://stackoverflow.com/a/51170797

http://stackoverflow.com/comment/89514685
comment on: http://stackoverflow.com/q/51268204
has text: _"After resizing your window frame, tkinter will fail to resize widgets if you have assigned a non zero weight to non existent columns."_ - that's not true. Tkinter doesn't fail in this case, it simply doesn't do what you might expect. However, it's behaving exactly as it's documented to behave.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89476511
type: Comment
type: QuestionComment
has text: So someone is sending you text over discord and you want to convert that to a list? Can you ask that person to use a more standard formatting, such as json?
comment on: http://stackoverflow.com/q/51248718
score: 1

http://stackoverflow.com/comment/92281416
type: Comment
has text: Please add more explanation to your answer
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/52675860

http://stackoverflow.com/q/51235056
score: 22
has answer: http://stackoverflow.com/a/54159400
answer count: 2
has title: VS Code - Rename symbol too slow for Python
has comment: http://stackoverflow.com/comment/89449289
favorite count: 0
has answer: http://stackoverflow.com/a/68948102
has comment: http://stackoverflow.com/comment/89484442
has comment: http://stackoverflow.com/comment/89484500
has comment: http://stackoverflow.com/comment/89449242
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89449061
tagged with: python
has body: I'm having this refactoring issue where I try to rename a function through the option "Rename symbol", but it will take a long time. There's a "progress bar" moving endlessly below the document tab. It is taking around 5 min to do the renaming (also with variable names). Is this a normal behaviour? I have about 10 python files in the same folder of around ~100 lines. BUT, I have a data folder (belonging to the project) with some 100,000 txt files (which is ignored by git, btw). Are this documents also taken into account? Is there a way to only rename in current file? VS Code version: 1.25.0 Python extension: 2018.6.0 Thanks, Rafa
upvote count: 22
downvote count: 0
has comment: http://stackoverflow.com/comment/89448999
type: Question
tagged with: visual-studio-code
tagged with: rename

http://stackoverflow.com/comment/89567867
score: 2
has text: Thanks for asking this, I have the same question! Hopefully we get a solution.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51294999

http://stackoverflow.com/comment/89603499
type: Comment
comment on: http://stackoverflow.com/a/51313375
score: 1
type: AnswerComment
has text: Seems to me like a prime candidate for a [defaultdict](https://docs.python.org/2/library/collections.html#collections.defaultdict)

http://stackoverflow.com/q/51320743
tagged with: f-string
score: 1
possible better answer: http://stackoverflow.com/a/51321391
upvote count: 2
answer count: 3
has body: With an f-string you can fill in 'placeholders' in a string directly with some variable value. Opposed to, let's say using the str.format() method, often seen. Example: In [1]: x=3 In [2]: y=4 In [3]: print(f'The product of {x} and {y} is {x*y}.') The product of 3 and 4 is 12. Is this concept of f-strings only found in python? Or is there any other language that supports this, maybe under a different name?
tagged with: language-concepts
has title: Are f-strings a unique feature to python (3.6 and higher)?
favorite count: 0
has answer: http://stackoverflow.com/a/51321240
accepted answer: http://stackoverflow.com/a/51321240
tagged with: python
has answer: http://stackoverflow.com/a/51321391
type: AnsweredQuestion
tagged with: python-3.x
downvote count: 1
has answer: http://stackoverflow.com/a/51321667
type: Question

http://stackoverflow.com/q/51209343
has answer: http://stackoverflow.com/a/51209537
type: Question
tagged with: opencv
tagged with: numpy
answer count: 2
tagged with: keras
favorite count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89442190
score: 2
has answer: http://stackoverflow.com/a/52934614
tagged with: conv-neural-network
has comment: http://stackoverflow.com/comment/89399614
upvote count: 3
has title: Preprocessing of a single image for prediction. ( CNN build and trained with Keras)
has body: Had a lack of understanding how to make a single prediction with existing trained model( keras Sequential. The preprocessing and training of CNN looked like this: from keras.preprocessing.image import ImageDataGenerator train_datagen = ImageDataGenerator(rescale=1./255, shear_range=0.2, zoom_range=0.2, horizontal_flip=True) test_datagen = ImageDataGenerator(rescale=1./255) training_set = train_datagen.flow_from_directory('dataset/training_set', target_size=(64, 64), batch_size=32, class_mode='binary') test_set = test_datagen.flow_from_directory('dataset/test_set', target_size=(64, 64), batch_size=32, class_mode='binary') classifier.fit_generator(training_set, steps_per_epoch=8000, epochs=25, validation_data=test_set, validation_steps=2000) As the predict_generator did not work I stucked...
downvote count: 1

http://stackoverflow.com/q/51207093
tagged with: python
has answer: http://stackoverflow.com/a/51211218
score: 0
tagged with: tensorflow
type: Question
tagged with: neural-network
answer count: 2
has title: Bias initializer for Multi-Layer Perceptron
has body: I have written my own Multi-Layer Perceptron in TensorFlow, in which I initialize the weights and biases like this: # Store layers weight &amp; bias weights = { 'h1': tf.Variable(tf.random_normal([n_input, hidden_layer_sizes[0]], 0, 0.1, seed=random_state)), # 1 hidden layer is mandatory } biases = { 'b1': tf.Variable(tf.random_normal([hidden_layer_sizes[0]], 0, 0.1, seed=random_state)), } for i in range(len(hidden_layer_sizes)-1): weights['h'+str(i+2)] = tf.Variable(tf.random_normal([hidden_layer_sizes[i], hidden_layer_sizes[i+1]], 0, 0.1, seed=random_state)) biases['b'+str(i+2)] = tf.Variable(tf.random_normal([hidden_layer_sizes[i+1]], 0, 0.1, seed=random_state)) weights['out'] = tf.Variable(tf.random_normal([hidden_layer_sizes[-1], n_classes], 0, 0.1, seed=random_state)) biases['out'] = tf.Variable(tf.random_normal([n_classes], 0, 0.1, seed=random_state)) The number of hidden layers varies between 1 and 4, depending on the input. I have been reading on the Internet about alternative ways of initializing the weights, and I wonder if they are applicable in the MLP model or only in more complex models like CNNs. For example, the Xavier, the HE, the variance-scaled initialization etc. Does any of the alternative initializers are applicable in my case and which one is considered the best for this type of network?
tagged with: perceptron
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51207457

http://stackoverflow.com/comment/89487908
has text: It depends what you call buit-in. There are implementation of aho-corasick algorithm in python that would give you a boost. [PyAhoCorasick on pypi](https://pypi.org/project/pyahocorasick/) by example.
comment on: http://stackoverflow.com/q/51254037
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51264355
downvote count: 0
answer count: 7
tagged with: python-typing
favorite count: 0
tagged with: http://stackoverflow.com/tag/csv
has answer: http://stackoverflow.com/a/51270295
tagged with: python
has answer: http://stackoverflow.com/a/72492916
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51265827
has body: I want to apply type annotation to the returned object of csv.writer in order to comply with a larger codebase. Unfortunately I can not figure out the fitting return type. >>> import csv >>> writer = csv.writer(open('outfile.csv', 'w')) >>> type(writer) <class '_csv.writer'> If I try to use this classname: >>> import _csv >>> writer: _csv.writer = csv.writer(open('outfile.csv', 'w')) I get the following mypy error: Invalid type "_csv.writer" Does someone know which type to use in this case. Of course I could use typing.Any but this nullify the sense of a type annotation.
has answer: http://stackoverflow.com/a/77607877
possible better answer: http://stackoverflow.com/a/63785959
type: Question
has answer: http://stackoverflow.com/a/63785959
has title: How to type-annotate object returned by csv.writer?
accepted answer: http://stackoverflow.com/a/51270295
has answer: http://stackoverflow.com/a/51267141
score: 36
has answer: http://stackoverflow.com/a/79230113
upvote count: 36

http://stackoverflow.com/a/51253906
has comment: http://stackoverflow.com/comment/89500219
score: 3
upvote count: 3
has body: There is nothing builtin that can do this, but it would be easy to make your own Button that can. You are on the right track too, only thing you are missing is that you need to use after to make the loop and after_cancel to stop the loop: try: import tkinter as tk except ImportError: import Tkinter as tk class PaulButton(tk.Button): """ a new kind of Button that calls the command repeatedly while the Button is held :command: the function to run :timeout: the number of milliseconds between :command: calls if timeout is not supplied, this Button runs the function once on the DOWN click, unlike a normal Button, which runs on release """ def __init__(self, master=None, **kwargs): self.command = kwargs.pop('command', None) self.timeout = kwargs.pop('timeout', None) tk.Button.__init__(self, master, **kwargs) self.bind('&lt;ButtonPress-1&gt;', self.start) self.bind('&lt;ButtonRelease-1&gt;', self.stop) self.timer = '' def start(self, event=None): if self.command is not None: self.command() if self.timeout is not None: self.timer = self.after(self.timeout, self.start) def stop(self, event=None): self.after_cancel(self.timer) #demo code: var=0 def func(): global var var=var+1 print(var) root = tk.Tk() btn = PaulButton(root, command=func, timeout=100, text="Click and hold to repeat!") btn.pack(fill=tk.X) btn = PaulButton(root, command=func, text="Click to run once!") btn.pack(fill=tk.X) btn = tk.Button(root, command=func, text="Normal Button.") btn.pack(fill=tk.X) root.mainloop() As @rioV8 mentioned, the after() call is not extremely accurate. If you set the timeout to 100 milliseconds, you can usually expect anywhere from 100 - 103 milliseconds between calls. These errors will stack up the longer the button is held. If you are trying to time exactly how long the button has been held down you will need a different approach.
has comment: http://stackoverflow.com/comment/89520573
type: Answer
answers question: http://stackoverflow.com/q/51253345
downvote count: 0

http://stackoverflow.com/comment/89524482
comment on: http://stackoverflow.com/q/51272909
score: 0
type: Comment
type: QuestionComment
has text: @HarvIpan that makes sense. is there a method to use `get_dummies()` to check all rows specifically for `weddings` in the `cateogry` column instead of just filtering rows with `weddings`?

http://stackoverflow.com/comment/89590908
has text: This is awkward idea. Imagine huge file system (10 TB FS are nothing exceptional) with thousands of directories. It would be sooooooooooo sluggish.
comment on: http://stackoverflow.com/a/51306467
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/89565062
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51293574
has text: Use the `attrs={'id': '82502690936618670'}` to the `pd.read_html()` call - there are nested tables in that page, so use `pd.read_html(..., attrs={'id': '82502690936618670'})[0][3]`
score: 0

http://stackoverflow.com/comment/89353078
comment on: http://stackoverflow.com/a/51185496
type: AnswerComment
score: 0
type: Comment
has text: Read about 'with'. So basically, readMyFile=open("myFile.txt","r").read() is equal to 'with' solution in regard, that in both cases file will be closed and throwed away? - that's what I wanted to know

http://stackoverflow.com/q/51300399
score: 3
has answer: http://stackoverflow.com/a/51307207
has body: i made a kivy/buildozer app for android. It fails after clicking the "get conditions" button. I have put preset variables in for reproducibility. just click the button. It works as expected on my laptop. but it stops on my phone. here is the python code: from kivy.app import App from kivy.uix.scatter import Scatter from kivy.uix.label import Label from kivy.uix.floatlayout import FloatLayout from kivy.uix.textinput import TextInput from kivy.uix.boxlayout import BoxLayout from kivy.uix.gridlayout import GridLayout from kivy.uix.button import Button import json import requests class BasicApp(App): def build(self): self.title = 'SurfsApp!' layout = BoxLayout(orientation = 'vertical') label1 = Label(text = 'SURFS APP!',size_hint = (1,.3), color = (0,0,1,1)) btn1 = Button(text = 'Todays Conditions', size_hint = (1,.3)) label2 = Label(text = 'Enter your latitude below',size_hint=(1,.1)) label3 = Label(text = 'Enter your longitude below',size_hint=(1,.1)) self.lon1 = str(122.5) self.lat1 = str(37) layout.add_widget(label1) layout.add_widget(label2) layout.add_widget(label3) layout.add_widget(btn1) def getconditions(*args,**kwargs): i = 0 north = self.lat1 west = self.lon1 gps= str(north) +','+ '-' + str(west) url = 'https://api.weather.gov/points/'+ str(gps) headers = {'Token': 'tArcrKZYxRTCWPvhTcdBqyydHZnxLCJB'} response = requests.get(url) data = response.json() # print(data['properties']['forecastGridData']) url = data['properties']['forecastGridData'] response = requests.get(url, headers = headers) data = response.json() forecast = {'windSpeed': "{0:.1f}".format(data['properties']['windSpeed']['values'][i]['value'] * 1.94384), 'windDirection': data['properties']['windDirection']['values'][i]['value'], 'primarySwellDirection': data['properties']['primarySwellDirection']['values'][i]['value'], 'primarySwellHeight': int(data['properties']['primarySwellHeight']['values'][i]['value'] * 3.28084), 'wavePeriod': data['properties']['wavePeriod']['values'][i]['value'], 'seconda…
type: Question
has title: kivy buildozer android https request fail
answer count: 1
downvote count: 0
favorite count: 0
tagged with: buildozer
tagged with: android
tagged with: kivy
upvote count: 3
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/51192402
has answer: http://stackoverflow.com/a/51949661
type: Question
has title: visible workflow engine with django or python?
score: 0
has comment: http://stackoverflow.com/comment/89367884
answer count: 1
tagged with: workflow
type: UnansweredQuestion
tagged with: python
has body: Is there visible workflow engine with django or python? in front-end webpage, user could handle workflow without coding via visible workflow interface. if have these workflow, pls recommend to me its name. thanks a lot!
has comment: http://stackoverflow.com/comment/89366641
tagged with: django

disk-access
tag name: disk-access
tags question: http://stackoverflow.com/q/51295993
type: Tag

tinkerpop3
tags question: http://stackoverflow.com/q/51195988
type: Tag
tag name: tinkerpop3

http://stackoverflow.com/comment/89398451
type: AnswerComment
comment on: http://stackoverflow.com/a/51208677
type: Comment
has text: That's right, I just re-produced the behavior of the original code. I guess is simply a matter of adding/substracting `1` from `df["Day_of_Week"] = df.Date.dt.weekday`
score: 0

http://stackoverflow.com/a/51277408
has body: rdd.sort('column_name', ascending=False).take(5) Hope this helps
score: 0
answers question: http://stackoverflow.com/q/51276541
type: Answer

http://stackoverflow.com/a/51210934
accepted answer of: http://stackoverflow.com/q/51204269
answers question: http://stackoverflow.com/q/51204269
upvote count: 3
score: 3
has comment: http://stackoverflow.com/comment/89439919
has comment: http://stackoverflow.com/comment/89437044
type: AcceptedAnswer
downvote count: 0
has body: The reason is that for the function (for example) f = abs(cos(0.75*pi) - cos(z)) the gradient f' happens to vanish at z = pi, as can be seen from the following plot: If you check the result the optimization procedure then you'll see that: fun: array([0.29289322]) hess_inv: &lt;1x1 LbfgsInvHessProduct with dtype=float64&gt; jac: array([0.]) message: b'CONVERGENCE: NORM_OF_PROJECTED_GRADIENT_&lt;=_PGTOL' nfev: 16 nit: 2 status: 0 success: True x: array([3.14159265]) So the optimization procedure reached one of its convergence criteria. More detailed information about the criterion can be found at the L-BFGS-B documentation. It says that gtol : float The iteration will stop when max{|proj g_i | i = 1, ..., n} &lt;= gtol where pg_i is the i-th component of the projected gradient. So it eventually reaches a point z &gt;= pi which is then projected back to z = pi due to the constraint and at this point the gradient of the function is zero and hence it stops. You can observe that by registering a callback which prints the current parameter vector: def new_callback(): step = 1 def callback(xk): nonlocal step print('Step #{}: xk = {}'.format(step, xk)) step += 1 return callback scipy.optimize.minimize(..., callback=new_callback()) Which outputs: Step #1: xk = [0.006] Step #2: xk = [3.14159265] So at the second step it hit z &gt;= pi which is projected back to z = pi. You can circumvent this problem by reducing the bounds to for example bounds=[(0, 0.99*np.pi)]. This will give you the expected result, however the method won't converge; you will see something like: fun: array([1.32930966e-09]) hess_inv: &lt;1x1 LbfgsInvHessProduct with dtype=float64&gt; jac: array([0.44124484]) message: b'ABNORMAL_TERMINATION_IN_LNSRCH' nfev: 160 nit: 6 status: 2 success: False x: array([2.35619449]) Note the message ABNORMAL_TERMINATION_IN_LNSRCH. This is due to the nature of abs(x) and the fact that its derivative has a discontinuity at x = 0 (you can read more about that here). Alternative …
type: Answer

http://stackoverflow.com/comment/89561012
type: Comment
type: QuestionComment
has text: Also remember to research before you post. This *problem* is solved in several places on line and on this site. If your problem is with your code in particular, then you'll need to describe that for us.
comment on: http://stackoverflow.com/q/51291648
score: 0

http://stackoverflow.com/comment/89368460
score: 0
has text: Thanks a lot. One more query. if the string is multiline with : in it, when it used something like this [\s\w,:]+. it selected almost all the lines. looks like it became greedy. how do I restrict it not to go beyond that line?
type: Comment
comment on: http://stackoverflow.com/a/51191955
type: AnswerComment

http://stackoverflow.com/comment/89842359
type: AnswerComment
score: 0
type: Comment
has text: I finally got around to testing this out and unfortunately none of those modules seem to exist for me even though plain old `fabric` imports fine
comment on: http://stackoverflow.com/a/51374537

http://stackoverflow.com/a/51228197
accepted answer of: http://stackoverflow.com/q/51228069
type: Answer
has comment: http://stackoverflow.com/comment/89436697
score: 2
has comment: http://stackoverflow.com/comment/89436507
upvote count: 2
has body: It looks like the code you are looking for is here: https://github.com/numpy/numpy/blob/464f79eb1d05bf938d16b49da1c39a4e02506fa3/numpy/random/mtrand/mtrand.pyx#L1551 As you can see, it's located under random/mtrand/mtrand.pyx. If you are wondering about .pyx: Cython states: "A .pyx file is compiled by Cython to a .c file, containing the code of a Python extension module. The .c file is compiled by a C compiler to a .so file (or .pyd on Windows) which can be imported directly into a Python session." You were looking for the definition of normal so I searched for "def normal". Here's the code at that link: def normal(self, loc=0.0, scale=1.0, size=None): """ normal(loc=0.0, scale=1.0, size=None) Draw random samples from a normal (Gaussian) distribution. The probability density function of the normal distribution, first derived by De Moivre and 200 years later by both Gauss and Laplace independently [2]_, is often called the bell curve because of its characteristic shape (see the example below). The normal distributions occurs often in nature. For example, it describes the commonly occurring distribution of samples influenced by a large number of tiny, random disturbances, each with its own unique distribution [2]_. Parameters ---------- loc : float or array_like of floats Mean ("centre") of the distribution. scale : float or array_like of floats Standard deviation (spread or "width") of the distribution. size : int or tuple of ints, optional Output shape. If the given shape is, e.g., ``(m, n, k)``, then ``m * n * k`` samples are drawn. If size is ``None`` (default), a single value is returned if ``loc`` and ``scale`` are both scalars. Otherwise, ``np.broadcast(loc, scale).size`` samples are drawn. Returns ------- out : ndarray or scalar Drawn samples from the parameterized normal distribution. See Also -------- scipy.stats.norm : probability density function, distribution or cumulative density function, etc. Notes ----- The probability density for the Gaussian distrib…
answers question: http://stackoverflow.com/q/51228069
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/51299787
has body: I would like to create functions in my Python3 code, making use of data supplied during run-time. I'm stuck on how I can write a function along the lines of def foo(varname1, varname2): return varname1 + varname2 where the strings varname1 and varname2 that give the parameter names are specified as arguments to some constructor function, e.g.: def makeNewFooFunc(varname1, varname2): # do magic return foo fooFunc = makeNewFooFunc('first', 'second') print(fooFunc(first=1, second=2)) # should return 3 what would be the #do magic step? Is this a job for eval, or is there an alternative?
answer count: 1
has comment: http://stackoverflow.com/comment/89577796
has comment: http://stackoverflow.com/comment/89577763
has comment: http://stackoverflow.com/comment/89582853
has answer: http://stackoverflow.com/a/51300223
linked to: http://stackoverflow.com/q/4246000
tagged with: python
type: AnsweredQuestion
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/51300223
has comment: http://stackoverflow.com/comment/89578086
type: Question
tagged with: metaprogramming
has comment: http://stackoverflow.com/comment/89578006
has comment: http://stackoverflow.com/comment/89576531
score: 0
has title: Dynamic generation of Python function with given parameter names

http://stackoverflow.com/q/51323547
type: Question
downvote count: 0
has body: I was trying to understand the behavior of Session's expire_on_commit parameter. So I created a small program which adds 2 rows, updates one of them and then accesses the other: engine = sa.create_engine('sqlite:///tmp.db', echo=True) Base = declarative_base() class User(Base): __tablename__ = 'users' id = Column(Integer, primary_key=True) name = Column(String) Base.metadata.create_all(engine) Session = sessionmaker(bind=engine, expire_on_commit=True) session = Session() # add 2 users u1 = User(name="u1") u2 = User(name="u2") session.add(u1) session.add(u2) session.commit() # update a user u1.name = "new name" session.commit() print("=== access a user ===") print(u2.name) Output when expire_on_commit is True (default): 2018-07-13 13:38:14,478 INFO sqlalchemy.engine.base.Engine SELECT CAST('test plain returns' AS VARCHAR(60)) AS anon_1 2018-07-13 13:38:14,478 INFO sqlalchemy.engine.base.Engine () 2018-07-13 13:38:14,479 INFO sqlalchemy.engine.base.Engine SELECT CAST('test unicode returns' AS VARCHAR(60)) AS anon_1 2018-07-13 13:38:14,479 INFO sqlalchemy.engine.base.Engine () 2018-07-13 13:38:14,479 INFO sqlalchemy.engine.base.Engine PRAGMA table_info("users") 2018-07-13 13:38:14,479 INFO sqlalchemy.engine.base.Engine () 2018-07-13 13:38:14,480 INFO sqlalchemy.engine.base.Engine CREATE TABLE users ( id INTEGER NOT NULL, name VARCHAR, PRIMARY KEY (id) ) 2018-07-13 13:38:14,480 INFO sqlalchemy.engine.base.Engine () 2018-07-13 13:38:14,488 INFO sqlalchemy.engine.base.Engine COMMIT 2018-07-13 13:38:14,490 INFO sqlalchemy.engine.base.Engine BEGIN (implicit) 2018-07-13 13:38:14,491 INFO sqlalchemy.engine.base.Engine INSERT INTO users (name) VALUES (?) 2018-07-13 13:38:14,491 INFO sqlalchemy.engine.base.Engine ('u1',) 2018-07-13 13:38:14,491 INFO sqlalchemy.engine.base.Engine INSERT INTO users (name) VALUES (?) 2018-07-13 13:38:14,491 INFO sqlalchemy.engine.base.Engine ('u2',) 2018-07-13 13:38:14,492 INFO sqlalchemy.engine.base.Engine COMMIT 2018-07-13 13:38:14,497 INFO sqla…
answer count: 1
tagged with: python
favorite count: 0
upvote count: 2
has answer: http://stackoverflow.com/a/51324414
score: 2
type: AnsweredQuestion
has title: SQL Alchemy: understanding expire_on_commit
accepted answer: http://stackoverflow.com/a/51324414
tagged with: sqlalchemy

http://stackoverflow.com/comment/115393711
type: Comment
type: QuestionComment
has text: I get the very same error when using `matplotlib.pyplot` on Win8.1 and Py3.7.
comment on: http://stackoverflow.com/q/51284268
score: 0

http://stackoverflow.com/q/51175182
upvote count: 2
has answer: http://stackoverflow.com/a/51175301
accepted answer: http://stackoverflow.com/a/51175239
tagged with: python
has answer: http://stackoverflow.com/a/51175362
has comment: http://stackoverflow.com/comment/89343429
type: AnsweredQuestion
has title: random integers and receiving them and saving them
possible better answer: http://stackoverflow.com/a/51175362
type: Question
score: 2
downvote count: 0
has body: So I'm quite new to Python and I've been making a dice roll for a lesson in class and I'm really stuck on it. My code works very well except for the point where the dice roll happens. If you roll a 6 then it should print that I win. But it prints that I lost. I have no idea why this is happening and any help would be appreciated. It's designed to ask you your name, give you a username and then ask if you want to play. But everything goes wrong at the end where you're given the number. Like I say I'd appreciate the test from random import randint print ("Hello, whats is your first name?") first_name = input() print ("What is your second name?") second_name = input() username = first_name[0] + first_name[1] + second_name[0] + second_name[1] print (username + ", I want to play a game. Do you accept?") game = input() if game == ("yes") or ("Yes") or : print ("Great, let's play. I'm going to roll a dice, if it lands on a 6, you win. If") print ("not, you lose.") dice_roll = print (randint(1,6)) if dice_roll == 6: print ("Congrats, you win.") elif dice_roll != 6: print ("Sorry. You lose.") elif game == ("no") or ("No"): print ("Ok, Bye.") else: print ("Ok, Bye.")
has answer: http://stackoverflow.com/a/51175239
answer count: 3
favorite count: 0

http://stackoverflow.com/comment/89471873
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/51245267
score: 0
has text: Thank you for the quick response. Kindly let me know to deal when you have decimal values. In france we use comma, to mention a decimal or float number. X= [('1,2',), ('2,3',), ('3,4',), ('4,2',), ('5,3',), ('6',)]. I get Value error : invalid literal for int() with base 10: '1,2'

http://stackoverflow.com/q/51251166
has comment: http://stackoverflow.com/comment/89486313
downvote count: 0
linked to: http://stackoverflow.com/q/46371321
tagged with: keras
has title: How do you specify that a specific Keras layer should be assigned to the CPU?
tagged with: gpu
tagged with: python
favorite count: 0
has body: I am working on a sequence-to-sequence model, mostly following the tutorial here. One of the layers on my model is too big to fit into GPU memory, but I would still like to be able to use the GPU for the other layers. Is it possible to move just that layer in Keras? I tried doing this: with tf.device('/device:CPU:0'): decoder_outputs = Dense(num_decoder_tokens, activation='softmax')(x) but it does not seem to work. I still run out of memory. This seems to work: with tf.device('/device:CPU:0'): model = Model([encoder_inputs, decoder_inputs], decoder_outputs_dense) model.compile(optimizer='adam', loss='categorical_crossentropy') but it moves the entire model to the CPU, and the training time jumps up to a few thousand hours, so I cannot do that. I guess it's possible in Tensorflow/pyTorch, but I was wondering if there was a way to do it while using Keras. EDIT: There is another question that sort of talks about the same problem, but the accepted answer there does not seem to work on Keras and I do not have enough reputation to comment on the answer :( EDIT2: The above link does solve the problem. It did not seem to work in my case initially, but that was because I was using a Jupyter notebook and probably forgot to execute the cell after editing or something similar.
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89486303
upvote count: 1
has comment: http://stackoverflow.com/comment/89526108
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/89485951
score: 1
tagged with: memory
type: Question

http://stackoverflow.com/q/51266383
accepted answer: http://stackoverflow.com/a/51266562
possible better answer: http://stackoverflow.com/a/51268262
score: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/89510944
tagged with: django
upvote count: 1
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51266562
type: Question
answer count: 2
has title: Django Model Function Performance
has comment: http://stackoverflow.com/comment/89510760
downvote count: 0
has body: I'm not sure how to title this question, please propose something better if you can! I have two models. The first model stored info for a tree (Tree). The second is a model to store information when a tree is replanted (TreeResettlement). A function in Tree called 'planted_date_real()' calculates the last time the tree was planted by looking at the latest record in TreeResettlement. trees = Tree.objects.all() for tree in trees: date = tree.planted_date_real() I have performance issues with this. Let's say 10000 trees are in the database. If I call those 10000 trees, and want to know the last planted date, Django calls the TreeResettlement table 10000 times. I'm aware of the 'select_related routine', however that only works if a Foreign Key is used in the table being worked on. Any help will be appreciated! ** Note that I understand the planted_date_real() function has problems, it is used for illustrative purposes. What I'm trying to figure out is how to use functions in models which can 'batch load' data and not do gazillion calls to the database when doing a function call (which filters a different table) on all objects in objects.filter() results Tree model class Tree(models.Model): name = models.CharField(max_length=200,blank=True) planted_date = models.DateTimeField(default = timezone.now,blank=True) def planted_date_real(self): #Calling data from TreeResettlement table is causing performance issues. #Is there some way of loading this table to memory when the function is called again? resettlements = TreeResettlement.objects.filter(tree=self) if len(resettlements) &gt; 0: return(resettlements[len(resettlements)-1].date) else: return(self.planted_date) TreeResettlement model class TreeResettlement(models.Model): tree = models.ForeignKey(Tree,on_delete=models.CASCADE) date = models.DateTimeField(default = timezone.now,blank=True) keep_main_stem = models.BooleanField()
has answer: http://stackoverflow.com/a/51268262

http://stackoverflow.com/q/51201390
tagged with: dictionary
has comment: http://stackoverflow.com/comment/89384401
has comment: http://stackoverflow.com/comment/89384236
type: AnsweredQuestion
tagged with: list
linked to: http://stackoverflow.com/q/1756096
has comment: http://stackoverflow.com/comment/89384299
upvote count: 1
has comment: http://stackoverflow.com/comment/89384204
type: Question
has title: Extracting order of client server from a dictionary using python
has comment: http://stackoverflow.com/comment/89384212
has body: I have a dictionary like below which for example, for the first item means 5 is the customer of 2. and in the last item, as you can see, 2 is the customer of 4 and 4 is also the customer of item 3. customer_provider_dic= {'2':['5'],'1':['2'],'3':['4'],'4':['2']} I am trying to extract all chains of customer of these items. The output will be like this: [2,5] [1,2,5] [3,4,2,5] [4,2,5] I really confused how can I extracts these chains. Any suggestion for the flowchart or the steps I should follow.
has answer: http://stackoverflow.com/a/51202290
downvote count: 0
answer count: 1
score: 1
tagged with: sequence
accepted answer: http://stackoverflow.com/a/51202290
favorite count: 0
has comment: http://stackoverflow.com/comment/89384200
has comment: http://stackoverflow.com/comment/89384380
has comment: http://stackoverflow.com/comment/89384547
tagged with: python

http://stackoverflow.com/comment/89408628
type: QuestionComment
comment on: http://stackoverflow.com/q/51213743
has text: I myself am not very sure how the data is returned that's why I'm having this problem
score: 0
type: Comment

http://stackoverflow.com/comment/89369074
comment on: http://stackoverflow.com/q/51193819
score: 0
has text: `**IPs**` is an invalid identifier.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89596251
has text: so, what I was trying makes no sense?. I didn't realize about the difference between expanding and filling. You would suggest change what I did?
type: Comment
comment on: http://stackoverflow.com/a/51294965
score: 0
type: AnswerComment

http://stackoverflow.com/comment/89430593
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51225057
type: Comment
has text: Maybe you should follow a python tutorial that explains lists and data. If you need the user to input 10 names, you could store them in a list like so: `mylistofnames = []` which creates an empty list and then you repeat the input() 10 times: `for _ in range(10):` + `mylistofnames.append(input())` ( you need to indent the stuff that should be looped by 4 spaces. See [for-loop-statement](https://docs.python.org/3/tutorial/controlflow.html#for-statements) and [list's](https://docs.python.org/3/tutorial/introduction.html#lists)

http://stackoverflow.com/comment/89437563
type: QuestionComment
has text: easier than what? Your solution is just a few lines. How much easier do you need it to be?
score: 1
comment on: http://stackoverflow.com/q/51228548
type: Comment

http://stackoverflow.com/q/51312952
score: 13
tagged with: python
upvote count: 13
type: AnsweredQuestion
tagged with: f-string
type: Question
has title: Python Sqlite3 - Using f strings for update database function
has answer: http://stackoverflow.com/a/51313074
downvote count: 0
has comment: http://stackoverflow.com/comment/128575624
has answer: http://stackoverflow.com/a/69850037
has body: I have my own personal database I made for fun (so not that concerned with sql injections as its my own private database I made) and am trying to change the functions I created that use string formatting (.format()) and placeholders (?, %s, etc) and use f strings instead. I ran into a problem where one of my functions that updates a specified column into a specified row won't run now that I changed the sqlite3 query to f strings. This is my current function using f strings: import sqlite3 from tabulate import tabulate conn = sqlite3.connect("Table.db") c = conn.cursor() def updatedb(Column, Info, IdNum): with conn: data = c.execute(f"UPDATE Table_name SET {Column} = {Info} WHERE IdNum={IdNum}") c.execute(f"SELECT * FROM Table_name WHERE IdNum = {IdNum}") print(tabulate(data, headers="keys", tablefmt="grid", stralign='center', numalign='center')) The function updates the table by updating a specified column of a specified row with the new info you want in that column. For example in a 3 x 3 table, instead of row 1, column 2 being 17, I can use the function to update row 1, column 2 to 18 if that column is an age or something. The select query after that is to just select that particular row that was updated and the print statement after that uses the tabulate package to print out a neat and organized table. The error I get whenever I try to use this function is: sqlite3.OperationalError: no such column: Info Whatever I type in for the Info variable in the function is what the error becomes but I can't figure out how to fix the problem. This is the update statement I had before attempting to change to f strings and it worked fine for me: data = c.execute("UPDATE Table_name SET {} = ? WHERE IdNum=?".format(Column), (Info, IdNum)) It didn't seem like to would be that big of a change to change the above query to a f string but it isn't working so any feedback would be appreciated.
tagged with: sqlite
possible better answer: http://stackoverflow.com/a/63946987
answer count: 4
has answer: http://stackoverflow.com/a/51313208
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/63946987
accepted answer: http://stackoverflow.com/a/51313074
has comment: http://stackoverflow.com/comment/89602714

http://stackoverflow.com/a/51327200
type: Answer
has comment: http://stackoverflow.com/comment/125928637
answers question: http://stackoverflow.com/q/51323686
upvote count: 2
score: 2
downvote count: 0
has body: How about this: ActionChains(driver).key_down(u'\ue03d').key_down('v').perform() or even: ActionChains(driver).key_down(u'\ue03d').send_keys('v').perform() I've checked it on a PC using the Control key instead of Command (obviously!) and both work. PS. Perhaps first you might need to simulate a click into the field you want to paste the buffer.

http://stackoverflow.com/comment/89358167
type: QuestionComment
has text: What are you even asking. I don't see a single `?`
comment on: http://stackoverflow.com/q/51188180
score: 0
type: Comment

http://stackoverflow.com/comment/89511216
type: QuestionComment
has text: That's right, but I couldn't find the file that defines tf.app.run() to check its return values.
score: 1
comment on: http://stackoverflow.com/q/51266268
type: Comment

http://stackoverflow.com/q/51315786
answer count: 1
accepted answer: http://stackoverflow.com/a/51316045
tagged with: matplotlib
tagged with: subplot
has body: I have a code to break up a picture into parts and I'd like to print them out together (with a small space between them), but retain the same sizes so the full image is still clearly visible. def crop_image(img, quadrant): img = img_to_array(img) d = img.shape rows = int(d[0]*2/3) cols = int(d[1]*2/3) q = {"TL": img[:rows,:cols,:], "TR": img[:rows,cols:,:], "BL": img[rows:,:cols,:], "BR": img[rows:,cols:,:]} return array_to_img(q[quadrant]) img = load_img('./example1.jpeg', target_size=(224, 224)) cropped = crop_image(img, 'TR') fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2,2) ax1.imshow(crop_image(img, 'TL')) ax1.axis('off') ax2.imshow(crop_image(img, 'TR')) ax2.axis('off') ax3.imshow(crop_image(img, 'BL')) ax3.axis('off') ax4.imshow(crop_image(img, 'BR')) ax4.axis('off') fig.subplots_adjust(hspace=0.1) plt.tight_layout()
type: AnsweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/51316045
score: 1
has title: How to adjust subplots' height and width for tight fit?
favorite count: 0
type: Question
upvote count: 1
tagged with: python

http://stackoverflow.com/a/51211536
accepted answer of: http://stackoverflow.com/q/51210929
answers question: http://stackoverflow.com/q/51210929
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89405222
has comment: http://stackoverflow.com/comment/89404279
score: 0
has comment: http://stackoverflow.com/comment/89404655
has comment: http://stackoverflow.com/comment/89404319
type: Answer
has comment: http://stackoverflow.com/comment/89404566
has comment: http://stackoverflow.com/comment/89404333
has comment: http://stackoverflow.com/comment/89405165
has body: I don't really understand your use case,I tried to solve it based on your input and output. from nltk.tokenize import sent_tokenize,word_tokenize string=input("enter your text: ? ") champ_ids = (word_tokenize(string)) champ_dict = {"hello" : 0, "Carly" : 36, "Freddy" : 85, "Megan" : 14, "Dilbert" : 69} result = "" value = 0 for k,v in champ_dict.items(): if k in champ_ids: result += k+" " value += v if value in range(20,30): status = "high" elif value in range(10,20): status = "moderate" elif value in range(0,10): status = "low" print("result = ", result) print("value = ", value) print("status = ", status) Output: result = hello Megan value = 14 status = moderate

http://stackoverflow.com/q/51266831
has answer: http://stackoverflow.com/a/51269062
score: 0
has title: OpenCV - Smoothing borders
has comment: http://stackoverflow.com/comment/112412950
has answer: http://stackoverflow.com/a/51268757
tagged with: python
type: UnansweredQuestion
tagged with: opencv
has body: I want to stitch multiple image patches to a new and mainly gray background image. The image patches contain colored elements which shall not be changed, if possible. Their shape and color is diverse. Like the new background image the borders of the image patches are also gray, just slightly different, but you can see strong borders if I just go by ImgPatch = cv2.imread("C://...//ImagePatch.png") NewBackground = cv2.imread("C://...//NewBackground.png") height, width, channels = ImgPatch.shape NewBackground[y:y+height,x:x+width] = ImgPatch I tried cv2.seamlessClone() (docs.opencv.org) as explained in this tutorial: www.learnopencv.com/seamless-cloning-using-opencv-python-cpp The edges are perfectly smoothed, but unfortunately the colors of the elements are changed way too much. I know the approximate width and height of the gray border of each image patch. If i could specifically smooth that area that may be a start and lets the result look already better than what I have. I tried different masks with cv2.seamlessClone(), of which none of the tried ways workes. So unfortunately I couldn't find a correct way to blend only the border of the patches so far. The following images visualize my problem in a very abstract way. What I have: Left: Background, Right: Image patch What I want: What I currently get by using cv2.seamlessClone(): Any help would be very much appreciated! EDIT As I probably was not clear enough: The real images are way more complex and so unfortunately I can not get reasonable results for all image patches by using cv2.findContour... What I am looking for is a method to merge the borders, so you can not see the exact transition of patch to background anymore.
tagged with: image-processing
has comment: http://stackoverflow.com/comment/89513492
has comment: http://stackoverflow.com/comment/89516542
type: Question
has comment: http://stackoverflow.com/comment/89517580
answer count: 2

http://stackoverflow.com/comment/89383698
score: 0
comment on: http://stackoverflow.com/q/51200951
type: QuestionComment
type: Comment
has text: But if "current version" is latest... you can have one more `elif version_number == "current version: pass" before the `LooseVersion` comparison. If it's already greater then `version` by definition.

http://stackoverflow.com/comment/89620058
type: AnswerComment
score: 0
type: Comment
has text: please tell me what to do if error does not came in assertion.
comment on: http://stackoverflow.com/a/51300962

http://stackoverflow.com/a/51256611
has comment: http://stackoverflow.com/comment/89493872
score: 2
has comment: http://stackoverflow.com/comment/89492070
downvote count: 0
has comment: http://stackoverflow.com/comment/89920301
upvote count: 2
answers question: http://stackoverflow.com/q/51256565
has comment: http://stackoverflow.com/comment/89492104
has body: Transform Investments2 before you merge. Like, Investments2['security code'] = Investments2['security code'].transform(float) or as pointed out in the comments, use DataFrame.astype Investments2['security code'] = Investments2['security code'].astype(float)
type: Answer

http://stackoverflow.com/comment/89567753
type: QuestionComment
type: Comment
has text: Sounds like you are trying to divide by 100.
comment on: http://stackoverflow.com/q/51295101
score: 4

http://stackoverflow.com/q/51307636
score: 1
favorite count: 0
has answer: http://stackoverflow.com/a/51362552
tagged with: pycharm
has title: Can't run PyCharm interpreter as root
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/89603770
type: AnsweredQuestion
tagged with: interpreter
has body: I am trying to use Kubernetes python SDK. I tried to run the following code: from kubernetes import client, config # Configs can be set in Configuration class directly or using helper utility config.load_kube_config() v1 = client.CoreV1Api() print("Listing pods with their IPs:") ret = v1.list_pod_for_all_namespaces(watch=False) It failed with lots of errors. When I run the same code with python from a shell, the same issue. When I run the same code with sudo python from shell, it works. I am trying to run PyCharm interperte as root. Following the instruction from JetBrains, I created a script shell with the name pythonCustomInt.sh that contains: sudo python I went to PyCharm settings > Project Interpreter and changed the Base interpreter to /&lt;path&gt;/pythonCutomInt.sh but it writes an error: Environment location directory is not empty I am not sure where I need to put the script. Any idea?
accepted answer: http://stackoverflow.com/a/51362552
type: Question
downvote count: 0
tagged with: kubernetes
answer count: 1

slider
tags question: http://stackoverflow.com/q/51227341
tag name: slider
type: Tag

http://stackoverflow.com/comment/89445016
comment on: http://stackoverflow.com/a/51232841
type: AnswerComment
score: 0
type: Comment
has text: @AnkitJaiswal thanks for pointing it out, I wrote that code without testing it.

http://stackoverflow.com/q/51250668
has body: I am trying to select a drop down menu and choose an option. I am using the latest version of Selenium, the latest version of Firefox, the latest version of geckodriver, and the latest version of Python. Here is my issue: When I try to choose an option, it gives me the following error: selenium.common.exceptions.ElementNotInteractableException: Message: Element could not be scrolled into view. I have tried various ways to circumnavigate this issue, but none seem to work. Here are some of the approaches I tried. mySelectElement = browser.find_element_by_id('providerTypeDropDown') dropDownMenu = Select(mySelectElement) dropDownMenu.select_by_visible_text('Professional') mySelectElement = browser.find_element_by_id('providerTypeDropDown') dropDown = Select(mySelectElement) for option in dropDown.options: message = option.get_attribute('innerText') print(message) if message == 'Professional': print("Exists") dropDown.select_by_visible_text(message) break element = browser.find_element_by_id('providerTypeDropDown') browser.execute_script("var select = arguments[0]; for(var i = 0; i < select.options.length; i++){ if(select.options[i].text == arguments[1]){ select.options[i].selected = true; } }", element, "Professional") The HTML code follows the usual select tags and option tags. Any help is appreciated. The HTML code is included below. <select data-av-chosen="providerTypes" id="providerTypeDropDown" data-placeholder="Please Select a Provider Type" name="providerTypeDropDown" class="chzn-select input-full ng-pristine chzn-done ng-invalid ng-invalid-provider-type" data-ng-options="providerType.value for providerType in request.models.providerTypes" data-ng-model="request.models.providerType" data-av-validator-field="providerType" data-disable-search-threshold="5" style="display; none;"> Please Select a Provider Type Professional Institutional The print statements are there for testing/code tracing purposed.
upvote count: 6
accepted answer: http://stackoverflow.com/a/51252175
possible better answer: http://stackoverflow.com/a/51251328
answer count: 3
tagged with: drop-down-menu
has answer: http://stackoverflow.com/a/71319418
has answer: http://stackoverflow.com/a/51252175
favorite count: 0
tagged with: webdriverwait
tagged with: python
tagged with: selenium-webdriver
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51251328
tagged with: selenium
downvote count: 1
has title: Message: Element could not be scrolled into view while trying to click on an option within a dropdown menu through Selenium
type: Question
score: 5

http://stackoverflow.com/q/51288910
has comment: http://stackoverflow.com/comment/89555684
score: 0
has title: Get output from curl command in python.
linked to: http://stackoverflow.com/q/1996518
answer count: 1
tagged with: python
tagged with: curl
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51288968
accepted answer: http://stackoverflow.com/a/51288968
has body: How do I set the result of curl command to a variable, (So in this the ip address.) import subprocess; ip = subprocess.call("curl ident.me", shell=True) 120.12.12.12 ip returns "0"
type: Question
has comment: http://stackoverflow.com/comment/89635796

http://stackoverflow.com/q/51172911
tagged with: windows
tagged with: python
tagged with: rasa-core
tagged with: tensorflow
type: Question
has title: tensorflow installation error in rasa_core package
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/51173350
type: UnansweredQuestion
has body: Tried a lot of things to rectify the problem but nothing helped. tried downloading tensorflow separately but while installing rasa_core again the same problem is coming. I have a 32 bit machine with python 3.6.5 installed and with the latest version of pip. I would really appreciate the help.

http://stackoverflow.com/comment/89498614
type: QuestionComment
has text: @mulg0r Yes, I tried with `port: - "9001:9001"` or using `9002` instead of `9001` using `port: - "9002:9001"` bot not worked.
comment on: http://stackoverflow.com/q/51260058
score: 0
type: Comment

http://stackoverflow.com/a/61095102
answers question: http://stackoverflow.com/q/51188180
type: Answer
score: 1
upvote count: 1
downvote count: 0
has body: Yor are miss spell the class name. It is not chrome(), Chrome(). webdriver.chrome("F:\\chromedriver.exe") to webdriver.Chrome("F:\\chromedriver.exe") or webdriver.Chrome()

http://stackoverflow.com/comment/89589064
score: 2
has text: Interesting, I found this [related issue (bpo-20423)](https://bugs.python.org/issue20493) on the python bug tracker. Another way to work around this issue is to [schedule a background task that wakes up every day](https://gist.github.com/vxgmichel/46e7aa46d0da32ce0c647e27df39f7b9).
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51294509

http://stackoverflow.com/q/51189483
has comment: http://stackoverflow.com/comment/89360589
favorite count: 0
has answer: http://stackoverflow.com/a/51189990
has comment: http://stackoverflow.com/comment/89360726
answer count: 3
tagged with: python
tagged with: nlp
has comment: http://stackoverflow.com/comment/89360813
has body: I have a text file with 11965 entries that looks like: AAA BBB CCC DDD Which I transformed into: list_1 = ['AAA', 'BBB', 'CCC', ...] And I need to compare it with another text file with 2221545 entries that looks like: AAA,.ADJ UK AAA,.N UK AAA,.N ES B,.ADV UK BB,.ADV UK BBB,.N IT Which I transformed into: list_2 = ['AAA\tADJ\tUK', 'AAA\tN\tUK', 'AAA\tN\tES', 'B\tADV\UK', 'BB\tADV\tUK', ...] So I have to get a dict that looks like this: result_dict = {'AAA':[[UK, ADJ, N], [ES,N]], 'BBB':IT,N, ...} Due to the size of the second list, if we compare the entries one by one the time complexity will be O(11965*2221545). (Am I getting in right?) And because I have to get the entire entry, I cannot use set to compare them. Is there any efficient way to get the job done?
has comment: http://stackoverflow.com/comment/89361055
possible better answer: http://stackoverflow.com/a/51189648
downvote count: 1
type: AnsweredQuestion
tagged with: performance
has comment: http://stackoverflow.com/comment/89361150
has title: Comparing strings in huge lists but cannot use set in Python
score: -1
tagged with: list-comprehension
type: Question
accepted answer: http://stackoverflow.com/a/51189990
has answer: http://stackoverflow.com/a/51190002
upvote count: 0
tagged with: string-comparison
has answer: http://stackoverflow.com/a/51189648

http://stackoverflow.com/comment/89570560
score: 1
has text: Local variables are marked as such during compilation. What actually changes is the op-code in the compiled bytecode, but the error wont' actually occur until the code runs.
comment on: http://stackoverflow.com/q/51296579
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51318225
answers question: http://stackoverflow.com/q/51318092
downvote count: 0
type: Answer
upvote count: 1
score: 1
has body: From the documentation on ndarray with the signature. ndarray(shape, dtype, buffer, offset, strides, order) If buffer is None, then only shape, dtype, and order are used. If buffer is an object exposing the buffer interface, then all keywords are interpreted. Seems to be that for the first example, even though the buffer is an np.array of integers, ndarray interprets it as a different type. You have to give it the optional argument dtype = int so that the ndarray explicitly know its elements are of type integer. np.ndarray(shape = (2,1), dtype = int, buffer = np.array([1,2,3,4]))

http://stackoverflow.com/comment/89566618
score: 1
has text: not sure if it helps,but from this dict the highest scoring window would be `AACB` or `ABCB` - you could construct all possible combinations for this example and check if either is in your string -but I guess ou cant do for your real world problem. that way you have to create a dict with 4-char combinations and the sum and can simply check top down value vise if its in there - lookup is bound to be cheaper then sliding a window and recomputing
comment on: http://stackoverflow.com/q/51294426
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89419367
has text: @Mankind_008, so I added that before using your initial code suggestion and now I've got the error: TypeError: unsupported operand type(s) for /: 'Timestamp' and 'int'
score: 0
comment on: http://stackoverflow.com/q/51219069
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/89430813
has text: The request that I use is "res = requests.get('https://www.calix.com/search-results.html?searchKeyword=C7',headers={'User-Agent':'test'})" This is downloading the page under "page-source". That is what I see when I print res.text But page source doesnt have the "Inspect element" that I am looking for.
comment on: http://stackoverflow.com/q/51225090
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89621012
comment on: http://stackoverflow.com/q/51322889
score: 0
type: QuestionComment
has text: Current URL is exactly the same as you used in request
type: Comment

http-status-code-403
tags question: http://stackoverflow.com/q/51219203
tag name: http-status-code-403
type: Tag

http://stackoverflow.com/comment/89589655
type: QuestionComment
has text: can you describe a little about feather please
comment on: http://stackoverflow.com/q/51305199
type: Comment
score: 0

http://stackoverflow.com/q/51243562
tagged with: opencv
type: Question
tagged with: codec
duplicate of: http://stackoverflow.com/q/30103077
has comment: http://stackoverflow.com/comment/89465683
score: 0
has body: I'm trying to convert an image to a video. I success to convert an image to an avi video, but I try to convert in mp4, but I got this error : [libx264 @ 0x15e2140] broken ffmpeg default settings detected [libx264 @ 0x15e2140] use an encoding preset (e.g. -vpre medium) [libx264 @ 0x15e2140] preset usage: -vpre &lt;speed&gt; -vpre &lt;profile&gt; [libx264 @ 0x15e2140] speed presets are listed in x264 --help [libx264 @ 0x15e2140] profile is optional; x264 defaults to high Could not open codec 'libx264': Unspecified error My code for mp4 (Which give the error): # -*- coding: utf-8 -*- import os import cv2 import numpy as np print(cv2.__version__) FILENAME = "test.jpg" if FILENAME.endswith('.mp4'): print('.mp4') elif FILENAME.endswith('.jpg'): print('.jpg') if not os.path.exists(FILENAME): print('File not found') img = cv2.imread(FILENAME, cv2.IMREAD_COLOR) height, width, layers = img.shape fourcc = cv2.cv.CV_FOURCC(*'X264') video = cv2.VideoWriter('video.mp4', fourcc, 1, (width, height)) video.write(img) #cv2.imshow('image', img) #cv2.waitKey(0) cv2.destroyAllWindows() video.release() My code for avi (Which work): # -*- coding: utf-8 -*- import os import cv2 import numpy as np print(cv2.__version__) FILENAME = "test.jpg" if FILENAME.endswith('.mp4'): print('.mp4') elif FILENAME.endswith('.jpg'): print('.jpg') if not os.path.exists(FILENAME): print('File not found') img = cv2.imread(FILENAME, cv2.IMREAD_COLOR) height, width, layers = img.shape fourcc = cv2.cv.CV_FOURCC(*'XVID') video = cv2.VideoWriter('video.avi', fourcc, 1, (width, height)) video.write(img) #cv2.imshow('image', img) #cv2.waitKey(0) cv2.destroyAllWindows() video.release() I try to replace X264 by H264, I got the same error. I search some answer, and try to adapt their code to mine, change nothing, so I come back to my working avi code. I try to install this: $ sudo apt-get install ffmpeg x264 libx264-dev doesn't work. I try to replace H264 by 0X00000021, doesn't work too. Thanks for your answers
linked to: http://stackoverflow.com/q/30103077
has comment: http://stackoverflow.com/comment/89465586
answer count: 0
type: UnansweredQuestion
has title: OpenCV convert image to video(mp4)
tagged with: python

http://stackoverflow.com/q/51292880
tagged with: python
accepted answer: http://stackoverflow.com/a/51294308
score: 0
answer count: 1
tagged with: grid
has title: Grid in Python Tkinter is Resizing Without Reason?
tagged with: character-replacement
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51294308
tagged with: python-3.x
tagged with: tkinter
has body: I am creating a To - Do List In Python, and I have to arrange 3 elements as I start. These include a Notebook in order to flip through notes and to - dos. The others are just labels with images on them. Here is the code. My question is that I'm not sure how I am supposed to go about putting these images on the grid. The Notebook, which is located Row 1, Column 0, is very large and causes the column 2 to shift all the way right, which gets rid of the ability to put two items in two columns close to each other in row 1. Here is the code. from tkinter import * import datetime from tkinter import ttk import tkinter as tk from tkinter.scrolledtext import ScrolledText root = Tk() root.title("To - Do List") root.geometry("1200x600") root.configure(background = "white") # Variable list: content = ttk.Frame(root) content.grid(column=0, row=0, sticky=(N, S, E, W)) Photo1= PhotoImage(file="Full Circle Image Icon Docs.png") Photo2 = PhotoImage(file="To - Do List Label.png") TasksList = ttk.Notebook() Task1 = ttk.Frame(TasksList) Task2 = ttk.Frame(TasksList) TasksList.add(Task1, text = 'One') TasksList.add(Task2, text = 'Two') TasksList.grid(row=2, column=0, sticky=W) root.columnconfigure(0, weight=0) root.rowconfigure(0, weight=0) Label(image=Photo1, bg="black", borderwidth=0, highlightthickness=0).grid(row=0, column=0, sticky=W) Label(image=Photo2, borderwidth=0, highlightthickness=0).grid(row=0, column=1, sticky=W) root.mainloop() Help would be greatly appreciated. Thanks a lot guys!
type: Question

http://stackoverflow.com/q/51225657
has comment: http://stackoverflow.com/comment/89432870
has body: We can define the range of red color in HSV as below. I want to detect that whether a certain pixel is red or not? How can I do that in Python? I spend whole day, but unable to find solution. Please resolve my problem. I'm very new to Python. Code that I'm using is: img=cv2.imread("img.png") img_hsv=cv2.cvtColor(img, cv2.COLOR_BGR2HSV) # lower mask (0-10) lower_red = np.array([0,50,50]) upper_red = np.array([10,255,255]) mask0 = cv2.inRange(img_hsv, lower_red, upper_red) # upper mask (170-180) lower_red = np.array([170,50,50]) upper_red = np.array([180,255,255]) mask1 = cv2.inRange(img_hsv, lower_red, upper_red) image_height,image_width,_=img.shape for i in range(image_height): for j in range(image_width): if img_hsv[i][j][1]&gt;=lower_red and img_hsv[i][j][1]&lt;=upper_red: print("Found red")
has comment: http://stackoverflow.com/comment/89431641
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89432317
has answer: http://stackoverflow.com/a/51228567
tagged with: hsv
score: 1
tagged with: image-processing
upvote count: 1
has comment: http://stackoverflow.com/comment/89431629
has comment: http://stackoverflow.com/comment/89434904
type: Question
tagged with: numpy
accepted answer: http://stackoverflow.com/a/51228567
linked to: http://stackoverflow.com/q/48109650
tagged with: opencv
has comment: http://stackoverflow.com/comment/89434419
has title: Detect whether a pixel is red or not
linked to: http://stackoverflow.com/q/10948589
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/89433987
favorite count: 0
has comment: http://stackoverflow.com/comment/89431592
has comment: http://stackoverflow.com/comment/89431724
has comment: http://stackoverflow.com/comment/89431691
has comment: http://stackoverflow.com/comment/89432900

http://stackoverflow.com/a/51297081
answers question: http://stackoverflow.com/q/51297004
has body: Have you set the correct path in your PATH variable ? also your question is already answered over here :- java.io.IOException: Cannot run program "python" using Spark in Pycharm (Windows) Hope this helps !!
accepted answer of: http://stackoverflow.com/q/51297004
score: 0
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/q/51219201
tagged with: python
has body: I was able to use parallel on html2text via this code find . -type f -name \*html &gt; FLIST parallel --a FLIST -j 1000 'html2text {} &gt; {.}.txt' Now, how can I delete each .html input file once it was converted.
tagged with: parallel-processing
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51219273
type: Question
answer count: 1
has title: Run html2text using parallel while deleting the input
tagged with: terminal
score: 0
tagged with: linux
has answer: http://stackoverflow.com/a/51219273
tagged with: http://stackoverflow.com/tag/html

http://stackoverflow.com/a/51242635
score: 2
accepted answer of: http://stackoverflow.com/q/51242426
upvote count: 2
answers question: http://stackoverflow.com/q/51242426
type: AcceptedAnswer
downvote count: 0
has body: Of course you need a return statement to get any result at all. The problem is in the concept: If you want to return zero or more values, a list would be the easiest solution. (Your code simply overwrites the 1 by the 2). color_status = [] if "blue" in myInput: color_status.append("1") if "red" in myInput: color_status.append("2") return color_status
type: Answer

http://stackoverflow.com/a/51199723
has comment: http://stackoverflow.com/comment/89382412
type: Answer
score: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/89394399
has comment: http://stackoverflow.com/comment/89393264
has body: In the traceback, look at the fourth line, it's the same line that is in your code and causing an exception. We always put try except around the code block that we think is going to cause an exception. Everything else is put outside the block. try: response = language_client.analyze_sentiment(document=document) except InvalidArgument: continue # Assuming none of these would work if we don't get response? description_list.append(descr) sentiment = response.document_sentiment entimentscore_list.append(sentiment.score) magnitude_list.append(sentiment.magnitude) # Add the description that was actually used to the description list We try to get response from language client, it raises an exception saying InvalidArgument, we catch that. Now we know we don't need to do anything and we use continue, and move on to the next iteration. You probably will need to import InvalidArgument like - from google.api_core.exceptions import InvalidArgument before using it in the code. You are right about continue. More about continue statement and how to handle exceptions in python.
has comment: http://stackoverflow.com/comment/89389688
answers question: http://stackoverflow.com/q/51199436
upvote count: 3

http://stackoverflow.com/comment/89570972
type: AnswerComment
comment on: http://stackoverflow.com/a/51294054
type: Comment
has text: Why do they have to be useful for anything other than backwards compatibility? But if your question is "whether it's worth knowing", then I'd say for array, your answer is probably 'no'. But if you're suggestion is "it should be removed", then I'd disagree and say there's not much harm in leaving it (until there's some difficult change that causes it to be a headache to be updated)
score: 0

http://stackoverflow.com/q/51281612
has comment: http://stackoverflow.com/comment/89600960
score: 0
tagged with: python
has comment: http://stackoverflow.com/comment/89561694
has comment: http://stackoverflow.com/comment/89541555
has comment: http://stackoverflow.com/comment/89575164
answer count: 0
type: UnansweredQuestion
has title: How to properly implement multiprocessing with keras?
tagged with: tensorflow
tagged with: multiprocessing
type: Question
tagged with: keras
has body: I am attempting to scale my project to fully utilize my cpu, but I have run into a wall with using keras and multiprocessing properly. My code is attempting to simulate several games in parallel. def create_model(): #Very simple conv-net import keras from keras.models import Model from keras.layers import Input, Add, Dense, Flatten, Conv2D, Activation from keras.models import model_from_json from keras.initializers import glorot_uniform inputs = Input(shape=(8,8,1)) X = Conv2D(filters=32, kernel_size=(3,3), strides=(1,1), kernel_initializer=glorot_uniform())(inputs) X = Activation('relu')(X) X = Flatten()(X) X = Dense(10, activation='relu', kernel_initializer=glorot_uniform())(X) output = Dense(1, activation='sigmoid', name='output', kernel_initializer=glorot_uniform())(X) model = Model(inputs=inputs, outputs=output) model.compile(optimizer='adam', loss={'output': 'binary_crossentropy'}) return model def convert(board): import numpy as np print("converting") string_board = str(board) data_board = string_board.split() final_data = [] #normalized board values variance = 14 convert = {'.': 0.0, 'p': -1.0, 'r': -2.0, 'n': -3.0, 'b': -4.0, 'q': -5.0, 'k': -6.0, 'P': 1.0, 'R': 2.0, 'N': 3.0, 'B': 4.0, 'Q': 5.0, 'K': 6.0} for char in data_board: final_data.append(convert[char]) final_data = np.asarray(final_data) final_data /= variance if not board.turn: final_data = -final_data final_data = final_data.reshape(1, 8, 8, 1) return final_data return_list = [] model = create_model() #This just creates a conv-net def board_prediction(board): #Get predictions in parallel print("predicting") position = convert(board) #Prep board for CNN probs, _ = model.predict(position) return probs def log_result(result): return_list.append(results) def apply_async(): import chess from multiprocessing import Manager, Process, Pool pool = Pool() for i in range(1): board = chess.Board() pool.apply_async(board_prediction, args=(board, ), callback=log_result) pool.close() pool.join() print(return_l…
has comment: http://stackoverflow.com/comment/89559872

http://stackoverflow.com/q/51199118
type: AnsweredQuestion
score: 1
type: Question
accepted answer: http://stackoverflow.com/a/51199413
answer count: 1
downvote count: 0
favorite count: 0
has title: Python: socket.rcvfrom() lock all script
tagged with: python
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51199413
upvote count: 1
has body: I have a simple code in python 3 using schedule and socket: import schedule import socket from time import sleep def readDataFromFile(): data = [] with open("/tmp/tmp.txt", "r") as f: for singleLine in f.readlines(): data.append(str(singleLine)) if(len(data)&gt;0): writeToBuffer(data) def readDataFromUDP(): udpData = [] rcvData, addr = sock.recvfrom(256) udpData.append(rcvData.decode('ascii')) if(len(udpData)&gt;0): writeToBuffer(udpData) . . . def main(): schedule.every().second.do(readDataFromFile) schedule.every().second.do(readDataFromUDP) while(1): schedule.run_pending() sleep(1) UDP_IP = "192.xxx.xxx.xxx" UDP_PORT = xxxx sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.bind((UDP_IP, UDP_PORT)) main() The problem is, script hung up on the sock.rcvfrom() instruction, and wait until data come. How force python to run this job independently? Better idea is to run this in threads?

http://stackoverflow.com/a/51340187
has body: I think the problem is in the Config.py python file. You should specify the path for the database properly. Change your code like this: First of all import os library to the config.py file. import os Then make a variable. In my case I name that variable as basedir: basedir = os.path.abspath(os.path.dirname(__file__)) Now you can specify your path for the database. Change your SQLALCHEMY_DATABASE_URI as follows: SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') or \ 'sqlite:///' + os.path.join(basedir, 'hotel\\grandluis\\app.db') SQLALCHEMY_TRACK_MODIFICATIONS = False Go to your run.py python file and do these changes: from grandluis import db, createApp from flask_migrate import MigrateCommand from flask_script import Manager fro flask_sqlalchemy import SQLAlchemy app = createApp() db = SQLAlchemy(app) manager = Manager(app) manager.add_command('db', MigrateCommand) db.init_app(app) db.app = app db.create_all() if __name__ == '__main__': manager.run()
score: 0
has comment: http://stackoverflow.com/comment/89666861
has comment: http://stackoverflow.com/comment/89666899
type: Answer
answers question: http://stackoverflow.com/q/51299411

http://stackoverflow.com/comment/89482845
has text: Thank you all for your help, but I found the issue. The problem was that I was saving the info to password_file twice.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51237591

http://stackoverflow.com/q/51265182
has answer: http://stackoverflow.com/a/51284060
tagged with: python-3.x
upvote count: 2
type: UnansweredQuestion
tagged with: django
has comment: http://stackoverflow.com/comment/89537851
score: 2
has body: I had forked my shipping app into a folder called forked_apps using oscar_fork_app command and also added in settings.py get_core_apps(['forked_apps.shipping']), I just want to create two shipping methods mentioned, standard and express in the docs in this link:https://django-oscar.readthedocs.io/en/latest/howto/how_to_configure_shipping.html. In the init.py I have this code pre-existing: default_app_config = 'forked_apps.shipping.config.ShippingConfig' In repository.py I have written like this: from oscar.apps.shipping import repository from .methods import * class Repository(repository.Repository): def get_available_shipping_methods( self, basket, user=None, shipping_addr=None, request=None, **kwargs): methods = (Standard()) print("\n\nFetch availble shipping methods") if shipping_addr: # Express is only available in the UK methods = (Standard(), Express()) return methods And in the methods.py I had written: from decimal import Decimal as D from oscar.apps.shipping import methods from oscar.core import prices class Standard(methods.FixedPrice): code = 'standard' name = 'Standard shipping' charge_excl_tax = D('5.00') class Express(methods.FixedPrice): code = 'express' name = 'Express shipping' charge_excl_tax = D('10.00') What should happen is, the shipping_methods.html page should show up, but instead, after entering the shipping address it goes to the payment details page directly; this would usually happen only if there are no shipping methods defined, but I have implemented two shipping methods, standard and Express in the above code.I can't figure out how to make this work, even the print statement isn't working. Is there any other additional code that I must write? Can someone provide a solution with some code, if you have implemented it?
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/115977082
has comment: http://stackoverflow.com/comment/89541170
has title: Forking shipping app has no effect in Django oscar
has answer: http://stackoverflow.com/a/55467682
downvote count: 0
tagged with: django-oscar
favorite count: 0
has comment: http://stackoverflow.com/comment/89513864
has comment: http://stackoverflow.com/comment/89526197
tagged with: python

http://stackoverflow.com/comment/89439243
has text: @AngelValenzuela If you're doing one of those online course things, they tend to give you examples that only cover a few of the rules in the assignment, and then keep the tests that cover all the other rules secret. So you need to figure out how to come up with tests for all the other rules first. You can go too far with that methodology (unless you're applying to be a Ruby programmer at a hardcore Rails shop, in which case you should probably spend your entire interview writing test for your code to fail and not actually coding anything that works), but in moderation it's a good habit.
comment on: http://stackoverflow.com/a/51229522
score: 1
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/89369461
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51193908
has text: I have to remove this character. I have column with values - [nan, '\x01', '0.0', '1.0', 0.0, 1.0]. This needs to be summed.
score: 0

http://stackoverflow.com/q/51296414
has title: Python:ValueError: scatter requires y column to be numeric?
has body: Using pd.Dataframe won't convert columns of lists into dataframe : Below are my lines of code for reading in a .mat file and converting it into a dataframe from the many examples that I have seen. However, when I read the data in the columns they still remain as lists with square brackets around the data. What I am trying to do is convert this into a proper dataframe so I can plot the last column (time data) along with the other columns as an x and y scatter plot. But the error I get is ValueError: scatter requires y column to be numeric. I have not shown the code for plotting the x and y data. import mat4py as mp data = mp.loadmat('test.mat') df = pd.DataFrame(data) When I type: df.columns I get the following: Index(['col 1', 'col 2', 'col 3', 'col 4', ... 'col 189'] with dtype='object', length=189) If I type: df.['col 1'] I get the following: Out[95]: 0 [0.0] 1 [0.0] 2 [0.0] 3 [0.0] 4 [0.0] 5 [0.0] 6 [0.0] 7 [0.0] 8 [0.0] 9 [0.0] ... 1622 rows in total. I even tried using .apply(pd.to_numeric, errors='coerce') to the columns and that does not work either. What am I doing wrong? Update: The solution in the comments presented below applied only for a single column, but I wanted this to apply to every cell in the dataframe. When using .apply(lambda ..) on a whole dataframe, the columns become the index and messes up the dataframe. I found the solution that would properly apply the lambda to each cell and retain the dataframe. It is as follows: mm = df.applymap(lambda x: x[0]) Many thanks to those who provided the original lambda solution.
type: Question
answer count: 2
downvote count: 0
tagged with: pandas
tagged with: python
favorite count: 0
upvote count: 3
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51296452
score: 3
has answer: http://stackoverflow.com/a/51296439

http://stackoverflow.com/comment/89515469
type: AnswerComment
type: Comment
has text: True, but since this question is not about numba or highly optimizing the performance of code, I wanted to just post a simple and short example of what was meant with compiling. And in this case the performance gain is negligible compared to the additional effort.
comment on: http://stackoverflow.com/a/51250399
score: 0

peewee
tag name: peewee
type: Tag
tags question: http://stackoverflow.com/q/51173602
tags question: http://stackoverflow.com/q/51206342

http://stackoverflow.com/comment/89358578
has text: What do you want to replace them with? Once you know that, this is simply text manipulation.
type: QuestionComment
comment on: http://stackoverflow.com/q/51188365
score: 0
type: Comment

http://stackoverflow.com/q/51317280
has comment: http://stackoverflow.com/comment/89611020
downvote count: 0
favorite count: 0
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89611112
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/89611086
score: 1
has body: I read that numpy arrays are very good for tasks that allow for vectorization, but I also read that scipy matrices are very efficient for matrix manipulations. Given that numpy arrays seem to be more often associated with containing data, would it be better to use numpy arrays for creation and storage, but to convert to scipy matrices when heavy use of matrix operations are used? In general what is the best practice for when to use numpy over scipy?
has title: When to use numpy arrays vs scipy matrices
tagged with: scipy
type: Question
tagged with: numpy

http://stackoverflow.com/comment/89347817
comment on: http://stackoverflow.com/a/51182746
type: AnswerComment
score: 0
type: Comment
has text: Thanks for your answer, but it still in trouble. In Bottle, I return values to `rows`, and I use `@route('/table)'`, then I follow your code and change `url` to `http://localhost:8080/table`. That error still appears.

http://stackoverflow.com/q/51229013
has comment: http://stackoverflow.com/comment/89437848
has comment: http://stackoverflow.com/comment/89437925
has comment: http://stackoverflow.com/comment/89437851
has comment: http://stackoverflow.com/comment/89437830
has title: Error message for keyboard-chord code: termios.error: (25, 'Inappropriate ioctl for device')
has body: I'm a python beginner, and I was recently trying to code a program that required the readchar module. However, I kept getting the error message: termios.error: (25, 'Inappropriate ioctl for device') I've tried adjusting my code, but I keep getting the same error message. Here is my code: import readchar while True: print(readchar.readkey()) (This is the full error message.) Traceback (most recent call last): File "/Users/larajean/PycharmProjects/thegreatesthits/chordKeyboard.py", line 7, in &lt;module&gt; chord = readchar.readkey() File "/Users/larajean/PycharmProjects/thegreatesthits/venv/lib/python2.7/site-packages/readchar/readchar.py", line 20, in readkey c1 = getchar() File "/Users/larajean/PycharmProjects/thegreatesthits/venv/lib/python2.7/site-packages/readchar/readchar_linux.py", line 12, in readchar old_settings = termios.tcgetattr(fd) termios.error: (25, 'Inappropriate ioctl for device') I am using a PyCharm IDE and a version of Python 2.7. Any suggestions on how to fix this problem?
tagged with: pycharm
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/89438044
has comment: http://stackoverflow.com/comment/89437872
has comment: http://stackoverflow.com/comment/89437929
type: Question
has comment: http://stackoverflow.com/comment/89437772
has comment: http://stackoverflow.com/comment/89437821
has comment: http://stackoverflow.com/comment/89437978
has comment: http://stackoverflow.com/comment/89438087
has comment: http://stackoverflow.com/comment/89437788
has answer: http://stackoverflow.com/a/68787154
has comment: http://stackoverflow.com/comment/89438037
upvote count: 1
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/51176864
tagged with: dictionary
has title: Python: create dictionary inside dictionary to convert to JSON
has comment: http://stackoverflow.com/comment/89336417
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89336400
has body: I want to create the JSON: [ { measurement: "Equipment1", fields: { Pressure: 5.5 }, tags:{ MachineType:"type1" }, timestamp: 1530717056.48 } ] The code ive written is : import json import time from decimal import Decimal count = 0 read_pressures = [] while (count &lt; 100): current_time=time.time() array_of_pressures.append(dict(measurement="Equipment1", dict(pressure=5.5),dict(MachineType="Type1"),timestamp=time.time())) time.sleep(0.01) count = count + 1 print(data) # read_pressures.append(data) print ("printing all values") print(json.dumps(read_pressures, ensure_ascii=False)) #print(read_pressures) The codes giving a error "SyntaxError: non-keyword arg after keyword arg " but i dont know how i'm supposed to create a dictionary inside a dictionary. Any help appreciated? Thanks
score: 1
tagged with: http://stackoverflow.com/tag/json
type: Question
accepted answer: http://stackoverflow.com/a/51176896
answer count: 1
downvote count: 0
favorite count: 0
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/51176896

php
tags question: http://stackoverflow.com/q/51195932
tags question: http://stackoverflow.com/q/51286037
tag name: php
tags question: http://stackoverflow.com/q/51185266
tags question: http://stackoverflow.com/q/51255230
tags question: http://stackoverflow.com/q/51314217
tags question: http://stackoverflow.com/q/51254455
tags question: http://stackoverflow.com/q/51193749
type: Tag

plotly-dash
tags question: http://stackoverflow.com/q/51193845
tags question: http://stackoverflow.com/q/51273588
type: Tag
tags question: http://stackoverflow.com/q/51201901
tags question: http://stackoverflow.com/q/51314752
tag name: plotly-dash
tags question: http://stackoverflow.com/q/51255660
tags question: http://stackoverflow.com/q/51286524
tags question: http://stackoverflow.com/q/51233737
tags question: http://stackoverflow.com/q/51191353
tags question: http://stackoverflow.com/q/51168680

http://stackoverflow.com/comment/138670747
type: AnswerComment
has text: You might have to cast it is `str` for some of your columns. try `' '.join(map(str,df.columns))`. I bet you might have already figured it out by now
type: Comment
comment on: http://stackoverflow.com/a/51194149
score: 0

http://stackoverflow.com/comment/89371900
type: AnswerComment
type: Comment
score: 0
has text: @miradulo i use the code from the answers verbatim. zipping large lists is not a free lunch either =)
comment on: http://stackoverflow.com/a/51194532

http://stackoverflow.com/q/51218937
type: Question
has answer: http://stackoverflow.com/a/51218975
has title: Saving a 3D numpy array to .txt file
tagged with: numpy
answer count: 2
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/70473030
has body: I'm just asking the question because it worked two days ago on my desktop, but as I'm trying to run this on my laptop, it doesn't work. array = numpy.zeros((3,3,1)) numpy.savetxt("nxx", array, fmt='%s') This gives me the following error: "Expected 1D or 2D array, got %dD array instead" % X.ndim) ValueError: Expected 1D or 2D array, got 3D array instead
tagged with: python
upvote count: 13
type: UnansweredQuestion
tagged with: save
score: 13

http://stackoverflow.com/comment/89422173
score: 0
comment on: http://stackoverflow.com/q/51220438
type: QuestionComment
type: Comment
has text: the code was run by jupyter notebook 5.5.0, line by line

http://stackoverflow.com/comment/89478060
type: Comment
has text: Thanks that's it :)
comment on: http://stackoverflow.com/a/51249551
type: AnswerComment
score: 0

http://stackoverflow.com/q/51301150
score: 0
tagged with: string
has comment: http://stackoverflow.com/comment/89579268
answer count: 0
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/7771011
has title: how to convert abstruse string to list
tagged with: http://stackoverflow.com/tag/json
type: Question
has body: I want to convert '["$.insert(\"//localhost:0000/aaaa/js/\", function() {});", "$.functions($)(\"//localhost:0000/aaa2/js/\", function() {});", "$.placeholder.id+\"&amp;_uid=\"+$.p.token+\"&amp;_ref=\"+$.p.url;"]' to ["$.insert(\"//localhost:0000/aaaa/js/\", function() {});", "$.functions($)(\"//localhost:0000/aaa2/js/\", function() {});", "$.placeholder.id+\"&amp;_uid=\"+$.p.token+\"&amp;_ref=\"+$.p.url;"] In Django JSON: { "templates": ["$.insert(\"//localhost:0000/aaaa/js/\", function() {});", "$.functions($)(\"//localhost:0000/aaa2/js/\", function() {});", "$.placeholder.id+\"&amp;_uid=\"+$.p.token+\"&amp;_ref=\"+$.p.url;"] }
has comment: http://stackoverflow.com/comment/89579324
has comment: http://stackoverflow.com/comment/89579226

http://stackoverflow.com/q/51318249
has answer: http://stackoverflow.com/a/51318294
has answer: http://stackoverflow.com/a/51318327
has title: Python: How do I replace value in a nested list?
upvote count: 3
has answer: http://stackoverflow.com/a/51318320
has answer: http://stackoverflow.com/a/51318296
downvote count: 0
has body: How do I replace James's salary from 1000 to 1500 and print James's data? data = [['Ben', 'Manager', 3000], ['James', 'Cleaner', 1000], ['Ken', 'Supervisor', 2000]] for (name,appt,salary) in data: if name == 'James': salary = 1500 print(linked_data[1]) Here's my current output: ['James', 'Cleaner', 1000] Expected output: ['James', 'Cleaner', 1500]
has answer: http://stackoverflow.com/a/51318471
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51318404
score: 3
has answer: http://stackoverflow.com/a/51318304
linked to: http://stackoverflow.com/q/18449360
has answer: http://stackoverflow.com/a/51318336
has answer: http://stackoverflow.com/a/51318577
favorite count: 0
answer count: 11
accepted answer: http://stackoverflow.com/a/51318296
has comment: http://stackoverflow.com/comment/89612394
possible better answer: http://stackoverflow.com/a/51318316
tagged with: python
has answer: http://stackoverflow.com/a/51318665
has answer: http://stackoverflow.com/a/51318316

http://stackoverflow.com/q/51191878
has body: How to use regex with different pattern in a multiline string in python str1 = '''' interface is up admin state is up mtu is 1500 ''' str2 = 'interface is up admin state is up' pat = re.compile(r"interface is ([A-za-z]+) admin state is ([A-za-z]+)") matches = pat.finditer(str2) for match in matches: print match.group() print match.group(1) print match.group(2) the above regex pattern works for str2 (which doesn;t have newline) but not for str1 which has the same text but with newline. I tried using re.M as well but that also doesn't seem to work. I wanted to filter the interface status, admin status and mtu with different patterns on a multiline string.
type: Question
has title: How to use regex with different pattern in a multiline string in python
answer count: 1
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/51191955
tagged with: python
has comment: http://stackoverflow.com/comment/89365750
type: AnsweredQuestion
score: 2
accepted answer: http://stackoverflow.com/a/51191955
upvote count: 2

http://stackoverflow.com/a/54423482
upvote count: 3
type: Answer
score: 3
downvote count: 0
answers question: http://stackoverflow.com/q/51225035
has body: # Create a Data Feed data = bt.feeds.GenericCSVData( dataname='filepath.csv', fromdate=datetime.datetime(2018, 1, 1), todate=datetime.datetime(2018, 12, 31), nullvalue=0.0, dtformat=('%Y-%m-%d'), datetime=0, open = 1, high = 2, low = 3, close = 4, volume =5, openinterest=-1, reverse=False) # Add the Data Feed to Cerebro cerebro.adddata(data) If this is what you are trying to accomplish, although i am not sure. https://www.backtrader.com/docu/datafeed.html

http://stackoverflow.com/q/51174564
type: Question
has body: I need to force/check the arguments sequence handed over to argparse. I tried the "try/except" approach but it does not seem to work. import argparse epilog = '''usage example:''' parser = argparse.ArgumentParser(description="add watchit hosts", epilog=epilog) parser.add_argument('--add', nargs='*', default="-1", metavar="key 'value'") args = vars(parser.parse_args()) try: args['add'][0] != 'name' args['add'][3] != 'desc' args['add'][5] != 'ip' except: print "wrong argument sequence, read the help message!" print args print args['add'][1] print args['add'][3] print args['add'][5] The following call should raise an error, since name is missing. root@lpgaixmgmtlx01:/root&gt;python argparse_test.py --add desc 'aixbuildhost - buildhost - Test(Linz)' ip '172.17.14.37' nagiostmpl 'Enable without Notification' tsm 'AIXBUILDHOST' witnode 'lvgwatchit01t' loc 'loc_gru' devgrp 'hg_aix_lpar' persgrp 'cg_aix' {'add': ['desc', 'aixbuildhost - buildhost - Test(Linz)', 'ip', '172.17.14.37', 'nagiostmpl', 'Enable without Notification', 'tsm', 'AIXBUILDHOST', 'witnode', 'lvgwatchit01t', 'loc', 'loc_gru', 'devgrp', 'hg_aix_lpar', 'persgrp', 'cg_aix']} aixbuildhost - buildhost - Test(Linz) 172.17.14.37 Enable without Notification ...and so on Any clever solution to force the arguments sequence?
answer count: 1
downvote count: 0
has title: python argparse: force argument sequence
favorite count: 0
has answer: http://stackoverflow.com/a/51174751
accepted answer: http://stackoverflow.com/a/51174751
tagged with: argparse
tagged with: python
type: AnsweredQuestion
score: 1
upvote count: 1

http://stackoverflow.com/comment/89549020
type: QuestionComment
comment on: http://stackoverflow.com/q/51285765
has text: Actually, I want to define different variables. Here, I want to define 3 variables not rename a single variable.
score: 0
type: Comment

http://stackoverflow.com/comment/89669333
has text: Holy crap what a detailed answer! Thank you so much! I hope you'll give me a bit to digest what's written here because I'm a noob at linear algebra, but I definitely get back to you once I do!
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51345219
type: Comment

http://stackoverflow.com/comment/89566690
type: Comment
has text: Sounds like a pure math question to me.
score: 0
comment on: http://stackoverflow.com/q/51294548
type: QuestionComment

http://stackoverflow.com/q/51264652
has comment: http://stackoverflow.com/comment/89507538
score: 0
answer count: 2
has title: Using same browser session in different cases
tagged with: selenium
has answer: http://stackoverflow.com/a/51270990
type: UnansweredQuestion
type: Question
has answer: http://stackoverflow.com/a/51264934
tagged with: python
has body: In the below code am trying to use the same browser session in different test cases, but after running its observed that two different browser sessions are opened for each test case. Please guide me to fix this issue: driver1 = webdriver.Chrome( executable_path="C:\\Program Files (x86)\\chromedriver.exe") class Test_Trials(unittest.TestCase): def test_1(self): driver1.set_page_load_timeout(20) driver1.get("http://192.168.221.238:8180/tnp/") driver1.maximize_window() def test_2(self): driver1.find_element_by_id("j_username").send_keys("admin") driver1.find_element_by_name("j_password").send_keys("admin1001") driver1.find_element_by_class_name("gwt-Button").click() driver1.set_page_load_timeout(20)

http://stackoverflow.com/comment/89445203
type: QuestionComment
type: Comment
has text: is this `https://github.com/gooofy/py-espeak-ng` ?
score: 0
comment on: http://stackoverflow.com/q/51232871

http://stackoverflow.com/comment/89422394
type: Comment
type: QuestionComment
has text: Can you show us the `jobs/basic_form.html` template?
comment on: http://stackoverflow.com/q/51214553
score: 0

http://stackoverflow.com/q/51175298
type: AnsweredQuestion
has title: float to embedded c float over UART
score: -5
has comment: http://stackoverflow.com/comment/89333361
has comment: http://stackoverflow.com/comment/89334150
tagged with: floating-point
type: Question
tagged with: ieee-754
accepted answer: http://stackoverflow.com/a/51175961
has body: I am trying to send python float's over UART to an Embedded c processor, the MKE14 from NXP. In python I am using the Struct library to make a 32 bit float and send this over UART. I checked both float impelementations and there both "IEEE-754". I send Decimal: 5.490715 Hex: 0x40, 0xAF, 0xB3, 0xF0 I receive in "Longitude" Decimal: 1085256688 Hex: 0x40, 0xAF, 0xB3, 0xF0 After float conv Decimal: 1085256704 Hex: 0x40, 0xAF, 0xB4, 0x00 It must be some conversion problem, I receive the right packet but the representation is tottaly different. The used code on both systems are in the attached file. Python code image Embedded C code
downvote count: 5
tagged with: http://stackoverflow.com/tag/c
tagged with: struct
answer count: 2
upvote count: 0
has comment: http://stackoverflow.com/comment/89334261
possible better answer: http://stackoverflow.com/a/51176064
favorite count: 0
has answer: http://stackoverflow.com/a/51176064
has answer: http://stackoverflow.com/a/51175961
tagged with: python
has comment: http://stackoverflow.com/comment/89333853

http://stackoverflow.com/q/51312948
answer count: 1
tagged with: caldav
has title: How to get freebusy details in python-caldav library
type: UnansweredQuestion
has body: I am using python-caldav and vobject Python libraries to connect to and parse calendar files from a private caldav server. I cannot for the life of me figure out how to make a freebusy request using these libraries. I've searched through the documentation and have searched and searched for examples, but I cannot seem to find any information anywhere. If anyone has any information, I would greatly appreciate it. Here is an example from caldav library using details I found in the repo. url = "https://" + username + ":" + password + "@domain.com/" client = caldav.DAVClient(url) principal = client.principal() calendars = principal.calendars() calendar = calendars[1] freebusy = calendar.freebusy_request(datetime(2018,7,12, 12, 0, 0), datetime(2018,7,13, 12, 0, 0)) It returns the following error: caldav.lib.error.ReportError: 406 Not Acceptable
tagged with: python
tagged with: vobject
has answer: http://stackoverflow.com/a/51335194
type: Question
tagged with: icalendar
score: 0

http://stackoverflow.com/a/65411584
has comment: http://stackoverflow.com/comment/125240535
downvote count: 0
score: 6
type: Answer
upvote count: 6
answers question: http://stackoverflow.com/q/51219531
has body: To add on to @Gopesh Kwandelwal's answer sudo apt install ffmpeg an alternative is to have Anaconda or Miniconda installed, then use: conda install ffmpeg This worked for me when inside a custom environment, and didn't even require restarting the kernel, let alone restarting the computer. (I couldn't comment on that thread b/c I don't have enough reputation).

http://stackoverflow.com/comment/89398753
has text: different companies :)
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51175638

http://stackoverflow.com/q/51314302
has body: I have two dataframes like- a b c c d f 2 4 6 6 7 1 4 7 9 9 5 8 Now I want to make a new dataframe which looks like- a b c d f 2 4 6 7 1 4 7 9 5 8 I tried merge,concat,append but no of them worked for me when using on the real dataset. like- pd.append([df,df2],axis=1) pd.concat([df,df2], ignore_index=True,axis=1)
type: UnansweredQuestion
downvote count: 3
upvote count: 1
has comment: http://stackoverflow.com/comment/89605348
has comment: http://stackoverflow.com/comment/89605687
has title: Stacking dataframes sideways with common column
type: Question
has comment: http://stackoverflow.com/comment/89605333
score: -2
answer count: 1
has comment: http://stackoverflow.com/comment/89606368
favorite count: 0
has comment: http://stackoverflow.com/comment/89605425
has comment: http://stackoverflow.com/comment/89605572
tagged with: pandas
has comment: http://stackoverflow.com/comment/89606491
tagged with: python
has comment: http://stackoverflow.com/comment/89606434
has comment: http://stackoverflow.com/comment/89605362
has answer: http://stackoverflow.com/a/51317475
has comment: http://stackoverflow.com/comment/89705071
has comment: http://stackoverflow.com/comment/89605414
has comment: http://stackoverflow.com/comment/89625797

azure
tags question: http://stackoverflow.com/q/51304669
tags question: http://stackoverflow.com/q/51274664
tags question: http://stackoverflow.com/q/51275815
tags question: http://stackoverflow.com/q/51253977
tags question: http://stackoverflow.com/q/51255586
tags question: http://stackoverflow.com/q/51192025
type: Tag
tags question: http://stackoverflow.com/q/51180033
tags question: http://stackoverflow.com/q/51182199
tags question: http://stackoverflow.com/q/51209613
tag name: azure

http://stackoverflow.com/a/51235009
upvote count: 3
type: Answer
has body: If you want to separate it by making group of some specific numbers of character then you can do it simply using textwrap's wrap function. In our case the number of characters in group is 2. &gt;&gt;&gt;from textwrap import wrap &gt;&gt;&gt;v = 0xFFFF &gt;&gt;&gt;print list('0x' + x.upper() for x in wrap(str(hex(v))[2:], 2)) &gt;&gt;&gt;v = 0xFFFFF &gt;&gt;&gt;print list('0x' + x.upper() for x in wrap(str(hex(v))[2:], 2)) &gt;&gt;&gt;print list(int('0x' + x, 16) for x in wrap(str(hex(v))[2:], 2)) Output: &gt;&gt;&gt;['0xFF', '0xFF'] &gt;&gt;&gt;['0xFF', '0xFF', '0xF'] &gt;&gt;&gt;[255, 255, 15] *Note: wrap function makes the group from starting of the string and if the length of string is not the multiple of the number of which we have to make groups, it will make group of remaining characters (as making groups from starting of the string) at last.
score: 3
answers question: http://stackoverflow.com/q/51234380
downvote count: 0

http://stackoverflow.com/q/51185274
tagged with: python
has answer: http://stackoverflow.com/a/51190906
has comment: http://stackoverflow.com/comment/89353792
has comment: http://stackoverflow.com/comment/89354408
tagged with: parallel-processing
has comment: http://stackoverflow.com/comment/89354531
type: Question
has comment: http://stackoverflow.com/comment/89354776
has body: I am trying to fit a rather large dataset (~10 million samples, 15 features) using SVC. When I run it as a single job it appears to run fine, but after several hours it is still not done. I have a remote connection to a workstation with 40 logical cores and 125 Gigs of memory, so it should be straightforward to transfer my code and data to that machine and use either the BaggingClassifier or the OneVsRestClassifier and then set n_jobs=-1 or n_jobs=10. However when I do that, a lot of new python proccesses are created, each with identical memory usage, but all of them are stuck at zero percent cpu usage. Any idea what is going on? This is my code. The shape of data is (10046977, 15). import numpy as np from sklearn import svm from sklearn.ensemble import BaggingClassifier from sklearn.multiclass import OneVsRestClassifier data = np.loadtxt('training.csv', header=None, dtype=float, usecols=range(2,17)) types = np.loadtxt('training.csv', header=None, dtype=str, usecols=(17,)) clf = OneVsRestClassifier(svm.SVC(gamma=0.001, C=100), n_jobs=-1) clf.fit(data[:], types[:]) EDIT I am using Ubuntu 16.04 for this particular issue.
has comment: http://stackoverflow.com/comment/89357561
score: 0
answer count: 1
tagged with: scikit-learn
has comment: http://stackoverflow.com/comment/89353207
tagged with: python-3.x
type: UnansweredQuestion
has title: OneVsRestClassifier with n_jobs > 1 stuck with zero percent cpu usage for all jobs

http://stackoverflow.com/q/51300460
tagged with: sage
answer count: 1
has answer: http://stackoverflow.com/a/51308972
downvote count: 0
favorite count: 0
tagged with: python
tagged with: jupyter
has title: How to install SageMath kernel in Anaconda?
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51308972
tagged with: jupyter-kernel
type: Question
tagged with: anaconda
has body: I'm trying to use Sage in Anaconda 3 but it looks that the libraries are not imported. I firstly created a new environment 'ipykernel_py2' and then installed Python 2 as explained in here. With this I can have both Python 3 and Python 3 up and running in Anaconda 3. Then I went to the kernel's folder created (C:\Users\YOUR_USERNAME\AppData\Local\Continuum\anaconda3\envs\ipykernel_py2\share\jupyter\kernels) and pasted Sage's kernel (taken from C:\Program Files\SageMath 8.2\runtime\opt\sagemath-8.2\local\share\jupyter\kernels). This allows to create new SageMath files in Jupyter but the kernel is dead. To activate the kernel I used Anaconda Prompt and typed: activate ipykernel_py2 python -m ipykernel install --user --name sagemath --display-name "SageMath 8.2" So the kernel is now activated and I can create and run Sage files. However the libraries are still not working. It seems that the file is running like a normal Python 2 file. Does anyone know how to fix this? Do I need to create a seperate environment?
score: 4
upvote count: 4

http://stackoverflow.com/comment/89437872
score: 0
type: QuestionComment
type: Comment
has text: @abarnert if the other questions you're referring to are the ones in your first comment, I'm using MacOS and PyCharm(Python 2.7)
comment on: http://stackoverflow.com/q/51229013

http://stackoverflow.com/q/51251668
tagged with: mysql
has comment: http://stackoverflow.com/comment/89483666
type: Question
has comment: http://stackoverflow.com/comment/89483857
has comment: http://stackoverflow.com/comment/89483979
has title: Fix password hash getting truncated when imported to MySQL table
has comment: http://stackoverflow.com/comment/89483542
tagged with: flask
has comment: http://stackoverflow.com/comment/89512251
answer count: 1
has comment: http://stackoverflow.com/comment/89519851
has comment: http://stackoverflow.com/comment/89482736
has comment: http://stackoverflow.com/comment/89483994
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/247304
tagged with: python
has body: I currently have a Flask app that registers a Username and password to a MySQL database. My problem is that using Bcrypt to hash passwords and then save to them to the database, the outputted hash gets truncated by MySQL. My function looks like this: class PasswordResource(Resource): @app.route('/password', methods=['GET']) @jwt_required def sendPassword(): data = get_jwt_identity() hashed_password = bcrypt.hashpw(data['user_password'].encode('utf8'), bcrypt.gensalt()) print(hashed_password) return mysqldb.addPassword("{}".format(str(data['user_name'])),"{}".format(hashed_password)) and connects to the database: def addPassword(Username,Userpassword): try: cursorObject = connection.cursor() cursorObject.execute("call sp_createPassword('{}'".format(Username)+",'{}')".format(Userpassword)) connection.commit() connection.close() finally: return 'User added succesfully!' However, the hash gets truncated by MySql even though I have tried various VARCHAR() for the password table. This is an error i get in console Warning: (1265, u"Data truncated for column 'p_password' at row 1") self._do_get_result(). My password column currently is configured to VARCHAR(255), Not Null. How can I fix this error and avoid having the hashes getting truncated? UPDATE This is would be the schema for my password table: +---------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | Table | Create Table | +---------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | tbl_passwords | CREATE TABLE `tbl_passwords` ( `user_name` …
has comment: http://stackoverflow.com/comment/89483510
has comment: http://stackoverflow.com/comment/89483390
has answer: http://stackoverflow.com/a/51270225
tagged with: bcrypt
score: 0

http://stackoverflow.com/q/51227309
score: 0
tagged with: libxml2
answer count: 1
tagged with: dtd-parsing
has body: I am currently limited to using libxml2 (instead of lxml) for parsing on QNX 6.5. I want to validate my xml using a DTD loaded from a string, instead of from a file. lxml lets you do this: import lxml from lxml import etree from StringIO import StringIO dtd_string = """ <!ELEMENT page (title)> <!ELEMENT title (#PCDATA)> """ xml = """ Hello """ dtd = etree.DTD(StringIO(dtd_string)) root = etree.fromstring(xml) is_valid = dtd.validate(root) I would like to do the same using libxml2. I can load the DTD from file, but don't know and can't find the syntax to load it from string: import libxml2 dtd = libxml2.parseDTD(None, dtd_file) #How to parse DTD from a string?? ctxt = libxml2.newValidCtxt() doc = libxml2.parseDoc(xml) is_valid = doc.validateDtd(ctxt, dtd) #cleanup omitted Does anyone happen to know how to do this in libxml2?
has answer: http://stackoverflow.com/a/52227742
type: UnansweredQuestion
tagged with: python
has title: Loading a DTD from text using libxml2 for python
type: Question

http://stackoverflow.com/q/51267998
linked to: http://stackoverflow.com/q/19843116
type: Question
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/89515812
has comment: http://stackoverflow.com/comment/89514573
tagged with: python
tagged with: nonlinear-optimization
has comment: http://stackoverflow.com/comment/89518579
answer count: 0
type: UnansweredQuestion
score: 1
linked to: http://stackoverflow.com/q/31388319
upvote count: 1
tagged with: scipy
has title: Object as arguments to fsolve
has body: I'm trying to solve what is effectively a non-linear equation, containing a spline object. Since I want to do this many times with different data I don't want to create a new function for each data set, but create only one function and pass the spline on as an argument. The data are in reality experimental data to which I fit a spline and the equation I'm trying to solve is rather complicated, but to illustrate my problem I'm using a simple sine function in the example below. import numpy as np from scipy import interpolate from scipy.optimize import fsolve import matplotlib.pyplot as plt def equation(x0,func): return ( interpolate.splev(x0,func) - 1 ) x = np.arange(0,2*np.pi,1) y = np.sin(x) yy = interpolate.splrep(x,y) x0 = 3 root = fsolve(equation,x0,yy) I get the following error: TypeError: equation() takes exactly 2 arguments (4 given) How can I do this? Any suggestion? Maybe it cant be done this way, and if so, is there another solution?
has comment: http://stackoverflow.com/comment/89516843

http://stackoverflow.com/comment/89678133
has text: @Code-Apprentice I did as you suggested, and I located the problematic HTML. Where the table is usually located was instead replaced by:" Rates not available on requested date. Please try another date." Which is weird because I get a valid URL that I can go and manually get the HTML from.
comment on: http://stackoverflow.com/q/51315550
score: 0
type: Comment
type: QuestionComment

pyorient
tag name: pyorient
tags question: http://stackoverflow.com/q/51228377
type: Tag

http://stackoverflow.com/comment/89539295
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51276337
has text: @juanpa.arrivillaga These class attributes are constant by semantics. Say, DEFAULT_CONNECTION_IP.
score: 0

http://stackoverflow.com/comment/136518704
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).
score: 1
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/77437440

http://stackoverflow.com/comment/89598432
comment on: http://stackoverflow.com/a/51309711
score: 0
type: Comment
has text: @Brandon - Can you let me know if the formatting works with returning ' return out.as_matrix()'?
type: AnswerComment

http://stackoverflow.com/a/51221023
has comment: http://stackoverflow.com/comment/89428404
has comment: http://stackoverflow.com/comment/89427299
upvote count: 2
score: 2
has comment: http://stackoverflow.com/comment/89423557
has body: The manager of a model is a regular instance of its respective class, so you could implement some kind of registry. However, this registry would be unique per process. In production, your application is usually run by a server starting multiple processes e.g. uwsgi (or even run on multiple machines). If you want to make transient data available in your whole application, you can use Django's caching facilities with an in-memory store like Memcached or Redis.
answers question: http://stackoverflow.com/q/51220853
downvote count: 0
type: Answer

http://stackoverflow.com/q/51305317
accepted answer: http://stackoverflow.com/a/51350871
downvote count: 0
tagged with: spectrogram
has comment: http://stackoverflow.com/comment/89591005
favorite count: 0
has comment: http://stackoverflow.com/comment/89596385
tagged with: python
tagged with: librosa
has title: Why spectrogram from librosa library have twice the time duration of the actual audio track?
tagged with: audio
type: AnsweredQuestion
upvote count: 3
possible better answer: http://stackoverflow.com/a/66974183
has comment: http://stackoverflow.com/comment/89595758
has answer: http://stackoverflow.com/a/51350871
has comment: http://stackoverflow.com/comment/89592652
has answer: http://stackoverflow.com/a/66974183
type: Question
score: 3
has comment: http://stackoverflow.com/comment/89595886
has comment: http://stackoverflow.com/comment/89596153
answer count: 2
has body: I am using the following code to obtain Mel spectrogram from a recorded audio signal of about 30 s: spectrogram = librosa.feature.melspectrogram(y=self.RawSamples,sr=self.SamplingFrequency, n_mels=128, fmax=8000) if show: plt.figure(figsize=(10, 4)) librosa.display.specshow(librosa.power_to_db(self.Spectrogram, ref=np.max), y_axis='mel', fmax=8000, x_axis='time') plt.colorbar(format='%+2.0f dB') plt.title('Mel spectrogram') plt.tight_layout() Obtained spectrogram: Mel spectrogram Can you please explain me why the time axis depicts twice the time duration (it should be 30 s). What is going wrong with the code?

http://stackoverflow.com/comment/89641686
type: Comment
comment on: http://stackoverflow.com/a/51269282
has text: But thank you for your information. It was quite helpful and shed some light on the details of the implementation. Thank you!
type: AnswerComment
score: 0

http://stackoverflow.com/comment/89537140
has text: Thank you for your answer!...I found an answer and I posted it. It seems a bit like yours. Would you please help to check my code to see if it is fine?
comment on: http://stackoverflow.com/a/51279112
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/89594897
score: 0
has text: @Mr.Developer Another strategy is to call python file through Python.h, but that strategy involves knowing the library which is an additional time. The methods I indicated in my previous comment involve only communication, not importation. You can also use boost as indicated in another comment.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51306118

http://stackoverflow.com/comment/89571988
type: QuestionComment
comment on: http://stackoverflow.com/q/51288802
has text: @McAngus does it means that directly training my model for say 5000 iterations and training in steps of 1000 iterations for 5 times will have similar results?
score: 0
type: Comment

http://stackoverflow.com/comment/89373875
has text: It will go in views.py ? I have tried return (Blog.objects.filter(date__lte=timezone.now()) .order_by('-date') .annotate( author_total_blogs = Count('author') ) but it doesnt give the correct figure
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51195679
score: 0

http://stackoverflow.com/q/51249975
has title: Scraping a 'p' tag value associated with a 'tr class' tag
tagged with: http://stackoverflow.com/tag/html
has body: I'm using Anaconda and BeautifulSoup to scrape data off a site. import requests resp = requests.get('https://www.url.com') Weathertest = resp.text from bs4 import BeautifulSoup soup = BeautifulSoup(Weathertest,'lxml') mintemp = BeautifulSoup(Weathertest, 'lxml') mintemp.find_all('p',class_='weatherhistory_results_datavalue temp_mn') What I'm trying to do is pull the minimum temperature for a particular day. Here's the html of the page: &lt;tr class="weatherhistory_results_datavalue temp_mn"&gt;&lt;th&gt;&lt;h3&gt;Minimum Temperature&lt;/h3&gt;&lt;/th&gt;&lt;td&gt;&lt;p&gt;&lt;span class="value"&gt;47.3&lt;/span&gt; &lt;span class="units"&gt;&amp;#176;F&lt;/span&gt;&lt;/p&gt;&lt;/td&gt;&lt;/tr&gt; I realized after I tried the above and got the result of [] that the weatherhistory class is not a p class so the above doesn't work. Instead, I tried: mintemp = BeautifulSoup(Weathertest, 'lxml') mintemp.find_all('tr',class_='weatherhistory_results_datavalue temp_mn') And the result I got is the entire html string above (from tr class through the /tr). I've tried finding how to pull a p value from a tr class but I'm not coming up with anything. I'm fairly new to all this, so I'm sure it's something simple I just don't know yet. Or perhaps I need a compound statement, like "find all the tr class above and then give me the p value" but I'm not sure how to code that.
has answer: http://stackoverflow.com/a/51250362
type: UnansweredQuestion
tagged with: web-scraping
upvote count: 1
tagged with: python
tagged with: anaconda
score: 1
type: Question
downvote count: 0
answer count: 1
favorite count: 0
tagged with: beautifulsoup

http://stackoverflow.com/comment/89394988
has text: `array.insert( 0, val )` ?
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51207005
score: 1

http://stackoverflow.com/comment/89428603
score: 1
comment on: http://stackoverflow.com/q/51219068
has text: The format at the top of the bar means, for example, that the bottom value of the bar is -1.357e-7 - 8.0e-11. If you don't mind scaling you could plot with `pcolor(1e7*np.transpose(Kappa))` for a cleaner scale.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51847744
downvote count: 1
has comment: http://stackoverflow.com/comment/90652623
answers question: http://stackoverflow.com/q/51262031
upvote count: 12
type: Answer
has comment: http://stackoverflow.com/comment/106913003
has body: The issue is probably that you haven't grouped your files as a package. The Beam documentation has a section on it. Multiple File Dependencies Often, your pipeline code spans multiple files. To run your project remotely, you must group these files as a Python package and specify the package when you run your pipeline. When the remote workers start, they will install your package. To group your files as a Python package and make it available remotely, perform the following steps: Create a setup.py file for your project. The following is a very basic setup.py file. setuptools.setup( name='PACKAGE-NAME' version='PACKAGE-VERSION', install_requires=[], packages=setuptools.find_packages(), ) Structure your project so that the root directory contains the setup.py file, the main workflow file, and a directory with the rest of the files. root_dir/ setup.py main.py other_files_dir/ See Juliaset for an example that follows this required project structure. Run your pipeline with the following command-line option: --setup_file /path/to/setup.py Note: If you created a requirements.txt file and your project spans multiple files, you can get rid of the requirements.txt file and instead, add all packages contained in requirements.txt to the install_requires field of the setup call (in step 1).
score: 11

http://stackoverflow.com/comment/89345768
comment on: http://stackoverflow.com/a/51181571
type: Comment
score: 1
has text: @DyZ You're absolutely right that `truncate` isn't needed in this very case, but in general you want to truncate if you aren't sure about the size of the replacement versus the original in advance. I just put it there so that the solution is more generic.
type: AnswerComment

http://stackoverflow.com/q/51241499
answer count: 1
downvote count: 0
has title: Parameters to control the size of a spectrogram
tagged with: spectrogram
favorite count: 0
has body: I am trying to get the spectrogram as described by the following instruction. Each audio segment has duration of 5s. Frames with equal size are extracted from the audio (with overlap between the consecutive frames), and each of the frame consists of 1024 samples. The mel-scale is divided into 128 bins. Therefore, the spectrogram for the audio segment has the dimension of 192×128. To my knowledge, this instruction implies n_mels=128 and n_fft=1024 in the melspectrogram function. So I tried to get a spectrogram with the following code: from librosa import load, power_to_db from librosa.display import specshow from librosa.feature import melspectrogram audio_path = r'5s.wav' y, sr = load(audio_path,sr=44100) S = melspectrogram(y,sr,n_mels=128,n_fft=1024,hop_length=512) print(S.shape) The shape of y is (220500,) and the sampling rate sr is 44100 And the spectrogram shape I get is (128, 431). The 128 mel-scale size is correct, yet the number of frames I get is 431 instead of 192 frames mentioned in the instruction. In order to get 192 frames, I changed the sampling rate to 22050 and keep adjusting the hop_lenghtuntil the spectrogram has 192 frames: audio_path = r'5s.wav' y, sr = load(audio_path,sr=22050) S = melspectrogram(y,sr,n_mels=128,n_fft=1024,hop_length=575) print(S.shape) However, I am not sure if it is the correct way to get the spectrogram dimension that I want. It seems the process is just trial and error. I wonder if there is a more scientific way to get a spectrogram with the shape that I want without guessing the parameter values?
tagged with: python
tagged with: librosa
score: 2
upvote count: 2
type: UnansweredQuestion
tagged with: signal-processing
type: Question
has answer: http://stackoverflow.com/a/51245080

http://stackoverflow.com/a/51198753
has comment: http://stackoverflow.com/comment/89398060
answers question: http://stackoverflow.com/q/51198633
has body: In that case you can perform perform for example an itertools.groupby: # views.py from itertools import groupby from operator import attrgetter from django.db.models import Min def some_view(request): bs = B.objects.prefetch_related( 'foreign_key' ).annotate( first_b=Min('foreign_key__b__time') ).order_by('first_b', 'time') groups = groupby(bs, key=attrgetter('foreign_key')) return render(request, 'some_template.html', {'groups': groups}) And then as template (some_template.html), we can use: &lt;ul&gt; {% for group, items in groups %} &lt;li&gt;{{ group.title }}&lt;/li&gt; &lt;ul&gt; {% for item in items %} &lt;li&gt;{{ item.time }}&lt;/li&gt; {% endfor %} &lt;/ul&gt; {% endfor %} &lt;/ul&gt;
has comment: http://stackoverflow.com/comment/89380206
has comment: http://stackoverflow.com/comment/89380438
has comment: http://stackoverflow.com/comment/89380149
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/89408420

http://stackoverflow.com/comment/89467417
type: QuestionComment
comment on: http://stackoverflow.com/q/51244350
score: 1
has text: Probably. Can you be more specific about what they're doing with FoxPro, i.e. just querying the database in a way you could with SQL Server Management Studio, say, or then transforming and visualising the data in way which would require some programming? However this is possibly a too-opinionated question for StackOverflow. Justifiable to keep using - that's up to them I'd guess? If it still works for them and there's no maintenance issues why do you want them to move?
type: Comment

http://stackoverflow.com/a/63755137
has comment: http://stackoverflow.com/comment/136905750
answers question: http://stackoverflow.com/q/51286748
type: Answer
has comment: http://stackoverflow.com/comment/114618056
has comment: http://stackoverflow.com/comment/125008593
upvote count: 5
downvote count: 5
score: 0
has comment: http://stackoverflow.com/comment/117645314
has body: A much simpler answer can be found on Reddit using dictionary unpacking &gt;&gt;&gt; from dataclasses import dataclass &gt;&gt;&gt; @dataclass ... class MyData: ... prop1: int ... prop2: str ... prop3: int ... &gt;&gt;&gt; d = {'prop1': 5, 'prop2': 'hi', 'prop3': 100} &gt;&gt;&gt; my_data = MyData(**d) &gt;&gt;&gt; my_data MyData(prop1=5, prop2='hi', prop3=100)

http://stackoverflow.com/q/51323224
tagged with: python
type: AnsweredQuestion
score: 2
has comment: http://stackoverflow.com/comment/89646728
downvote count: 0
tagged with: tk-toolkit
type: Question
upvote count: 2
has answer: http://stackoverflow.com/a/51338440
accepted answer: http://stackoverflow.com/a/51338440
has body: I have an application wherein, I have to pop a Spinbox widget on click of a button. The widget needs to be overlayed on a background which is an image. I have tried with the code below, but the widget does not appear on the click of the button. I believe the image display is taking precedence over the widget display. import tkinter as tk import cv2 from PIL import Image,ImageTk top = tk.Tk() count = 1 image = cv2.imread("frames/0.jpg") w = tk.Spinbox(top, from_=0, to=10) def helloCallBack(): global count,w if count%2 != 0: w.pack() else: w.forget() print(count) count+=1 B = tk.Button(top, text ="Hello", command = helloCallBack) B.pack() label = tk.Label(top) label.pack() img = Image.fromarray(image) imgtk = ImageTk.PhotoImage(image=img) label.imgtk = imgtk label.configure(image=imgtk) top.update() top.mainloop()
answer count: 1
has title: Overlaying a tkinter widget on an image frame
has comment: http://stackoverflow.com/comment/89624500
has comment: http://stackoverflow.com/comment/89625914
favorite count: 0
tagged with: python-3.x
tagged with: tkinter
has comment: http://stackoverflow.com/comment/89646544
linked to: http://stackoverflow.com/q/10158552

http://stackoverflow.com/a/51181610
accepted answer of: http://stackoverflow.com/q/51181384
upvote count: 5
answers question: http://stackoverflow.com/q/51181384
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: pyspark.sql.types are schema descriptors, not collections or external language representations so cannot be used with fold or Accumulator. The most straightforward solution is to explode and aggregate from pyspark.sql.functions import explode df = spark.createDataFrame( [{'a': 1, 'b': 2, 'c': 3}, {'a': 2, 'b': 4, 'd': 6}], "map&lt;string,integer&gt;" ).toDF("Maps") df.select(explode("Maps")).groupBy("key").sum("value").rdd.collectAsMap() # {'d': 6, 'c': 3, 'b': 6, 'a': 3} With RDD you can do a similar thing: from operator import add df.rdd.flatMap(lambda row: row.Maps.items()).reduceByKey(add).collectAsMap() # {'b': 6, 'c': 3, 'a': 3, 'd': 6} or if you really want fold from operator import attrgetter from collections import defaultdict def merge(acc, d): for k in d: acc[k] += d[k] return acc df.rdd.map(attrgetter("Maps")).fold(defaultdict(int), merge) # defaultdict(int, {'a': 3, 'b': 6, 'c': 3, 'd': 6})
score: 5

http://stackoverflow.com/comment/89470950
comment on: http://stackoverflow.com/q/51213822
has text: Since that was the solution to the problem, may, @Sagasaki, post the good answer not as a comment but as an answer in order SoulMan be able to accept it and thus so help other SO users?
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/comment/89646438
type: AnswerComment
has text: Works like a charm – fantastic! Thank you very much!
type: Comment
comment on: http://stackoverflow.com/a/51333847
score: 0

http://stackoverflow.com/comment/89496668
comment on: http://stackoverflow.com/a/51245176
score: 0
type: AnswerComment
type: Comment
has text: @CallumTwig, this program is not generating a name, but works on an existing one. The sample name used in the program is "abc". I have updated my answer to make it more clear.

http://stackoverflow.com/comment/89599103
type: QuestionComment
comment on: http://stackoverflow.com/q/51310197
has text: I would suggest then some tutorial about gdb or pdb (Python debugger). Try https://www.youtube.com/watch?v=bZZTeKPRSLQ&t=350s
score: 0
type: Comment

http://stackoverflow.com/comment/89364385
has text: @RishikeshJha as mentioned, it does not error and does not hit exception. Both times it looks to execute fine, but if I exclude the print statements, then the newly created unix user does not authenticate with that password. If i put the print lines back in, everything works fine.
score: 0
comment on: http://stackoverflow.com/q/51191085
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51260036
tagged with: lint
linked to: http://stackoverflow.com/q/6412146
downvote count: 0
tagged with: decorator
tagged with: static-analysis
favorite count: 0
has comment: http://stackoverflow.com/comment/89498982
possible better answer: http://stackoverflow.com/a/51260639
accepted answer: http://stackoverflow.com/a/51260453
has body: I want to define a decorator within a class. I don't want to define it as a separated, independent function, for this decorator is specifically for this class and I want to keep the correlated methods together. The purpose of this decorator is to check some prerequisites, especially the database connection, SSH connection, etc., which are held by member variables, are still available. If not, the decorated function won't be called and some error reporting and clean-up works will be done. I made the following testing class to test if it works, and the code did work well. But I found that PyCharm shows warnings to this piece of code. So I wonder, if it means that my code is not Pythonic, or PyCharm is not smart enough and gave this warning by mistake? If my code is is not Pythonic, how to change? If it is PyCharm's mistake, how shall I and my team configure PyCharm to let it specifically ignore this kind of warning while keep most other lint check? class TestClass: def __init__(self): self.flag = True def dec(func): def wrapper(self, *args, **kwargs): if not self.flag: print("Won't run!") return empty_fun(self, *args, **kwargs) return func(self, *args, **kwargs) def empty_fun(*args, **kwargs): return None return wrapper @dec def foo(self): print("foo") @dec def bar(self, msg, more, *args, **kwargs): print("message: %s" % msg) print("more %s:" % more) for item in args: print("other item: %s" % item) name = kwargs.get('name') age = kwargs.get('age') print('name: %s' % name) print('age: %s' % age) def main(): t = TestClass() t.foo() print('-'*10) t.bar("abc", 'def', 'hij', 'klm', name='Tom', age=20) if __name__ == '__main__': main() Here is the lint warning reported by PyCharm:
tagged with: python
type: AnsweredQuestion
tagged with: pycharm
has title: Is my in-class decorator not Pythonic enough or PyCharm not smart enough in lint warning?
type: Question
score: 5
has answer: http://stackoverflow.com/a/51260453
upvote count: 5
has comment: http://stackoverflow.com/comment/89498905
answer count: 2
has answer: http://stackoverflow.com/a/51260639

http://stackoverflow.com/comment/89523336
score: 3
has text: `"12" >= '3'` is `False`, for example. Is this what you intend? If not, casting the values to `int`s (and catching any errors) is probably nicer than doing string comparisons.
comment on: http://stackoverflow.com/q/51272645
type: Comment
type: QuestionComment

http://stackoverflow.com/a/60565838
answers question: http://stackoverflow.com/q/51272691
score: 0
type: Answer
has body: import os dirList = os.listdir() for directory in dirList: if os.path.isdir(directory): print('Directory Name: ', directory) print('File List: ', os.listdir(directory))

scheme
tag name: scheme
type: Tag
tags question: http://stackoverflow.com/q/51294880

http://stackoverflow.com/comment/89520683
comment on: http://stackoverflow.com/a/51255374
score: 1
type: AnswerComment
has text: This perfectly solved my problem and thanks for reminding me of "return_sequences", I actually have met this problem. Thanks a lot!
type: Comment

http://stackoverflow.com/a/51320514
type: Answer
answers question: http://stackoverflow.com/q/51304016
has body: Here's the solution I'm most happy with. It boils down to: some_dict['foo']['bar']['baz'] = 1 is equal to (some_dict['foo']['bar']['baz']) = 1 which you can break anywhere you want, like so: (some_dict['foo'] ['bar']['baz']) = 1 Which should be aligned with Pythons preferred way to break long lines, using Python's implied line continuation inside parentheses.
upvote count: 14
score: 14
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51304016

openpyxl
tags question: http://stackoverflow.com/q/51223048
tags question: http://stackoverflow.com/q/51238985
type: Tag
tags question: http://stackoverflow.com/q/51239236
tags question: http://stackoverflow.com/q/51300015
tags question: http://stackoverflow.com/q/51233280
tag name: openpyxl
tags question: http://stackoverflow.com/q/51291524
tags question: http://stackoverflow.com/q/51178491
tags question: http://stackoverflow.com/q/51200747
tags question: http://stackoverflow.com/q/51248929
tags question: http://stackoverflow.com/q/51283088
tags question: http://stackoverflow.com/q/51230017
tags question: http://stackoverflow.com/q/51251325

http://stackoverflow.com/comment/89595479
comment on: http://stackoverflow.com/q/51308220
type: Comment
type: QuestionComment
has text: From the stackoverflow question asking help page: "Not all questions benefit from including code. But if your problem is with code you've written, you should include some. But don't just copy in your entire program! Not only is this likely to get you in trouble if you're posting your employer's code, it likely includes a lot of irrelevant details that readers will need to ignore when trying to reproduce the problem." I'm not just C+Ping my entire code straight into my post. I have included " just enough code to allow others to reproduce the problem".
score: 0

http://stackoverflow.com/comment/89402543
type: Comment
has text: Read the documentation for the function.
score: 9
type: QuestionComment
comment on: http://stackoverflow.com/q/51210887

http://stackoverflow.com/q/51313429
favorite count: 0
has answer: http://stackoverflow.com/a/51313474
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/51313514
has body: I have the following test.txt data, and I want to to check the occurrence of each state and show it as summary output. I am able to count how many times which state occurred using following logic for line in file: if 'success' in line: count+=1 but I am unable to add a column and append it to the end like my output. Any help will be highly appreciated. Sample Input ------------------------- 11/11/2015 9.9.9.9 30s success 11/11/2015 9.9.9.8 30s stuck 11/11/2015 9.9.9.9 30s Sync 11/11/2015 9.9.9.9 30s success 11/12/2015 9.9.9.9 30s success 11/12/2015 9.9.9.9 30s stuck 11/12/2015 9.9.9.9 30s stuck 11/12/2015 9.9.9.9 30s success 11/12/2015 9.9.9.8 30s success 11/12/2015 9.9.9.9 30s success 11/12/2015 9.9.9.9 30s stuck 11/12/2015 9.9.9.9 30s success 11/12/2015 9.9.9.9 30s Sync 11/12/2015 9.9.9.9 30s Sync --------------------Output I want ------------------------- 11/11/2015 9.9.9.9 success 2 11/11/2015 9.9.9.8 stuck 1 11/11/2015 9.9.9.9 Sync 1 11/12/2015 9.9.9.9 success 4 11/12/2015 9.9.9.9 stuck 3 11/12/2015 9.9.9.9 Sync 2 11/12/2015 9.9.9.8 success 1
upvote count: 0
tagged with: list
type: Question
score: -1
has title: Parse sample data using python
tagged with: python-2.7
answer count: 2
downvote count: 1
tagged with: scripting
tagged with: pydictionary

http://stackoverflow.com/q/51320667
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51323076
has answer: http://stackoverflow.com/a/65388955
possible better answer: http://stackoverflow.com/a/57633393
has answer: http://stackoverflow.com/a/67257000
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/89620649
upvote count: 9
has answer: http://stackoverflow.com/a/51321460
has body: def fun(s): for i in s: if i.isalnum(): print("True") if i.isalpha(): print("True") if i.isdigit(): print("True") if i.isupper(): print("True") if i.islower(): print("True") s=input().split() fun(s) why it prints true only once even though it is in a for loop
has comment: http://stackoverflow.com/comment/89616958
has answer: http://stackoverflow.com/a/51323076
has answer: http://stackoverflow.com/a/76213209
tagged with: string
favorite count: 0
score: 8
has title: I have to check if the string contains: alphanumeric, alphabetical , digits, lowercase and uppercase characters
has answer: http://stackoverflow.com/a/60693771
tagged with: python-3.x
has answer: http://stackoverflow.com/a/71662934
has answer: http://stackoverflow.com/a/68429762
has answer: http://stackoverflow.com/a/61911934
answer count: 10
tagged with: python
has answer: http://stackoverflow.com/a/57633393

http://stackoverflow.com/a/51237375
answers question: http://stackoverflow.com/q/51237363
has body: You can check if the first parameter (x) is a tuple: from functools import reduce marks = [("Jon" ,29 ), ("santi",35), ("anna",35)] new_marks = reduce(lambda x, y:(x if isinstance(x, int) else x[-1])+y[-1], marks) assert new_marks == sum(b for _, b in marks) print(new_marks) Output: 99
has comment: http://stackoverflow.com/comment/89453806
has comment: http://stackoverflow.com/comment/89453950
has comment: http://stackoverflow.com/comment/89453824
type: Answer
upvote count: 3
downvote count: 2
has comment: http://stackoverflow.com/comment/89453877
score: 1

http://stackoverflow.com/comment/89372386
has text: You can simply do `O[x.astype('int')+50, y.astype('int')+50]` to get the values of the pixels of near locations and then iterate over different values of `R`
comment on: http://stackoverflow.com/a/51194886
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/89478599
type: Comment
has text: Hi Daniel & Martin class networkFilterUserbased(django_filters.FilterSet): def __init__(self, *args, **kwargs): super().__init__(*args,**kwargs) request = kwargs['request'] username = request.user.id my_choices = NetworkRelatedInformation.objects.values_list('account__accountName') \ .filter(account__accountusermapping__userId=username).distinct() self.filters['account'].extra.update({'choices': my_choices}) class Meta: model = Network fields = ['month', 'year', 'account'] Updated code, but error
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51204787

http://stackoverflow.com/a/51313514
answers question: http://stackoverflow.com/q/51313429
score: 0
has body: Assuming this is a text file you're writing to you can use something like the following format but change it according to how you have your line and value set up. with open('output.txt','w') as f: line = 'something' value = 2 f.write(line + str(value)) This should give you the output 'something2' To remove duplicates for line in lines: read = [] if line not in read: read.append(line) do something with it else: add current count to previous values Not too sure how you have your script set up but this is just an idea.
has comment: http://stackoverflow.com/comment/89604456
type: Answer
has comment: http://stackoverflow.com/comment/89603903
has comment: http://stackoverflow.com/comment/89646486

http://stackoverflow.com/comment/89353792
has text: @VivekKumar it appears that every new job created goes straight to sleep. When setting `n_jobs=-1` IDLE pops up with about 39 warnings that my program is still running and asks if I want to kill it. `verbose=True` is not really giving me any output. When I had only one job, it gave me the following: `[LibSVM]` and nothing else. Running multiple jobs have not given me any output as of yet. I am currently trying with a 100.000 sample dataset without any luck.
comment on: http://stackoverflow.com/q/51185274
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/89635688
has text: To be honest I just wasn't sure about how to proceed best. I'm used to system-wide installations (either using a package manager like apt, or by using something like cvmfs on a cluster where I'm working remote in a terminal). At my current work, a lot of people are using Anaconda, but are also usually working in Windows. I wanted to be able to use "my way" of just firing up an ipython notebook or an ipython console to start coding, but wasn't sure if it's the same in conda and whether I can still use conda in case it's a requirement in a project.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51319551
type: Comment

http://stackoverflow.com/q/51207503
type: Question
tagged with: flask
accepted answer: http://stackoverflow.com/a/51219880
score: 0
has title: Remember user sign up
answer count: 1
has body: I am having trouble with the signup/login process. I am using Flask as Backend Here's the setup: When a user visits the site they see a signup page, all this data is stored in a sqlite3 db. After they press create account they get redirected to the dashboard. The next time they visit the site they are supposed to go to the Login page instead of the signup page. But how do I manage that? I am using Login_Manager This is my signup/login code part def index(): return redirect('signup', code=302) @app.route('/login', methods=['GET', 'POST']) def login(): form = LoginForm() if form.validate_on_submit(): user = User.query.filter_by(username=form.username.data).first() if user: if check_password_hash(user.password, form.password.data): login_user(user, remember=True) return redirect(url_for('dashboard')) else: return 'invalid user' #return form.username.data + ' ' + form.password.data return render_template('login.html', form=form) @app.route('/signup', methods=['GET', 'POST']) def signup(): form = RegisterForm() hashed_password = generate_password_hash(form.password.data, method='sha256') if form.validate_on_submit(): new_user = User(username=form.username.data, password=hashed_password) db.session.add(new_user) db.session.commit() return render_template('dashboard.html') # return form.username.data + ' ' + form.password.data return render_template('signup.html', form=form)
has answer: http://stackoverflow.com/a/51219880
has comment: http://stackoverflow.com/comment/89395851
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/a/51199017
answers question: http://stackoverflow.com/q/51198845
has body: Here's one way using collections.defaultdict. Like @HoriaComan's method, this solution doesn't require iterating your entire list. myArray = [1,1,1,1,1,1,1,1,2] from collections import defaultdict def count_limit(L, k=2): d = defaultdict(int) for item in L: if d[item] == k: return True else: d[item] += 1 return False res = count_limit(myArray) # False Performance benchmarking To demonstrate the impact, we can compare with Counter on a larger iterable: myArray = [1,1,1,1,1,1,1,1,2]*10000 from collections import defaultdict, Counter def count_limit(L, k=2): d = defaultdict(int) for item in L: if d[item] == k: return True else: d[item] += 1 return False def count_limit_counter(myArray): return any(count &gt; 2 for count in Counter(myArray).values()) %timeit count_limit(myArray) # 1.52 µs per loop %timeit count_limit_counter(myArray) # 6.64 ms per loop
downvote count: 0
type: Answer
score: 2
upvote count: 2

http://stackoverflow.com/a/51217372
has body: When you iterate over a dictionary with a for, you're not iterating over the items, but over the keys ('a', 'b'). These are just strings that mean nothing. That's why you have to do it as on test 2. You could also iterate over the items with test.items().
downvote count: 0
type: Answer
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/51217344

http://stackoverflow.com/comment/89561402
type: Comment
comment on: http://stackoverflow.com/q/51275627
type: QuestionComment
has text: I wonder if [Blender](https://www.blender.org/)'s Python interface might be helpful here, e.g. https://blender.stackexchange.com/questions/5898/how-can-i-create-a-cylinder-linking-two-points-with-python
score: 0

http://stackoverflow.com/comment/89383179
has text: Have you printed out the data frame? I would expect that first data line to have 7 entries, denoted by those commas, rather than a single string.
comment on: http://stackoverflow.com/q/51200743
score: 0
type: Comment
type: QuestionComment

php-carbon
tag name: php-carbon
tags question: http://stackoverflow.com/q/51314217
type: Tag

http://stackoverflow.com/comment/89434299
comment on: http://stackoverflow.com/q/51218931
score: 0
type: Comment
type: QuestionComment
has text: I just added the output for model.summary(). I am not sure what caused the increase in Conv2D parameters from the VGG16 model to the last 3 Conv2D layers (the ones that I added with Keras). The summary looks the same except for the number of parameters.

apache
tag name: apache
tags question: http://stackoverflow.com/q/51247772
tags question: http://stackoverflow.com/q/51257322
tags question: http://stackoverflow.com/q/51205411
tags question: http://stackoverflow.com/q/51194310
tags question: http://stackoverflow.com/q/51288692
tags question: http://stackoverflow.com/q/51218025
tags question: http://stackoverflow.com/q/51285853
tags question: http://stackoverflow.com/q/51186217
tags question: http://stackoverflow.com/q/51196117
type: Tag
tags question: http://stackoverflow.com/q/51202430
tags question: http://stackoverflow.com/q/51195932

http://stackoverflow.com/a/51204689
type: Answer
accepted answer of: http://stackoverflow.com/q/51204370
score: 0
has body: so, range(1, k) (in Python 2) gives you a list [1, 2, 3, ..., k-1]. When you append the list o by something from the input, the element is available on index 0 &gt;&gt; o = [] &gt;&gt; o.append(42) &gt;&gt; o[0] 42 But, in your loop you try to get index 1, which is not available. Remember, that the first element in a list is available through index 0, where the second has index 1 etc..
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51204370

http://stackoverflow.com/a/51196565
has comment: http://stackoverflow.com/comment/89375724
has comment: http://stackoverflow.com/comment/89377548
has comment: http://stackoverflow.com/comment/89375733
has comment: http://stackoverflow.com/comment/89376384
has comment: http://stackoverflow.com/comment/89377209
has comment: http://stackoverflow.com/comment/89376316
has comment: http://stackoverflow.com/comment/89374808
has body: Update : Your columns increment is category df=pd.DataFrame({'A':[1,1,2,2],'B':[1,1,2,3],'C':[1,1,1,1]}) df.B=df.B.astype('category') df.groupby(['A','B']).last() Out[590]: C A B 1 1 1.0 2 NaN 3 NaN 2 1 NaN 2 1.0 3 1.0 When you using tail it will not make up the miss level since , tail is more like dataframe base , not single columns df.groupby(['A','B']).tail(1) Out[593]: A B C 1 1 1 1 2 2 2 1 3 2 3 1 After hange it using astype df.B=df.B.astype('int') df.groupby(['A','B']).last() Out[591]: C A B 1 1 1 2 2 1 3 1
score: 0
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51196382
downvote count: 1
answers question: http://stackoverflow.com/q/51196382
has comment: http://stackoverflow.com/comment/89375621
has comment: http://stackoverflow.com/comment/89374800
type: Answer

http://stackoverflow.com/comment/89559965
has text: @helen Sorry; it's `socket.SO_REUSEADDR`, not `socket, SO.REUSEADDR`. (That's what I get for editing on a tablet…) As for the infinite loop… If `if not data: break` is never happening, that implies that the `data = conn.recv(buf)` keeps returning non-empty buffers. Which should only happen if the client keeps sending forever. But the client keeps doing `data = f.read(buf)` until it's empty, and you haven't opened an infinite-size pseudofile like `/dev/zero`, so that doesn't make sense.
type: Comment
comment on: http://stackoverflow.com/a/51275377
score: 0
type: AnswerComment

http://stackoverflow.com/comment/109277468
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51234889
has text: how to check the version of HTMLTestRunner

http://stackoverflow.com/comment/89555983
comment on: http://stackoverflow.com/q/51289003
score: 0
type: Comment
type: QuestionComment
has text: Does this work for Python2 and Python3?

http://stackoverflow.com/comment/89604181
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51313754
score: 4
has text: Post the code of how you read the `csv` what data structures you have. Once you have `Andy` and `Ball` , just do `a + ' has a ' + b`

http://stackoverflow.com/comment/89530161
type: QuestionComment
comment on: http://stackoverflow.com/q/51275976
has text: https://github.com/pandas-dev/pandas/blob/master/pandas/_libs/tslibs/parsing.pyxGood find @kitman0804. J C I'm guessing that you can't get the source for these functions because they're cython, but you can find it [on GitHub](https://github.com/pandas-dev/pandas/blob/5d0daa0522730a6f999ceaf328f63f03dd62d0b4/pandas/_libs/tslibs/parsing.pyx#L561)
score: 0
type: Comment

axios
tags question: http://stackoverflow.com/q/51204241
tag name: axios
type: Tag

restful-architecture
type: Tag
tags question: http://stackoverflow.com/q/51314091
tag name: restful-architecture

http://stackoverflow.com/comment/89561852
has text: So this is super close to what I need -- however, it doesn't write anything to my json file, and it only outputs the final indicator to my ipython console: Out[47]: '{"indicator": {"detection": [{"selection": {"EventID": 1, "Image": ["*\\\\schtasks.exe", "*\\\\nslookup.exe", "*\\\\certutil.exe", "*\\\\bitsadmin.exe", "*\\\\mshta.exe"], "ParentImage": ["*\\\\mshta.exe", "*\\\\powershell.exe", "*\\\\cmd.exe", "*\\\\rundll32.exe", "*\\\\cscript.exe", "*\\\\wscript.exe", "*\\\\wmiprvse.exe"]}, "condition": "selection"}], "fields": "CommandLine", "ParentCommandLine", "level": ["medium"], ...
type: AnswerComment
comment on: http://stackoverflow.com/a/51292033
score: 0
type: Comment

http://stackoverflow.com/q/51251584
has answer: http://stackoverflow.com/a/51859229
type: Question
has answer: http://stackoverflow.com/a/51251644
has body: I want to work with sql server in orange through anaconda. When installing pymssql I am getting the attached error. After hours of googling I could not find a solution for anaconda. Please help! Thank you Michael _mssql.c(266): fatal error C1083: Cannot open include file: 'sqlfront.h': No such file or directory error: command 'C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.14.26428\bin\HostX86\x64\cl.exe' failed with exit status 2
tagged with: anaconda
tagged with: pymssql
tagged with: sql-server
answer count: 2
downvote count: 0
favorite count: 0
has title: pip install pymssql fails in anaconda windows
upvote count: 2
type: UnansweredQuestion
tagged with: python
score: 2

http://stackoverflow.com/comment/89582552
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/51302668
has text: You can print your table as preformatted text by adding four spaces to the start of each line; check the formatting help for details. I'd edit it for you, but it looks like your first table is also missing a column.

http://stackoverflow.com/q/51214626
type: Question
answer count: 2
tagged with: python
has answer: http://stackoverflow.com/a/51214889
has answer: http://stackoverflow.com/a/55647279
score: 4
tagged with: tkinter
has title: Why does asksaveasfilename not return the file type?
has comment: http://stackoverflow.com/comment/89410722
has body: Tkinter is a great package and filedialog has some very helpful features. Both askopenfilename and asksaveasfilename have the 'filetypes' attribute, but it works differently for each one. With askopenfilename it provides options in the GUI and returns the filetype, BUT with asksaveasfilename it only provides options in the GUI and does not return the filetype. Example code is shown below: import tkinter as tk from tkinter import filedialog old_file_name = filedialog.askopenfilename(title = "Choose file",filetypes=\ (('All files','*.*'),\ ('tagData','*.tagData'),\ ('FDAX files','*.fdax'),\ ('CSV files','*.csv'))) new_file_name = filedialog.asksaveasfilename(initialdir = "/",filetypes=\ (('tagData','*.tagData'),\ ('FDAX files','*.fdax'),\ ('CSV files','*.csv'),\ ('XLS files','*.xls'))) print(old_file_name) print(new_file_name) Output: C:/Users/christian.abbott/Desktop/FDAX_Error/example.csv C:/Users/christian.abbott/Desktop/example I have looked for good filedialog documentation but have not been able to find it. Why does the package behave this way? Is there a better option to extract the full path of a user-prompted file path?
downvote count: 1
upvote count: 5
type: UnansweredQuestion
tagged with: filedialog
tagged with: openfiledialog
has comment: http://stackoverflow.com/comment/89410415
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/comment/89432879
type: Comment
has text: `CTRL+Z` stops the process, but you should add that it puts it into background as a stopped job, it does not kill it.
comment on: http://stackoverflow.com/a/51226100
score: 0
type: AnswerComment

http://stackoverflow.com/comment/89549767
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51285762
type: AnswerComment
has text: I guess you will have to override it... because its a native widget, never tried it before, if you get any good response let me know

http://stackoverflow.com/q/51224245
upvote count: 1
has comment: http://stackoverflow.com/comment/89428830
score: -1
type: Question
has answer: http://stackoverflow.com/a/51224278
answer count: 1
has comment: http://stackoverflow.com/comment/89428819
linked to: http://stackoverflow.com/q/16940293
has title: Difference in printing tuples and list in python
favorite count: 0
tagged with: tuples
tagged with: python
has body: When I'm changing output type between list and tuple, one is showing output whereas other is just showing location of result. Why does this happen? &gt;&gt;&gt; symbol = '123456789' &gt;&gt;&gt; (s for s in symbol) &lt;generator object &lt;genexpr&gt; at 0x7fc0e9e2fbf8&gt; &gt;&gt;&gt; [s for s in symbol] ['1', '2', '3', '4', '5', '6', '7', '8', '9']
tagged with: list
tagged with: generator-expression
type: UnansweredQuestion
downvote count: 2

http://stackoverflow.com/q/51169691
score: 0
has body: For the df below, I'm trying to alter the legend of the scatter plot to display Column C values. It works when the values are floats but when I try to insert strings it returns a ValueError. ValueError: could not convert string to float: 'Y' import pandas as pd import matplotlib.pyplot as plt d = ({ 'A' : [1,2,3,4,5,6,7,8,9,10], 'B' : [1,1,1,2,2,2,7,7,7,7], #'C' : ['X','Y','Z','X','Y','Z','A','X','Y','Z'], #Doesn't work 'C' : [2,4,6,8,2,4,6,8,10,2], # Works }) df = pd.DataFrame(data=d) fig,ax = plt.subplots() x = df['A'] y = df['B'] classes = df['C'] unique = list(set(classes)) colors = [plt.cm.jet(float(i)/max(unique)) for i in unique] for i, u in enumerate(unique): xi = [x[j] for j in range(len(x)) if classes[j] == u] yi = [y[j] for j in range(len(x)) if classes[j] == u] plt.scatter(xi, yi, c=colors[i], label=str(u)) plt.legend() Thus far, when trying to use the strings I've tried to change float to str (as below): colors = [plt.cm.jet(float(i)/max(unique)) for i in unique] colors = [plt.cm.jet(str(i)/max(unique)) for i in unique] It returns TypeError: unsupported operand type(s) for /: 'str' and 'str' Intended Output (But I would like to have strings in the legend, so 'X','Y','Z' instead of 2,4,6):
tagged with: legend
duplicate of: http://stackoverflow.com/q/42056713
tagged with: python
has comment: http://stackoverflow.com/comment/89322487
has comment: http://stackoverflow.com/comment/89323722
answer count: 0
has comment: http://stackoverflow.com/comment/89323275
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89327695
linked to: http://stackoverflow.com/q/42056713
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/89324103
has comment: http://stackoverflow.com/comment/89327039
type: Question
has comment: http://stackoverflow.com/comment/89324290
has title: Scatterplot legend from color dict python
tagged with: scatter

http://stackoverflow.com/comment/89377479
comment on: http://stackoverflow.com/q/51197793
type: Comment
type: QuestionComment
has text: @Nagashayan yes, anaconda is shown in the directory when using echo $PATH
score: 0

http://stackoverflow.com/a/51219457
score: 1
answers question: http://stackoverflow.com/q/51213743
has body: Hard to say if this is what you're looking for but sounds like you're looking for a way to search a list of dictionaries. &gt;&gt;&gt; rows = [{'symbol': 'APPL', 'shares':1000},{'symbol': 'GE', 'shares': 2000},{'symbol': 'TWTR', 'shares': 5000}] &gt;&gt;&gt; def lookup(rows, stock): ... results = [row for row in rows if row["symbol"] == stock] ... return results ... &gt;&gt;&gt; lookup(rows, 'APPL') [{'symbol': 'APPL', 'shares': 1000}]
upvote count: 1
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/51213743
downvote count: 0

http://stackoverflow.com/comment/89393916
score: 0
has text: So a M=np.float(M) did the trick
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51187122

http://stackoverflow.com/q/51222981
tagged with: pandas
has comment: http://stackoverflow.com/comment/89426358
has comment: http://stackoverflow.com/comment/89426520
has title: Count occurrence of elements in column of lists (with a twist)
tagged with: python
has body: I've got a column of lists called "author_background" which I would like to analyze. The actual column consists of 8.000 rows. My aim is to get an overview on how many different elements there are in total (in all lists of the column) and count in how many lists each element occurs in. How my column looks like: df.author_background 0 [Professor for Business Administration, Harvard Business School] 1 [Professor for Industrial Engineering, University of Oakland] 2 [Harvard Business School] 3 [CEO, SpaceX] desired output 0 Harvard Business School 2 1 Professor for Business Administration 1 2 Professor for Industrial Engineering 1 3 CEO 1 4 University of Oakland 1 5 SpaceX 1 I would like to know how often "Professor of Business Administration", "Professor for Industrial Engineering", "Harvard Business School", etc. occurs in the column. There are way more titles I don't know about. Basically, I would like to use pd.value_counts for the column. However, its not possible because its a list. Is there another way to count the occurrence of each element? If thats more helpful: I also got a list which contains all elements of the lists (not nested).
tagged with: count
type: AnsweredQuestion
tagged with: list
possible better answer: http://stackoverflow.com/a/51223097
has comment: http://stackoverflow.com/comment/89426374
has answer: http://stackoverflow.com/a/51223097
type: Question
answer count: 2
accepted answer: http://stackoverflow.com/a/51223104
linked to: http://stackoverflow.com/q/952914
has comment: http://stackoverflow.com/comment/89426420
score: 0
has answer: http://stackoverflow.com/a/51223104

http://stackoverflow.com/q/51218151
type: Question
tagged with: discrete-mathematics
tagged with: python-itertools
has comment: http://stackoverflow.com/comment/89417995
has comment: http://stackoverflow.com/comment/89418159
has answer: http://stackoverflow.com/a/51218926
has answer: http://stackoverflow.com/a/51218673
possible better answer: http://stackoverflow.com/a/51218601
has answer: http://stackoverflow.com/a/51218601
has title: All possible subdivisions of a list
tagged with: permutation
score: 7
favorite count: 0
has comment: http://stackoverflow.com/comment/89418537
upvote count: 8
answer count: 3
accepted answer: http://stackoverflow.com/a/51218673
tagged with: python
has comment: http://stackoverflow.com/comment/89417556
has comment: http://stackoverflow.com/comment/89417386
has comment: http://stackoverflow.com/comment/89418220
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/33000320
has comment: http://stackoverflow.com/comment/89417685
has comment: http://stackoverflow.com/comment/89417487
has body: I've just written a small recursive programme to generate all the possible subdivisions of a list: def subdivisions(ls): yield [ls] if len(ls) &gt; 1: for i in range(1, len(ls)): for lhs in subdivisions(ls[:i]): yield lhs + [ls[i:]] &gt;&gt;&gt; for x in subdivisions('abcd'): print x ... ['abcd'] ['a', 'bcd'] ['ab', 'cd'] ['a', 'b', 'cd'] ['abc', 'd'] ['a', 'bc', 'd'] ['ab', 'c', 'd'] ['a', 'b', 'c', 'd'] I've brute forced this and it's taken me a long time to figure out. I'm wondering what this is called, as I'm sure there is a name for it. In general I'm wondering how to learn this stuff from a mathematical point of view and whether there are good well known programming libraries that cover useful algorithms like this (I know of https://docs.python.org/3/library/itertools.html ) [Edit] the question that this is marked as duplicate of - get all possible partitions of a set - gets a different answer. It is looking for { {{1,2,3},{}} , {{1},{2,3}} , {{1,2},{3}} , {{1,3},{2}}, {{1},{2},{3}}} while a correct answer for me (in it's terminology) would be { {{1,2,3}} , {{1},{2,3}} , {{1,2},{3}} , {{1},{2},{3}}} Also, the point of asking the question was to figure out what the terminology of this is; I'm calling it 'subdivisions'; that answer is calling it 'partitions'. I'm looking for a good resource which enumerates all of these patterns, so that people don't go reinventing the wheel.
downvote count: 1

qweb
tags question: http://stackoverflow.com/q/51224448
type: Tag
tag name: qweb

http://stackoverflow.com/comment/89618031
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51320926
type: Comment
has text: In the general case, no, not without running the code. Import statements aren't the only way to import things.

http://stackoverflow.com/q/51310962
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/89598719
score: 0
has body: I am trying to make a python script that loads a few excel documents and tries to collect data. Right now i am trying to return all the data from one column, however it seems that when i use the for loop in grab_index_id it only returns the first value on the column, index id. import openpyxl from openpyxl import load_workbook doc1 = openpyxl.load_workbook('sp_schema.xlsx') master_sheet = doc1.get_sheet_by_name('Master List') doc2 = openpyxl.load_workbook('slc.xlsx') slc_sheet = doc2.get_sheet_by_name('Sheet1') def grab_index_id(): i = 0 x = 1 while i &lt; 10: return (master_sheet.cell(row = x, column = 1).value) x = x + 1 i = i + 1 print(grab_index_id()) INDEX ID Process finished with exit code 0
answer count: 1
accepted answer: http://stackoverflow.com/a/51310997
linked to: http://stackoverflow.com/q/50402694
favorite count: 0
duplicate of: http://stackoverflow.com/q/50402694
tagged with: python
has comment: http://stackoverflow.com/comment/89598939
has comment: http://stackoverflow.com/comment/89598574
type: AnsweredQuestion
upvote count: 1
has title: Only one value returns from while loop function
has answer: http://stackoverflow.com/a/51310997

http://stackoverflow.com/q/51297475
has body: I have a column like this, valueCount 0.0 nan 2.0 1.0 1.0 1.0 nan nan nan 4.0 I want to fillna based on next value(add) or previous value(subtract) available. so the result should be, valueCount 0.0 **1.0** 2.0 1.0 1.0 1.0 **1.0** **2.0** **3.0** 4.0 i know it is very condititonal based, if my previous value is 0 i can add +1 to the nan row, else i should start adding from 0,1,2 and so on. i can do this algorithm in simple list of python, but in pandas is there any simple way ?
tagged with: pandas
upvote count: 1
has answer: http://stackoverflow.com/a/51299358
favorite count: 0
possible better answer: http://stackoverflow.com/a/51299358
has title: pandas fillna based on previous row value
has comment: http://stackoverflow.com/comment/89574195
tagged with: python
accepted answer: http://stackoverflow.com/a/51297736
type: AnsweredQuestion
downvote count: 0
score: 1
type: Question
has answer: http://stackoverflow.com/a/51297736
answer count: 2

http://stackoverflow.com/q/51218025
answer count: 0
has comment: http://stackoverflow.com/comment/89418376
tagged with: django
has comment: http://stackoverflow.com/comment/89425584
type: Question
has body: Hellos guys I’m trying to deploy django in a Windows machine, I already change python versions and wsgi_mod many times and it seem to be correct the problem is when I try to add the application in settinf.py, if I only create the Project and I run 127.0.0.1 it works fine it show me the django welcome message but once I juts create the app and I add in the setting.py it show me 500 Internal Server Error error, could you guys help me with this issue? This is my apache error log. [Fri Jul 06 16:26:07.620085 2018] [mpm_winnt:notice] [pid 6032:tid 564] AH00455: Apache/2.4.33 (Win64) mod_wsgi/4.6.4 Python/3.5 configured -- resuming normal operations [Fri Jul 06 16:26:07.620085 2018] [mpm_winnt:notice] [pid 6032:tid 564] AH00456: Apache Lounge VC14 Server built: Mar 29 2018 12:12:07 [Fri Jul 06 16:26:07.620085 2018] [core:notice] [pid 6032:tid 564] AH00094: Command line: 'C:\\Apache24\\bin\\httpd.exe -d C:/Apache24' [Fri Jul 06 16:26:07.635705 2018] [mpm_winnt:notice] [pid 6032:tid 564] AH00418: Parent: Created child process 4604 [Fri Jul 06 16:26:08.541998 2018] [mpm_winnt:notice] [pid 4604:tid 564] AH00354: Child: Starting 64 worker threads. [Fri Jul 06 16:26:18.172721 2018] [wsgi:error] [pid 4604:tid 1096] [client 127.0.0.1:50432] mod_wsgi (pid=4604): Failed to exec Python script file 'C:/uno/dos/dos/wsgi.py'. [Fri Jul 06 16:26:18.172721 2018] [wsgi:error] [pid 4604:tid 1096] [client 127.0.0.1:50432] mod_wsgi (pid=4604): Exception occurred processing WSGI script 'C:/uno/dos/dos/wsgi.py'. [Fri Jul 06 16:26:18.177727 2018] [wsgi:error] [pid 4604:tid 1096] [client 127.0.0.1:50432] Traceback (most recent call last):\r [Fri Jul 06 16:26:18.177727 2018] [wsgi:error] [pid 4604:tid 1096] [client 127.0.0.1:50432] File "C:/uno/dos/dos/wsgi.py", line 16, in &lt;module&gt;\r [Fri Jul 06 16:26:18.177727 2018] [wsgi:error] [pid 4604:tid 1096] [client 127.0.0.1:50432] application = get_wsgi_application()\r [Fri Jul 06 16:26:18.177727 2018] [wsgi:error] [pid 4604:tid 1096] [client 127.…
score: 0
has comment: http://stackoverflow.com/comment/89417210
tagged with: apache
has comment: http://stackoverflow.com/comment/89417644
type: UnansweredQuestion
tagged with: windows
tagged with: python
has title: Trying to deploy Django in windows machine

http://stackoverflow.com/q/51191603
has body: This is my code below : from tkinter import * login = Tk() username_1 = Entry() username_1.pack(side=TOP) input_username = login.username_1.get("1.0", END) username = input_username loginInfo = {"user1": "blue", "user2": "yellow", "user3": "green"} if username in loginInfo: print('Username correct!') login.mainloop() This is my error: 'AttributeError: '_tkinter.tkapp' object has no attribute 'username_1'':
has answer: http://stackoverflow.com/a/51191769
possible better answer: http://stackoverflow.com/a/51192566
tagged with: tkinter-entry
score: -1
favorite count: 0
tagged with: tkinter
tagged with: python
accepted answer: http://stackoverflow.com/a/51191769
type: AnsweredQuestion
has title: I have a tkinter entry box in python but I can't get the input from it into my code?
downvote count: 1
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/89365576
upvote count: 0
has answer: http://stackoverflow.com/a/51192566

http://stackoverflow.com/comment/89601606
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51312300
has text: Oh boy, I didn't try this way, let me try it than I'll let you know the result. thank you so much @J0hn

http://stackoverflow.com/a/64135777
answers question: http://stackoverflow.com/q/51181129
type: Answer
upvote count: 3
score: 3
has body: You can use the nan_policy='omit' option in stats.zscore. See here. gpoa_z=stats.zscore(gpoa, nan_policy='omit')
downvote count: 0

http://stackoverflow.com/comment/89459241
type: QuestionComment
comment on: http://stackoverflow.com/q/51240096
score: 0
has text: i just called sparse=scipy.csr_matrix(dataframe.values)
type: Comment

http://stackoverflow.com/a/51177558
type: Answer
score: 1
answers question: http://stackoverflow.com/q/51177493
upvote count: 2
has comment: http://stackoverflow.com/comment/89338065
has body: Have a look at Python Reflections which can provide information about type, class, attributes and methods of an object. You are looking for isinstance(inspect, class_object) Multiple checks will further ascertain inheritance
has comment: http://stackoverflow.com/comment/89338315
has comment: http://stackoverflow.com/comment/89338259
downvote count: 1
has comment: http://stackoverflow.com/comment/89338014

http://stackoverflow.com/q/51314024
has title: loading a set of text files whose names are stored in an array
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/51315216
has comment: http://stackoverflow.com/comment/89604888
answer count: 1
has comment: http://stackoverflow.com/comment/89604982
has comment: http://stackoverflow.com/comment/89617032
score: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/89605102
has comment: http://stackoverflow.com/comment/89606978
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89604733
has body: So I have a set of text files that are some columns of numbers and whos names are stored in an excel file. I need to load in every file in the directory who's name matches one in the excel file. I also want to inform you all that I am a python beginner, and I'm honestly not very computer savvy (but I'm trying). I start by loading the excel file into a dataframe and then converting it to an array. Then I was trying to loop through the array and load in any files that match it, with the name of the variable holding the data being the name of the text file (without the .txt) df=pd.read_excel('names.xlsx', sheet_name="Sheet 1") array=df.values for i in array: str(array[i][0])=np.loadtxt(str(array[i][0])+'.txt') when I try to run this I get: str(array[i][0]) = np.loadtxt(str(array[i][0])+'.txt') ^ SyntaxError: can't assign to function call So my questions are, how can I assign that as the variable name, and because it stops before the code gets there, is it valid to load the files in the way I have?

http://stackoverflow.com/a/51313779
answers question: http://stackoverflow.com/q/51313710
score: 1
has comment: http://stackoverflow.com/comment/89604757
type: AcceptedAnswer
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/89604709
has body: My take on the problem: XDict = { "Jersey" : 0, "Boston" : -1, "York" : 0, "Vegas" : 1, "Diego" : 0 } YDict = { "Jersey" : 0, "Boston" : 0, "York" : -1, "Vegas" : 0, "Diego" : 1 } hereX = 0 hereY = 0 for ((n1, x), (n2, y)) in zip(XDict.items(), YDict.items()): if (x==hereX) and (y==hereY): print(n1) break Prints: Jersey However, it's unclear why you store the city names in both dictionaries. Better solution would be storing the dataset like this: d = {(0, 0): "Jersey", (-1, 0): "Boston", (0, -1): "York", (1, 0): "Vegas", (0, 1): "Diego"} That way you can index it by d[(hereX, hereY)].
accepted answer of: http://stackoverflow.com/q/51313710
upvote count: 1

http://stackoverflow.com/a/51315210
has body: Just do out = StringIO() in Python 3, StringIO is already the class you want to instantiate, as opposed to Python 2 where it was the name of the module but also the class.
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51315148

http://stackoverflow.com/q/51322672
has title: SortedSet ValueError not in list
has comment: http://stackoverflow.com/comment/89620831
has comment: http://stackoverflow.com/comment/89621095
accepted answer: http://stackoverflow.com/a/51327158
type: Question
has comment: http://stackoverflow.com/comment/89620782
answer count: 1
has comment: http://stackoverflow.com/comment/89620608
tagged with: python-2.7
score: 0
has comment: http://stackoverflow.com/comment/89621178
has answer: http://stackoverflow.com/a/51327158
has comment: http://stackoverflow.com/comment/89620874
has body: I am using a SortedSet from the sortedcontainers library. The set contains Match objects which define a start attribute which is used to sort: class Match: def __lt__(self, other): return self.start &lt; other.start Matches are constantly added (SortedSet.add) and discarded (SortedSet.discard) from the set. Matches may have the same start. Matches may see their start changed while existing in the set. Everything seems to work without any issues until I get the following error when trying to discard a match sortedset.discard(match): ValueError: &lt;Match: X vs Y&gt; not in list The match is present in the set, as match in sortedset returns True. Not that it should matter since discard removes quietly. I have absolutely no idea why this is happening and I have been trying to figure out a solution for a couple of days, no success yet. I would provide more information if I had any clue of what may be wrong, but I am just clueless. Please ask any information you need and I will deliver.
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89621475

http://stackoverflow.com/comment/89678324
comment on: http://stackoverflow.com/q/51317007
has text: The execute statement is within a try block, if there's an exception it's it's supposed to log to console "unable to import" then "traceback.print_exc()" but when it's run it doesn't log anything to the console. The last thing logged to the console is writing out waterdata otu abundance to csv tempfile: bpaotu-ijpgihw6 and then it finishes after a few seconds.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/115192722
has text: See https://github.com/ilevkivskyi/typing_inspect/issues/65
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/56151421
type: Comment

http://stackoverflow.com/a/51306156
accepted answer of: http://stackoverflow.com/q/51266814
upvote count: 1
type: AcceptedAnswer
type: Answer
has body: Unfortunately, it's not possible. Please vote for the corresponding feature request in PyCharms' bug tracker: PY-15021.
downvote count: 0
answers question: http://stackoverflow.com/q/51266814
score: 1

http://stackoverflow.com/q/51236970
duplicate of: http://stackoverflow.com/q/37077432
tagged with: python
has comment: http://stackoverflow.com/comment/89569760
answer count: 0
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/37077432
type: Question
has comment: http://stackoverflow.com/comment/89572890
tagged with: aws-glue
tagged with: pyspark
tagged with: http://stackoverflow.com/tag/json
has body: I've been working with AWS Glue and pysaprk dataframes for the past few days. Unfortunately I need to calculate the size of my dataframes but I have been getting very inconsistent results. Python sys.getszieof() on a dataframe that loaded a JSON file of size 1.7mb returns 56 bytes, and I am not sure how to exactly deal with this. Is there any suggestions on what to do?
tagged with: dataframe
score: 0
has title: Calculating the actual size of a pyspark Dataframe

http://stackoverflow.com/comment/89566161
type: AnswerComment
has text: The problem is that the `run_cli()` method not able to run the testsuite created by `TestSuite object of robot.api`
type: Comment
comment on: http://stackoverflow.com/a/51277822
score: 0

http://stackoverflow.com/q/51317810
has body: My code is this: import matplotlib.pyplot as plt from sklearn import datasets, svm digits = datasets.load_digits() clf = svm.SVC(gamma=0.001, C=100) print(len(digits.data)) X,y = digits.data[:-1] , digits.target[:-1] clf.fit(X,y) print('Prediction:',clf.predict(digits.data[-1])) plt.imshow(digits.images[-1], cmap=plt.cm.gray_r, interpolation="nearest") plt.show() And I am getting this error: Traceback (most recent call last): File "E:\python programs\sklearn\sklearn 2.py", line 14, in &lt;module&gt; print('Prediction:',clf.predict(digits.data[-1])) File "C:\Users\Rohan\AppData\Local\Programs\Python\Python36\lib\site-packages\sklearn\svm\base.py", line 548, in predict y = super(BaseSVC, self).predict(X) File "C:\Users\Rohan\AppData\Local\Programs\Python\Python36\lib\site-packages\sklearn\svm\base.py", line 308, in predict X = self._validate_for_predict(X) File "C:\Users\Rohan\AppData\Local\Programs\Python\Python36\lib\site-packages\sklearn\svm\base.py", line 439, in _validate_for_predict X = check_array(X, accept_sparse='csr', dtype=np.float64, order="C") File "C:\Users\Rohan\AppData\Local\Programs\Python\Python36\lib\site-packages\sklearn\utils\validation.py", line 441, in check_array "if it contains a single sample.".format(array)) ValueError: Expected 2D array, got 1D array instead: array=[ 0. 0. 10. 14. 8. 1. 0. 0. 0. 2. 16. 14. m6. 1. 0. 0. 0. 0. 15. 15. 8. 15. 0. 0. 0. 0. 5. 16. 16. 10. 0. 0. 0. 0. 12. 15. 15. 12. 0. 0. 0. 4. 16. 6. 4. 16. 6. 0. 0. 8. 16. 10. 8. 16. 8. 0. 0. 1. 8. 12. 14. 12. 1. 0.]. Reshape your data either using array.reshape(-1, 1) if your data has a single feature or array.reshape(1, -1) if it contains a single sample. "What should I do?"
tagged with: machine-learning
type: Question
score: 0
upvote count: 1
has answer: http://stackoverflow.com/a/51317981
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/89611863
tagged with: scikit-learn
favorite count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89611719
has title: ValueError: Expected 2D array, got 1D array instead during svm recognition

http://stackoverflow.com/q/51267483
linked to: http://stackoverflow.com/q/13636848
has body: I am new to Python and I am trying to merge two datasets for my research together: df1 has the column names: companyname, ticker, and Dscode, df2 has companyname, ticker, grouptcode, and Dscode. I want to merge the grouptcode from df1 to df2, however, the companyname is slightly different, but very similar between the two dataframes. For each ticker, there is an associated Dscode. However, multiple companies have the same ticker, and therefore the same Dscode. Problem I am only interested in merging the grouptcode for the associated ticker and Dscode that matches the companyname (which at times is slightly different - this part is what I cannot get past). The code I have been using is below. Code import pandas as pd import os # set working directory path = "/Users/name/Desktop/Python" os.chdir(path) os.getcwd() # Prints the working directory # read in excel file file = "/Users/name/Desktop/Python/Excel/DSROE.xlsx" x1 = pd.ExcelFile(file) print(x1.sheet_names) df1 = x1.parse('Sheet1') df1.head() df1.tail() file2 = "/Users/name/Desktop/Python/Excel/tcode2.xlsx" x2 = pd.ExcelFile(file2) print(x2.sheet_names) df2 = x2.parse('Sheet1') df2['companyname'] = df2['companyname'].str.upper() ## make column uppercase df2.head() df2.tail() df2 = df2.dropna() x3 = pd.merge(df1, df2,how = 'outer') # merge Data df1 Dscode ticker companyname 65286 8933TC 3pl 3P LEARNING LIMITED 79291 9401FP a2m A2 MILK COMPANY LIMITED 1925 14424Q aac AUSTRALIAN AGRICULTURAL COMPANY LIMITED 39902 675493 aad ARDENT LEISURE GROUP 1400 133915 aba AUSWIDE BANK LIMITED 74565 922472 abc ADELAIDE BRIGHTON LIMITED 7350 26502C abp ABACUS PROPERTY GROUP 39202 675142 ada ADACEL TECHNOLOGIES LIMITED 80866 9661AD adh ADAIRS 80341 9522QV afg AUSTRALIAN FINANCE GROUP LIMITED 45327 691938 agg ANGLOGOLD ASHANTI LIMITED 2625 14880E agi AINSWORTH GAME TECHNOLOGY LIMITED 75090 923040 agl AGL ENERGY LIMITED 19251 29897X ago ATLAS IRON LIMITED 64409 890588 agy ARGOSY MINERALS LIMITED 24151 31511D ahg AUTOMOTIVE HOLDINGS G…
type: Question
has comment: http://stackoverflow.com/comment/89513857
has comment: http://stackoverflow.com/comment/89513418
has comment: http://stackoverflow.com/comment/89513495
score: 0
tagged with: pandas
tagged with: finance
has comment: http://stackoverflow.com/comment/89521069
tagged with: merge
has comment: http://stackoverflow.com/comment/89516247
answer count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89513616
has title: Having trouble merging two dataframes in python
has comment: http://stackoverflow.com/comment/89519675
linked to: http://stackoverflow.com/q/20109391

http://stackoverflow.com/comment/89490123
type: QuestionComment
has text: Also, are you typing `pip list` into the bash shell in your Terminal (at the prompt that looks like `jyabjyabs-macbook:myproj jyabjyabs$`), or did you run `python` in the terminal, and then try to type `pip list` inside Python (at the prompt that looks like `>>>`)? If the latter, that's your problem: `pip` is a command that you run at the shell, not a Python statement.
comment on: http://stackoverflow.com/q/51255533
type: Comment
score: 0

http://stackoverflow.com/comment/89589169
score: 0
has text: ah, it wasn't clear to me what the difference is between this question and the other. the final desired output looks exactly the same. please edit your question. removing the close vote.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51305370

http://stackoverflow.com/comment/89329128
has text: Sorry I didn't mention in the original post that I want to search through all the columns.
type: Comment
comment on: http://stackoverflow.com/a/51170972
type: AnswerComment
score: 0

http://stackoverflow.com/q/51252714
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/51252811
upvote count: 8
has title: How can I make Discord bots display the "Bot is typing ..." status?
tagged with: python
tagged with: discord
score: 8
type: AnsweredQuestion
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/51252816
type: Question
tagged with: discord.py
has answer: http://stackoverflow.com/a/51252816
has body: So if I have a long command like this: @bot.command(pass_context=True) async def longCommand(ctx): #typing status sleep(10) bot.say("Done!") Didn't find anything in the documentation or here, unfortunately.
possible better answer: http://stackoverflow.com/a/51252811
answer count: 3
has answer: http://stackoverflow.com/a/66706506

http://stackoverflow.com/q/51280487
favorite count: 0
tagged with: python-3.x
tagged with: python
accepted answer: http://stackoverflow.com/a/51283845
has title: Copy certain files to other folder using Python ( File Management in Python )
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89538394
score: 3
has answer: http://stackoverflow.com/a/51281125
has comment: http://stackoverflow.com/comment/89539877
upvote count: 3
has comment: http://stackoverflow.com/comment/89540832
has comment: http://stackoverflow.com/comment/89538369
has answer: http://stackoverflow.com/a/51280597
has answer: http://stackoverflow.com/a/51283845
has comment: http://stackoverflow.com/comment/89540757
type: Question
has comment: http://stackoverflow.com/comment/89539229
has comment: http://stackoverflow.com/comment/89538352
has comment: http://stackoverflow.com/comment/89538412
answer count: 3
downvote count: 0
has body: I want to check a folder and all subfolders if a certain file exists. If exists then I want to copy that in another folder. I have tried the following stuff def copy_files(src, dest): files = os.listdir(src) for f in files: shutil.copy(src +f , dest) for root, dirs, files in os.walk(my_path): for f in files: if f.endswith(".7z"): print("found files: " , f) copy_files(my_path, arch_dest) On the copy_files function works. But it does not work inside the for the loop. I am getting the following error: Permission denied: './data/f_1' What am I doing wrong? The Copy function works in other folders. But in this loop, it does not work. I need to make it work inside the loop. Update: I am assuming the problem is more with the path, I have checked inside the for loop it shows the home directory where it is. with print(os.getcwd()) Do I need to then go to the folder while checking the file?
possible better answer: http://stackoverflow.com/a/51280597

http://stackoverflow.com/q/51246990
score: 2
tagged with: python-3.x
type: AnsweredQuestion
has body: I have two classes with functions: from functools import partial class A: def __init__(self, collection): self.collection = collection def filter(self, val): for element in self.collection: if element.var == val: return element class B: def __init__(self, var): self.var = var def test(self): print('Element with variable ', self.var) Now I want to have a class that can call a function on an object, fetched on the fly by another function, both stored in a variable and all executed when a certain function was called: class C: def __init__(self, fetch, function): self.fetch = fetch self.function = function def run(self): global base # ----- # This is the code I need base.fetch().function() # ... and currently it's completely wrong # ----- c = C(partial(A.filter, 5), B.test) base = A([B(3), B(5), B(8)]) c.run() Should print: Element with variable 5
has title: Execute class function stored in variable on demand
tagged with: class
type: Question
upvote count: 2
tagged with: functools
tagged with: function
answer count: 1
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/51247231
tagged with: python
has answer: http://stackoverflow.com/a/51247231

http://stackoverflow.com/a/55326829
upvote count: 1
downvote count: 0
has body: How about something like this import pandas as pd from sklearn.model_selection import cross_val_score from sklearn.naive_bayes import GaussianNB #because only var_smoothing can be 'tuned' #do a cross validation on different var_smoothing values def cross_val(params): model = GaussianNB() model.set_params(**params) cv_results = cross_val_score(model, X_train, y_train, cv = 10, #10 folds scoring = "accuracy", verbose = 2 ) #return the mean of the 10 fold cross validation return cv_results.mean() #baseline parameters params = { "priors" : "None", "var_smoothing" : 1e-9 } #create an list of var_smoothing to cross validate steps = [1e-8, 1e-7, 1e-6, 1e-5, 1e-4] #will contain the cv results results = [] for step in steps: params["var_smoothing"] = step cv_result = cross_val(params) #save result results.append(cv_result) #print results #convert results to pandas dataframe for easier visualization df = pd.DataFrame({"var_smoothing" : steps, "accuracy" : results}) #sort it df_sorted = df.sort_values("accuracy", ascending=False) #reset the index of the sorted dataframe df_sorted.reset_index(inplace=True, drop=True) df_sorted.head()
answers question: http://stackoverflow.com/q/51194627
type: Answer
score: 1

http://stackoverflow.com/comment/89407139
comment on: http://stackoverflow.com/q/51213110
type: QuestionComment
score: 0
type: Comment
has text: For security reasons, always use `ast.literal_eval` instead of `eval`.

http://stackoverflow.com/q/51267029
has answer: http://stackoverflow.com/a/51267139
accepted answer: http://stackoverflow.com/a/51267139
score: 0
answer count: 1
tagged with: python
type: AnsweredQuestion
has title: Why we are using shape=((None,)+image_shape) below what does that mean?
tagged with: tensorflow
type: Question
has body: what does shape=((None,)+image_shape) mean below? tf.placeholder(tf.float32,shape=((None,)+image_shape),name="x")
tagged with: neural-network

http://stackoverflow.com/comment/89339577
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51177900
type: Comment
has text: Yes, you can use Selenium for opening the browser and then loading the relevant site. After that, you can send POST request using 'request' library in Python.

http://stackoverflow.com/q/51199698
score: 1
tagged with: selenium
possible better answer: http://stackoverflow.com/a/51201100
type: Question
answer count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/89382436
has comment: http://stackoverflow.com/comment/89382548
favorite count: 0
tagged with: python-3.x
has body: I've written a script in python in association with selenium to initiate clicks on some links connected to each profile out of a webpage. My script is doing good for the first link. As there is no valid links (all of them are javascript links) connected to each profile, I had to do the clicking. However, when it is supposed to click on the next linkk and so on, It throws an error stale element reference: element is not attached to the page document. If It were not for clicking, I could have easily navigated to each profile without having that error following the logic I applied within my script. In case of clicking links cyclically, I don't find any idea to move along. What can I do now to get rid of that error and click all the links? This is my try: from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC def search_links(driver,link): driver.get(link) items = [item for item in wait.until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, "#main table tr a"))) if "#" not in item.get_attribute("href")] for item in items: item.click() #The error is thrown here as soon as the script goes for the second click wait.until(EC.staleness_of(item)) if __name__ == '__main__': url = "https://intraweb.stockton.edu/eyos/page.cfm?siteID=58&amp;pageID=7&amp;action=dirmain&amp;type=FAC&amp;display=basic" driver = webdriver.Chrome() wait = WebDriverWait(driver, 10) try: search_links(driver,url) finally: driver.quit()
has answer: http://stackoverflow.com/a/51213116
has title: My script encounters an error while clicking links
tagged with: web-scraping
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/51201100
tagged with: selenium-webdriver
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51213116

keyword
tags question: http://stackoverflow.com/q/51214404
tag name: keyword
type: Tag

http://stackoverflow.com/comment/89557765
type: Comment
type: QuestionComment
has text: I've already tried changing the extension - it throws an error whereas it won't when it's writing to a .docx
comment on: http://stackoverflow.com/q/51252040
score: 0

http://stackoverflow.com/comment/89457095
type: Comment
type: QuestionComment
has text: you can almost certainly just use the last 2 ... in fact you could do it with just one command `python manage.py makemigrations && python manage.py migrate`
comment on: http://stackoverflow.com/q/51239135
score: 0

http://stackoverflow.com/q/51247139
has answer: http://stackoverflow.com/a/51247295
tagged with: sorting
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/89473112
has body: Is there any way in which I can sort a CSV file into descending order. I have a CSV file which contains all the scores of different players. The code below pulls the first 5 scores from the csv file and outputs it on my program. However i would like the highest 5 scores to be outputted, not the first 5. Is there anyway in which I can do this. def DisplayLeaderBoard(): count = 0 with open ('StudentNames&amp;Questions.csv') as scorelist: reader = csv.DictReader(scorelist) for row in reader: if count ==250: break count = count+50 scores_label = Label(canvas, text=(row['Names'], row['Score']), bg = 'gray25', fg='snow', font = font1) canvas_scores_label = canvas.create_window(350, 280+count, window = scores_label, width = 500, height = 40) I have played around with this code below, however this is used mainly for arrays. So if anyone knows how to put it first into an array and then into a for loop of labels then please let me know. array.sort(key=lambda x: x[0], reverse=True)
favorite count: 0
accepted answer: http://stackoverflow.com/a/51247295
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
type: AnsweredQuestion
has title: Sorting a CSV file numerically
upvote count: 1
downvote count: 1
type: Question

http://stackoverflow.com/comment/89572959
comment on: http://stackoverflow.com/a/51297436
type: AnswerComment
type: Comment
score: 1
has text: Glad I helped, GC error might be because Java can't use your whole memory, you should raise an upper boundary in Help -> Edit Custom VM Options: https://superuser.com/a/1141412/659142

http://stackoverflow.com/q/51226234
has comment: http://stackoverflow.com/comment/89432715
tagged with: pymongo
has answer: http://stackoverflow.com/a/51227965
has body: Total python noob here. Trying to learn python. I'm using macosx with high sierra 10.13.5 and have python Python 2.7.10. My task here is to run a mongodb query using python, but to no avail as i'm trying to use pymongo. Here's the message that I'm seeing: (executed on command line python mydev.py) File "mydev.py", line 3, in &lt;module&gt; import pymongo File "/usr/local/lib/python2.7/site-packages/pymongo/__init__.py", line 77, in &lt;module&gt; from pymongo.collection import ReturnDocument File "/usr/local/lib/python2.7/site-packages/pymongo/collection.py", line 20, in &lt;module&gt; from bson.code import Code File "/usr/local/lib/python2.7/site-packages/bson/__init__.py", line 84, in &lt;module&gt; from bson.dbref import DBRef File "/usr/local/lib/python2.7/site-packages/bson/dbref.py", line 17, in &lt;module&gt; from copy import deepcopy File "/usr/local/Cellar/python@2/2.7.15_1/Frameworks/Python.framework/Versions/2.7/lib/python2.7/copy.py", line 52, in &lt;module&gt; import weakref File "/usr/local/Cellar/python@2/2.7.15_1/Frameworks/Python.framework/Versions/2.7/lib/python2.7/weakref.py", line 14, in &lt;module&gt; from _weakref import ( ImportError: cannot import name _remove_dead_weakref I got this same message running the python shell with just import pymongo and running the script. My python script: #!/usr/local/bin/python import pymongo import json from pymongo import MongoClient # DB connect client = MongoClient('10.1.2.345') db = client.test collection = db.my_profiles # Read print collection.find_one({"account" : "foo", "profile" : "bar", "info.published" : True}, {"account":1, "profile":1,"settings.region":1}) So, i don't know how do i get this to work. What pkgs am I missing? Thanks for your help.
has comment: http://stackoverflow.com/comment/89433771
type: Question
has title: python - unable to execute python script that uses pymongo
has comment: http://stackoverflow.com/comment/89433659
tagged with: python-2.7
score: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/51227965
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89432641

http://stackoverflow.com/comment/89604565
comment on: http://stackoverflow.com/q/51313593
score: 0
type: Comment
type: QuestionComment
has text: and yes am using python 2.7

http://stackoverflow.com/comment/89320492
comment on: http://stackoverflow.com/a/51168781
score: 0
type: AnswerComment
has text: I created a .bat file with `start /B myfile.exe` and I double clicked the .bat file, but it still opens a command prompt. I want it to be completely in the background. Is this possible?
type: Comment

http://stackoverflow.com/comment/90373537
score: 0
type: Comment
has text: They could be different, but you can't have them all in a single numpy array. So you will need to train each video individually.
type: AnswerComment
comment on: http://stackoverflow.com/a/51274872

http://stackoverflow.com/a/51263761
type: Answer
answers question: http://stackoverflow.com/q/51263436
downvote count: 0
score: 1
has body: This program firstly ask the the three questions, validates them and then asks in loop only for questions that didn't validate. Until all questions are validated: # This is only example validate function: def validate(resp): if resp == "a": return True return False valid = [False, False, False] while not all(valid): a = valid[0] or input("Enter a:") b = valid[1] or input("Enter b:") c = valid[2] or input("Enter c:") valid = [True if valid[i] else bool(validate(v)) for i, v in enumerate((a, b, c))]
upvote count: 1

http://stackoverflow.com/q/51245311
score: 0
has comment: http://stackoverflow.com/comment/89470998
has comment: http://stackoverflow.com/comment/89469458
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89470636
has comment: http://stackoverflow.com/comment/89470259
answer count: 0
has comment: http://stackoverflow.com/comment/89470144
type: Question
has comment: http://stackoverflow.com/comment/89470260
has body: working on some beginner Machine Learning coder exercises. I'm stuck with an error with sklearn.cross_validation and sklearn.model_selection (neither works in my setup). Here's the log: Python 2.7.12 (default, Dec 4 2017, 14:50:18) Type "copyright", "credits" or "license" for more information. IPython 2.4.1 -- An enhanced Interactive Python. ? -&gt; Introduction and overview of IPython's features. %quickref -&gt; Quick reference. help -&gt; Python's own help system. object? -&gt; Details about 'object', use 'object??' for extra details. %guiref -&gt; A brief reference about the graphical user interface. In [1]: import numpy as np ...: import matplotlib.pyplot as plt ...: import pandas as pd In [2]: dataset = pd.read_csv('Salary_Data.csv') ...: X = dataset.iloc[:, :-1].values ...: y = dataset.iloc[:, 1].values In [3]: runfile('/home/rocketchef/Machine Learning/Machine Learning A-Z/Part 2 - Regression/Section 4 - Simple Linear Regression/simple_linear_regression.py', wdir='/home/rocketchef/Machine Learning/Machine Learning A-Z/Part 2 - Regression/Section 4 - Simple Linear Regression') Traceback (most recent call last): File "&lt;ipython-input-3-2d267c940766&gt;", line 1, in &lt;module&gt; runfile('/home/rocketchef/Machine Learning/Machine Learning A-Z/Part 2 - Regression/Section 4 - Simple Linear Regression/simple_linear_regression.py', wdir='/home/rocketchef/Machine Learning/Machine Learning A-Z/Part 2 - Regression/Section 4 - Simple Linear Regression') 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/rocketchef/Machine Learning/Machine Learning A-Z/Part 2 - Regression/Section 4 - Simple Linear Regression/simple_linear_regression.py", line 14, in &lt;module&gt; from sklearn.cross_validation import train_test_split Import…
has comment: http://stackoverflow.com/comment/89472691
has title: Got error despite using either sklearn.cross_valid & sklearn.model_selection
tagged with: scikit-learn
has comment: http://stackoverflow.com/comment/89469634
has comment: http://stackoverflow.com/comment/89470560

http://stackoverflow.com/comment/89593330
comment on: http://stackoverflow.com/q/51305711
type: QuestionComment
has text: using web driver i m pushing these configuration. i didnt want to quit webdriver and open back again only for this purpose.
score: 0
type: Comment

http://stackoverflow.com/q/51272628
has body: I found one python example problem that sounds like "Find the max number of connected colors in the grid". In other words, I have to find the color that is most frequent and also connected together. In my example, it would be 0, 4 times repeated. I made a grid that looks something like this. Each color is a number. arr = [[0,0,0,1], [1,0,2,1], [0,2,1,0]] I don't understand what to do next. I think that I have to start iterating through the array for i in arr:but what do I have to do next?
score: 2
has title: Find the max number of colors in grid
has comment: http://stackoverflow.com/comment/89523881
has comment: http://stackoverflow.com/comment/89523276
favorite count: 0
linked to: http://stackoverflow.com/q/39562365
has comment: http://stackoverflow.com/comment/89524607
type: Question
tagged with: python
downvote count: 2
has comment: http://stackoverflow.com/comment/89524017
has comment: http://stackoverflow.com/comment/89523287
answer count: 1
has comment: http://stackoverflow.com/comment/89523361
tagged with: algorithm
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51273162
upvote count: 4

http://stackoverflow.com/q/51275652
favorite count: 0
tagged with: psql
type: UnansweredQuestion
downvote count: 2
upvote count: 1
tagged with: python
has body: How would I run this psql command from a Python script? psql dbname &lt; dump.sql I have looked at subprocess, but it is not clear how to handle the &lt; redirect from file.
has answer: http://stackoverflow.com/a/51275871
score: -1
has comment: http://stackoverflow.com/comment/89529906
type: Question
tagged with: postgresql
answer count: 1
has title: Running psql command from Python to restore from a PostgreSQL dump file

http://stackoverflow.com/comment/89344562
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51179524
has text: I updated the code to build upon my earlier attempt: making the dictionary match the isoweekday format so that an integer from Monday returns 1 and so on. However I get a KeyError of 3 for today's date, which should be right...Wednesday (or 3).
score: 0

http://stackoverflow.com/comment/89464104
comment on: http://stackoverflow.com/q/51242510
has text: Did you test your globing-statements, i.e. does the listofffiles contain any filepath or will it stay empty? You might simply add an `print(listoffiles)` statement to inspect the list.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51265196
answer count: 1
tagged with: python
has answer: http://stackoverflow.com/a/51265719
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89508379
has title: Organizing dates and holidays in a dataframe
tagged with: dataframe
has comment: http://stackoverflow.com/comment/89508435
type: Question
has body: Scenario: I have one with different columns of data, and another single dataframe with lists of dates. Example of dataframe1: iterationcount datecolumn list iteration5 1 iteration5 2 iteration3 2 iteration3 2 iteration4 33 iteration3 4 iteration1 5 iteration2 3 iteration5 2 iteration4 22 Example of dataframe2: iteration1 01.01.2018 26.01.2018 30.03.2018 iteration2 01.01.2018 30.03.2018 02.04.2018 25.12.2018 26.12.2018 iteration3 iteration4 01.01.2018 15.01.2018 19.02.2018 iteration5 01.01.2018 19.02.2018 30.03.2018 21.05.2018 02.07.2018 06.08.2018 03.09.2018 08.10.2018 12.11.2018 The second dataframe is a list of holidays for each of the iterations. And it will be used to fill the second column of the first dataframe Constraints: For each iteration of the first dataframe the user will select a month and year: the script will then find the first date of that month. If that date is on the list of dates of dataframe2 for that iteration, then pick the next working date based on the program calender. Ex: User selects January 2018, code returns 01/01/2018. For the first iteration, that date is a holiday, so pick the next workday, in this case 02/01/2018, and then input this date to all of dataframe1 corresponding to that iteration: iterationcount datecolumn list iteration5 1 iteration5 2 iteration3 2 iteration3 2 iteration4 33 iteration3 4 iteration1 02/01/2018 5 iteration2 3 iteration5 2 iteration4 22 Then move to the next iteration (some iterations will have the same calendar dates). Code: I have tried multiple approaches so far, but could not achieve the result. The closest I think I got was with: import pandas as pd import datetime import os from os import listdir from os.path import isfile, join import glob ## Get Adjustments mypath3 = "//DGMS/Desktop/Uploader_v1.xlsm" ApplyOnDates = pd.read_excel(open(mypath3, 'rb'), sheet_name='Holidays') # Get content mypath = "//DGMS/Desktop/Uploaded" all_files = glob.glob(os.path.join(mypath, "*.xls*")) contentdataframes = [] co…
score: 0
tagged with: pandas

http://stackoverflow.com/a/51315056
type: Answer
has body: Use *args in all your parent's init class Ball(object): def __init__(self, *args): print ('IN Ball') class BouncingBall(Ball): """ ball effected by gravity """ def __init__(self, bounds, position, velocity, color, radius, weight, *args): print ('IN BouncingBall') super().__init__(bounds, position, velocity, color, radius, *args) self.weight = weight class KineticBall(Ball): """ A ball that collides with other collidable balls using simple elastic circle collision """ def __init__(self, bounds, position, velocity, color, radius, object_list, *args): print ('IN KineticBall') super().__init__(bounds, position, velocity, color, radius, *args) self.object_list = object_list class KineticBouncing(BouncingBall, KineticBall): def __init__(self, bounds, position, velocity, color, radius, weight, object_list): print ('IN KineticBouncing') super().__init__(bounds, position, velocity, color, radius, weight, object_list) Now on creating a new kinetic bouncing ball ball = KineticBouncing('SCREEN_SIZE', 'Vector2(50, 50)', 'Vector2(3, 3)', [255, 0, 255], 10, -1, 'object_list') IN KineticBouncing IN BouncingBall IN KineticBall IN Ball
answers question: http://stackoverflow.com/q/51314305
score: 0

http://stackoverflow.com/comment/89359366
has text: If the culprit is regex, the reason lies in catastrophic backtracking.
type: Comment
comment on: http://stackoverflow.com/q/51188878
score: 2
type: QuestionComment

http://stackoverflow.com/a/51226584
downvote count: 0
score: 1
type: Answer
answers question: http://stackoverflow.com/q/51226468
upvote count: 1
has body: import operator nlist = [2, 2, 4, 8, 0, 2, 8, 0, 0, 0, 0, 2, 4, 2, 2, 0] size = int(len(nlist) ** .5) print(list(zip(*map(lambda c: list(filter(bool, c)) + list(filter(operator.__not__, c)), zip(*[nlist[i * size: (i + 1) * size] for i in range(size)]))))) This outputs: [(2, 2, 4, 8), (4, 2, 8, 2), (0, 2, 2, 0), (0, 0, 0, 0)] Or if you prefer it flattened: print([a for r in zip(*map(lambda c: list(filter(bool, c)) + list(filter(operator.__not__, c)), zip(*[nlist[i * size: (i + 1) * size] for i in range(size)]))) for a in r]) This outputs: [2, 2, 4, 8, 4, 2, 8, 2, 0, 2, 2, 0, 0, 0, 0, 0]

http://stackoverflow.com/q/51175281
type: UnansweredQuestion
tagged with: python
tagged with: heroku-postgres
type: Question
has body: I have installed dj_database_url in my project but it is still producing an error when I do import dj_database_url. No module name dj_database_url Here's what my code looks like: import dj_database_url db_from_env = dj_database_url.config(conn_max_age=500) DATABASES['default'].update(db_from_env)
has answer: http://stackoverflow.com/a/51175572
score: 0
answer count: 1
has title: No module name dj_database_url

http://stackoverflow.com/q/51220161
has comment: http://stackoverflow.com/comment/89421219
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/51220167
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/89421187
type: Question
linked to: http://stackoverflow.com/q/444591
has title: How to convert from bytes to int?
has body: I know that to convert from int to bytes you have to do this, for example: &gt;&gt;&gt;a = bytes(4) &gt;&gt;&gt;print(a) b'\x00\x00\x00\x00' But what do I do if I want to revert it and convert bytes to int or float? I tried using: int.from_bytes( a, byteorder='little') and int.from_bytes( a, byteorder='big', signed=True) but it did not work.
has comment: http://stackoverflow.com/comment/89421224
duplicate of: http://stackoverflow.com/q/444591
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/comment/89462401
type: AnswerComment
has text: Many thanks, seems like that's it. I copied the deploy files and probably didn't notice that. I will run a new teaching process and let you know if that solved my issue and of course approve the answer. Thanks!
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51239969

http://stackoverflow.com/a/51260202
answers question: http://stackoverflow.com/q/51243578
type: Answer
has body: Although you have not stated it, you are clearly running this code in Python 3. The semantics of map changed between Python 2 and Python 3. In Python 2 map returns a list. In Python 3 it returns an iterator. See here. To fix this you need to do something like: block_ct = list(map(lambda x: int(math.ceil(float(x) / thread_ct[0])),[rows,ndims])) Alternatively you could just use a list comprehension without the lambda expression and map call: block_ct = [ int(math.ceil(float(x) / thread_ct[0])) for x in [rows,ndims] ] Either will yield a list with the necessary elements which should work in the CUDA kernel launch call.
upvote count: 1
score: 1
downvote count: 0

http://stackoverflow.com/comment/89346281
has text: Try copy pasting the code directly, avoid images for code to make it easy for us to help ;)
score: 0
comment on: http://stackoverflow.com/q/51181282
type: QuestionComment
type: Comment

dictionary
tags question: http://stackoverflow.com/q/51243303
tags question: http://stackoverflow.com/q/51301739
tags question: http://stackoverflow.com/q/51293794
tags question: http://stackoverflow.com/q/51308352
tags question: http://stackoverflow.com/q/51178693
tags question: http://stackoverflow.com/q/51201390
tags question: http://stackoverflow.com/q/51232080
tags question: http://stackoverflow.com/q/51227172
tags question: http://stackoverflow.com/q/51321723
tags question: http://stackoverflow.com/q/51194652
tags question: http://stackoverflow.com/q/51176864
tags question: http://stackoverflow.com/q/51219761
tags question: http://stackoverflow.com/q/51298087
tags question: http://stackoverflow.com/q/51219581
tags question: http://stackoverflow.com/q/51270051
tags question: http://stackoverflow.com/q/51197439
tags question: http://stackoverflow.com/q/51187967
tags question: http://stackoverflow.com/q/51251835
tags question: http://stackoverflow.com/q/51289736
tags question: http://stackoverflow.com/q/51226619
tags question: http://stackoverflow.com/q/51240613
tags question: http://stackoverflow.com/q/51217104
tags question: http://stackoverflow.com/q/51262549
tags question: http://stackoverflow.com/q/51279181
tags question: http://stackoverflow.com/q/51200982
tags question: http://stackoverflow.com/q/51239425
tags question: http://stackoverflow.com/q/51187459
tags question: http://stackoverflow.com/q/51244920
tags question: http://stackoverflow.com/q/51314701
tags question: http://stackoverflow.com/q/51184734
tags question: http://stackoverflow.com/q/51304738
tags question: http://stackoverflow.com/q/51169932
tags question: http://stackoverflow.com/q/51289482
tags question: http://stackoverflow.com/q/51250375
tags question: http://stackoverflow.com/q/51178256
tags question: http://stackoverflow.com/q/51181229
tags question: http://stackoverflow.com/q/51263226
tags question: http://stackoverflow.com/q/51199011
tags question: http://stackoverflow.com/q/51260270
tags question: http://stackoverflow.com/q/51192145
tags question: http://stackoverflow.com/q/51319061
tags question: http://stackoverflow.com/q/51192534
tags question: http://stackoverflow.com/q/51294426
tags question: http://stackoverflow.com/q/51301426
tags question: http://stackoverflow.com/q/51189289
tags question: http://stackoverflow.com/q/51243242
tags question: http://stackoverflow.com/q/51323218
tags question: http://stackoverflow.com/q/51202370
tag name: dictionary
tags question: http://stackoverflow.com/q/51242725
tags question: http://stackoverflow.com/q/51312690
tags question: http://stackoverflow.com/q/51219148
tags question: http://stackoverflow.com/q/51205726
tags question: http://stackoverflow.com/q/51268745
tags question: http://stackoverflow.com/q/51216292
tags question: http://stackoverflow.com/q/51225946
tags question: http://stackoverflow.com/q/51208672
tags question: http://stackoverflow.com/q/51289564
tags question: http://stackoverflow.com/q/51203760
tags question: http://stackoverflow.com/q/51303187
tags question: http://stackoverflow.com/q/51189741
tags question: http://stackoverflow.com/q/51170125
tags question: http://stackoverflow.com/q/51198179
tags question: http://stackoverflow.com/q/51206916
tags question: http://stackoverflow.com/q/51199309
tags question: http://stackoverflow.com/q/51310462
tags question: http://stackoverflow.com/q/51210929
tags question: http://stackoverflow.com/q/51312587
tags question: http://stackoverflow.com/q/51304016
tags question: http://stackoverflow.com/q/51241706
tags question: http://stackoverflow.com/q/51253061
tags question: http://stackoverflow.com/q/51224731
tags question: http://stackoverflow.com/q/51315083
tags question: http://stackoverflow.com/q/51296552
tags question: http://stackoverflow.com/q/51233680
tags question: http://stackoverflow.com/q/51249479
tags question: http://stackoverflow.com/q/51214726
tags question: http://stackoverflow.com/q/51248218
tags question: http://stackoverflow.com/q/51258434
tags question: http://stackoverflow.com/q/51275516

http://stackoverflow.com/comment/89508807
type: QuestionComment
has text: Where do I find it? I am executing that spider from a script, and I am new to web crawling :/
type: Comment
comment on: http://stackoverflow.com/q/51264283
score: 0

http://stackoverflow.com/q/51272768
tagged with: python
favorite count: 0
type: UnansweredQuestion
has body: I am a noob to Python BeautifulSoup, in fact I am noob to Python at all. I tried to scrape this webpage (https://th.jbl.com/bluetooth-portables) as a self-study exercise. I would like to scrape the SKU information of each product: category, subcategory, name, and productID to be precise. I managed to scrape category, subcategory, and most of the product name as well as their productID, but as you may see the product listings in this page is not consistent, and I just got repeatedly stuck to product: Xtreme 2 which does not have productID. At this stage, the scrape just flatly stops, whilst there are still 3 product tiles in need of scraping. I tried and tried but just couldn't get through. As a matter of fact, Xtreme 2 is only get printed with name, but no information is written to the file. My method is to scrape all tiles that contains products whilst ignore the rest. Below are the codes: from bs4 import BeautifulSoup import requests, csv, codecs, json jbl_file = codecs.open('JBL_TH.csv','w',encoding='utf_8_sig') csv_writer = csv.writer(jbl_file) csv_writer.writerow(['Category','Subcategory','Product','Prod_ID']) url = 'https://th.jbl.com/bluetooth-portables' source = requests.get(url).content soup = BeautifulSoup(source,'lxml') home = soup.find('div',class_='breadcrumb clearfix') # find the category and subcategory category = home.find('h2',property='name').text subcategory = home.find('span',class_='breadcrumb-last',property='name').text # define the scope of product container all = soup.find('div',id='search-result-items') # each product is in a tile, so find all the tiles for tile in all.find_all('div',class_='product-tile'): print(category) print(subcategory) # the tile may not contain product, hence steps to ignore such tile by try ... except ... try: # find out the name of the product in each tile name = tile.find('a',class_='productname-link')['title'] print(name) # even if product exists in the tile, SKU ID may not exist in class product-swtches, # hence …
tagged with: web-scraping
has answer: http://stackoverflow.com/a/51273056
downvote count: 0
score: 1
type: Question
answer count: 2
upvote count: 1
has answer: http://stackoverflow.com/a/51273235
has title: Tried to scrape a webpage by using BeautifulSoup4 and then it just stops halfway through

http://stackoverflow.com/a/51239426
has comment: http://stackoverflow.com/comment/89457708
score: -1
answers question: http://stackoverflow.com/q/51239353
has comment: http://stackoverflow.com/comment/89457838
has comment: http://stackoverflow.com/comment/89457749
has comment: http://stackoverflow.com/comment/137032520
has comment: http://stackoverflow.com/comment/89457790
downvote count: 1
type: Answer
has body: You need to install it from the command line. Go to Python folder under the below location. cd C:\Users\{username}\AppData\Local\Programs\Python\{python version}\Scripts pip install selenium
upvote count: 0

http://stackoverflow.com/comment/99878089
type: AnswerComment
comment on: http://stackoverflow.com/a/53973431
type: Comment
has text: @zerohedge Thanks for the compliment! This is really helpful for my motivation to work on ftputil. :-)
score: 1

http://stackoverflow.com/a/51231402
score: 10
accepted answer of: http://stackoverflow.com/q/51230726
has body: You'll have to combine different bits of data: Estimator ParamMaps extracted using getEstimatorParamMaps method. Training metrics which can be retrieved using avgMetrics parameter. First get names and values of all parameters declared in the map: params = [{p.name: v for p, v in m.items()} for m in cvModel.getEstimatorParamMaps()] Thane zip with metrics and convert to a data frame import pandas as pd pd.DataFrame.from_dict([ {cvModel.getEvaluator().getMetricName(): metric, **ps} for ps, metric in zip(params, cvModel.avgMetrics) ])
type: AcceptedAnswer
upvote count: 10
type: Answer
has comment: http://stackoverflow.com/comment/89442877
downvote count: 0
has comment: http://stackoverflow.com/comment/100561600
answers question: http://stackoverflow.com/q/51230726

http://stackoverflow.com/comment/89348293
type: QuestionComment
comment on: http://stackoverflow.com/q/51182988
has text: The first cell of `col2_vals_exist_in_col1` says `False` and why is that?
score: 0
type: Comment

dialogflow-es
tag name: dialogflow-es
tags question: http://stackoverflow.com/q/51204486
tags question: http://stackoverflow.com/q/51284904
type: Tag
tags question: http://stackoverflow.com/q/51187856

http://stackoverflow.com/q/51291722
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51294709
has body: Values that can be converted to a JSON string via json.dumps are: Scalars: Numbers and strings Containers: Mapping and Iterable Union[str, int, float, Mapping, Iterable] Do you have a better suggestion?
score: 46
type: Question
tagged with: mypy
upvote count: 46
has comment: http://stackoverflow.com/comment/89643280
has answer: http://stackoverflow.com/a/77361801
has comment: http://stackoverflow.com/comment/109273315
answer count: 3
has answer: http://stackoverflow.com/a/51294709
has title: Define a jsonable type using mypy / PEP-526
downvote count: 0
tagged with: python-typing
favorite count: 0
possible better answer: http://stackoverflow.com/a/58405201
has answer: http://stackoverflow.com/a/58405201
tagged with: python

http://stackoverflow.com/a/51308256
type: Answer
answers question: http://stackoverflow.com/q/51307128
has body: import calendar df= pd.DataFrame({'date': ['6/8/2015','7/10/2018','6/5/2015'],'food':[1.5,2.5,3],'drinks':[2,2.4,3],'wastage':[2,2.5,3],}) df.date=pd.to_datetime(df.date,format="%m/%d/%Y") df=pd.DataFrame(df.groupby(by=[df.date.dt.month.rename('month'),df.date.dt.year.rename('year')]).mean()).reset_index() df['month'] = df['month'].apply(lambda x: calendar.month_abbr[x]) df['year']=df['year'].apply(str) df['year']=df.year.str.replace("20","") df['period'] = df'month', 'year'.apply(lambda x: '-'.join(x), axis=1) df=df.drop(['year','month'],axis=1) df=df.rename(index=str, columns={"period": "month"}) cols = df.columns.tolist() cols = cols[-1:] + cols[:-1] df[cols] Output month drinks food wastage 0 Jun-15 2.5 2.25 2.5 1 Jul-18 2.4 2.50 2.5
score: 0

http://stackoverflow.com/q/51244013
answer count: 1
has comment: http://stackoverflow.com/comment/89468384
has comment: http://stackoverflow.com/comment/89466790
has comment: http://stackoverflow.com/comment/89466429
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89469804
type: Question
has comment: http://stackoverflow.com/comment/89468563
has comment: http://stackoverflow.com/comment/89466533
has comment: http://stackoverflow.com/comment/89467669
has title: Return a distance matrix containing vectors
has body: I am trying to calculate a distance matrix, but from vectors so I want to return a distance matrix where (i, j) is the distance between two vectors, e.g. between a and b. So I wish to create for example in this case a 4x4 matrix that contain a vector in each position. Here are my sample arrays, each contain a vector with multiple points. a = [a1, a2, a3] b = [b1, b2, b3] c = [c1, c2, c3] I tried using the scipy.spatial.distance.pdist and squareform (which just gives me a full instead of condensed matrix), but it returns me single values instead of vectors. So a matrix like this, [ 0 1 2 1 0 2 2 3 0 ] Instead of this, where each i, j position is the distance between two vectors therefore contains 5 points as per the example. [ [a1/a1, a2/a2, a3/a3 ] [a1/b1, a2/b2, a3/b3] [a1/c1, a2/c2, a3/c3] [b1/a1, b2/a2, b3/a3] [b1/b1, b2/b2, b3/b3] [b1/c1, b2/c2, b3/c3] [c1/a1, c2/a2, c3/a3] [c1/b1, c2/b2, c3/b3] [c1/c1, c2/c2, c3/c3]] I want to calculate the distance of each value in the array individually, so I do not wish to calculate the Eucladian distance of a1, a2, a3 against b1, b2, b3 but rather just a1 against b1 and so on... I want to return a vector that includes the distance calculated between all the values of array a and b and position it at (a,b). By the '/' I want to show between which two values the distance should be calculated.
has answer: http://stackoverflow.com/a/51245927
accepted answer: http://stackoverflow.com/a/51245927
score: 0
has comment: http://stackoverflow.com/comment/89466584

http://stackoverflow.com/q/51277851
tagged with: http://stackoverflow.com/tag/html
tagged with: python
has comment: http://stackoverflow.com/comment/89534795
has comment: http://stackoverflow.com/comment/89533542
tagged with: css
has body: I have searched all over for a simple solution to this problem, but have yet to find anything. Please let me know how you would approach this. I have a Django project and an app in which of the views for the app calls a function that takes a significant amount of time (upwards of 5-10 min) to run, so I would like to display a loading screen temporarily, and then have the results of the function display. I've looked into using JavaScript, IFrames, and other solutions, but nothing has yet to work. Please keep in mind that I'm a beginner/intermediate programmer, but I would like to know if there's a simple solution to what I thought was a simple and common problem, or if I need something more complex.
favorite count: 0
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89533570
upvote count: 1
tagged with: django
has title: Creating a Loading Screen in Django
has comment: http://stackoverflow.com/comment/89533572
has comment: http://stackoverflow.com/comment/89533314
has comment: http://stackoverflow.com/comment/89533337
has comment: http://stackoverflow.com/comment/89533707
has comment: http://stackoverflow.com/comment/89533567
type: Question
has comment: http://stackoverflow.com/comment/89533687
downvote count: 0
tagged with: javascript
score: 1
has comment: http://stackoverflow.com/comment/89533371
has comment: http://stackoverflow.com/comment/89533637
linked to: http://stackoverflow.com/q/8317219

http://stackoverflow.com/comment/89580953
type: QuestionComment
has text: please read https://stackoverflow.com/help/how-to-ask
score: 3
comment on: http://stackoverflow.com/q/51302042
type: Comment

http://stackoverflow.com/a/51207424
type: Answer
has comment: http://stackoverflow.com/comment/89396381
has comment: http://stackoverflow.com/comment/89395889
score: 2
upvote count: 2
has body: You can do this easily with regex You can filter number and special chars containing + or - or space import re with open("fastlane.txt","r+") as f: re.findall(r'[\d +-]+', f.read()) # ['1241515151', '+43 2414141414', '0221412414', '01989797 8', '214141'] Or to filter everything except quotes and newline re.findall(r'[^"\n]+', f.read()) # ['xxxxx', '1241515151', '+43 2414141414', '0221412414', '01989797 8', '214141']
has comment: http://stackoverflow.com/comment/89396212
answers question: http://stackoverflow.com/q/51207367
downvote count: 0

http://stackoverflow.com/q/51260235
tagged with: python
answer count: 0
type: Question
has comment: http://stackoverflow.com/comment/89499519
has body: I want to make boxplot using two features namely-'date_submitted' &amp; 'final_result'. I have checked the documentation. I don't understand why this error is coming. I used the following code- import pandas as pd import numpy as np df = pd.read_csv('/home/user/Documents/MOOC dataset cleaned/assessments.csv') df.boxplot(column ='date_submitted', by='final_result') this is the description of my dataset- date_submitted date_registration date_unregistration sum_click \ count 28785.000000 28785.000000 28785.000000 28785.000000 mean 26.414139 -69.139552 321.657426 2.660066 std 15.890933 49.305239 188.935462 5.177789 min -11.000000 -322.000000 -317.000000 1.000000 25% 18.000000 -100.000000 130.000000 1.000000 50% 24.000000 -56.000000 445.000000 1.000000 75% 30.000000 -29.000000 445.000000 3.000000 max 241.000000 124.000000 445.000000 511.000000 num_of_prev_attempts age_band region highest_education \ count 28785.000000 28785.000000 25559.000000 28785.000000 mean 0.121278 1.693660 5.041981 1.280111 std 0.420666 0.474206 3.689341 0.769604 min 0.000000 0.000000 0.000000 0.000000 25% 0.000000 1.000000 2.000000 1.000000 50% 0.000000 2.000000 5.000000 1.000000 75% 0.000000 2.000000 9.000000 2.000000 max 6.000000 2.000000 11.000000 4.000000 studied_credits score final_result count 28785.000000 28785.000000 28785.000000 mean 78.691506 75.453431 1.029703 std 40.617665 19.968919 0.884043 min 30.000000 0.000000 0.000000 25% 60.000000 68.000000 0.000000 50% 60.000000 82.000000 1.000000 75% 120.000000 87.000000 2.000000 max 655.000000 100.000000 2.000000 error traceback- Traceback (most recent call last): File "/home/user/Documents/outliers.py", line 6, in &lt;module&gt; df.boxplot(column ='date_submitted', by='final_result') File "/usr/lib/python2.7/dist-packages/pandas/core/frame.py", line 5516, in boxplot **kwds) File "/usr/lib/python2.7/dist-packages/pandas/tools/plotting.py", line 2689, in boxplot return_type=return_type) File "/usr/lib/python2.7/dist-packages/pandas/tools/plotti…
has comment: http://stackoverflow.com/comment/89498808
has comment: http://stackoverflow.com/comment/89498655
score: 0
tagged with: pandas
has title: KeyError: 'final_result' when using boxplot
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89498729

http://stackoverflow.com/comment/89633638
type: AnswerComment
type: Comment
has text: @mm_, I did. And it worked well for me. What is the size of the files that you get?
comment on: http://stackoverflow.com/a/51319161
score: 0

http://stackoverflow.com/q/51200714
type: Question
has body: How do I get VSC to show python executed code only in debug window. Currently, it keeps showing in the terminal with a long ugly path before the result. The Debug console shows "hello world" nicely but I'm doing a tutorial and I don't want the terminal automatically being the default to show the output with this long ugly path. Any one know how to configure it to do this? I tried many configurations in launch.json to no avail.
tagged with: visual-studio-code
has title: How do I get Visual Studio Code to show python executed code only in debug window?
upvote count: 1
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
answer count: 0
downvote count: 0
score: 1

http://stackoverflow.com/comment/109732967
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52630957
has text: But: "Resources are **not** thread safe", "It is recommended to create a resource instance for each thread / process", see https://boto3.amazonaws.com/v1/documentation/api/latest/guide/resources.html#multithreading-and-multiprocessing
score: 0

http://stackoverflow.com/comment/89644812
score: 0
type: Comment
has text: numpy version '1.14.5', python 2.7.15rc1, File.data.shape = (88471, 2), not working for me.
comment on: http://stackoverflow.com/a/51319161
type: AnswerComment

http://stackoverflow.com/comment/89404269
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51210773
type: Comment
has text: OH! I forgot to mention, if you want a permanent record of your interaction with the interpreter NOTHING beats the [Jupyter notebook](https://jupyter.org).

http://stackoverflow.com/comment/89492649
type: Comment
comment on: http://stackoverflow.com/a/51256893
score: 0
type: AnswerComment
has text: Thanks for that, I'm taking it that this executes anything within the script tags however I have an imported script such as ` ` and then my main code script(which uses the somejs.js), ` `. Which is why I was using the pyqt as I thought it executed the entire pages JS.

size
type: Tag
tags question: http://stackoverflow.com/q/51192250
tags question: http://stackoverflow.com/q/51285184
tag name: size
tags question: http://stackoverflow.com/q/51307031

http://stackoverflow.com/comment/89591978
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51307379
score: 0
has text: lncognos and @trixn, nice tips! You helped me a lot. I will search about that and in a few minutes I come back to give you a feedback. I was crazy about that since Monday!

http://stackoverflow.com/q/51205939
has answer: http://stackoverflow.com/a/51206516
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/89393725
has title: flask postgres dynamic query string with variable
type: AnsweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/89393940
tagged with: sqlalchemy
type: Question
accepted answer: http://stackoverflow.com/a/51206516
has comment: http://stackoverflow.com/comment/89393183
has comment: http://stackoverflow.com/comment/95669279
has body: I'm trying to dynamically query a PostgresSQL table with a variable. For instance, when the user enters a name, I want to the user to be redirected to a page that shows table data associated with that name (rows from a database table that have that name in a specific column). I know I am properly connected to a PostgresSQL database. In my Flask app.py file, I have: @app.route("/test") def hello(): html = render_template('test_index.html') return html @app.route("/results") def goodbye(): x = request.args.get('stuff') image=sql("SELECT * FROM image WHERE image_id = '%s'" % ({x})) html = render_template('test_results.html', target=x, image=image) return html In my test_index.html template, I have: Hello In my test_results.html template, I have: Image ID: {{target}} Image ID {% for images in image %} {{ images.image_id }} {% endfor %} When I enter a name, I get this error: ProgrammingError: (psycopg2.ProgrammingError) syntax error at or near "John" LINE 1: SELECT * FROM image WHERE image_id = 'set([u'John'... Is there a way to make this method of dynamically querying by string possible? Or am I approaching this problem in an incorrect manner? (Would I have to declare a model and approach it that way?)
has comment: http://stackoverflow.com/comment/89393425
has comment: http://stackoverflow.com/comment/89392861
has comment: http://stackoverflow.com/comment/89393627
has comment: http://stackoverflow.com/comment/89393820
answer count: 1
downvote count: 0
favorite count: 0

http://stackoverflow.com/q/51287504
has answer: http://stackoverflow.com/a/51287572
score: 5
tagged with: datetime
tagged with: python
has title: Remove the time from datetime.datetime in pandas column
has body: I have a pandas column called 'date' which has values and type like 2014-07-30 00:00:00 &lt;class 'datetime.datetime'&gt;. I want to remove the time from the date.The end result being `2014-07-30' in datetime.datetime format. I tried a bunch of solutions like- df['PSG Date '] = df['PSG Date '].dt.date but its giving me error- AttributeError: Can only use .dt accessor with datetimelike values
type: Question
upvote count: 5
has answer: http://stackoverflow.com/a/51288034
has answer: http://stackoverflow.com/a/51287534
answer count: 3
tagged with: pandas
downvote count: 0
favorite count: 0
type: UnansweredQuestion

http://stackoverflow.com/a/51168070
score: 1
type: AcceptedAnswer
downvote count: 0
has body: You should write: code = "print('hello\\n')"
type: Answer
accepted answer of: http://stackoverflow.com/q/51168035
upvote count: 1
answers question: http://stackoverflow.com/q/51168035

http://stackoverflow.com/q/51212160
has answer: http://stackoverflow.com/a/51333847
favorite count: 0
accepted answer: http://stackoverflow.com/a/51333847
tagged with: command-line
has answer: http://stackoverflow.com/a/54538799
upvote count: 10
tagged with: python
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/54538799
downvote count: 0
has body: I have successfully trained a DNNClassifier to classify texts (posts from an online discussion board). I've saved the model and I now want to classify texts using the TensorFlow CLI. When I run saved_model_cli show for my saved model, I get this output: saved_model_cli show --dir /my/model --tag_set serve --signature_def predict The given SavedModel SignatureDef contains the following input(s): inputs['examples'] tensor_info: dtype: DT_STRING shape: (-1) name: input_example_tensor:0 The given SavedModel SignatureDef contains the following output(s): outputs['class_ids'] tensor_info: dtype: DT_INT64 shape: (-1, 1) name: dnn/head/predictions/ExpandDims:0 outputs['classes'] tensor_info: dtype: DT_STRING shape: (-1, 1) name: dnn/head/predictions/str_classes:0 outputs['logistic'] tensor_info: dtype: DT_FLOAT shape: (-1, 1) name: dnn/head/predictions/logistic:0 outputs['logits'] tensor_info: dtype: DT_FLOAT shape: (-1, 1) name: dnn/logits/BiasAdd:0 outputs['probabilities'] tensor_info: dtype: DT_FLOAT shape: (-1, 2) name: dnn/head/predictions/probabilities:0 Method name is: tensorflow/serving/predict I cannot figure out the correct parameters for saved_model_cli run to get a prediction. I have tried several approaches, for example: saved_model_cli run --dir /my/model --tag_set serve --signature_def predict --input_exprs='examples=["klassifiziere mich bitte"]' Which gives me this error message: InvalidArgumentError (see above for traceback): Could not parse example input, value: 'klassifiziere mich bitte' [[Node: ParseExample/ParseExample = ParseExample[Ndense=1, Nsparse=0, Tdense=[DT_STRING], dense_shapes=[[1]], sparse_types=[], _device="/job:localhost/replica:0/task:0/device:CPU:0"](_arg_input_example_tensor_0_0, ParseExample/ParseExample/names, ParseExample/ParseExample/dense_keys_0, ParseExample/ParseExample/names)]] What is the correct way to pass my input string to the CLI to get a classification? You can find the code of my project, including the training data, on G…
has title: How to Do a Simple CLI Query for a Saved Estimator Model?
tagged with: tensorflow
type: Question
score: 10
linked to: http://stackoverflow.com/q/51249989
answer count: 2
has comment: http://stackoverflow.com/comment/89481345
has comment: http://stackoverflow.com/comment/89481237

http://stackoverflow.com/comment/89588921
type: QuestionComment
has text: No i never seen before, i see it now.
comment on: http://stackoverflow.com/q/51306118
score: 0
type: Comment

http://stackoverflow.com/comment/89323154
type: AnswerComment
comment on: http://stackoverflow.com/a/51169903
type: Comment
has text: By "main parts" I mean "core" part of your code - those functions/statements that you want to run after running, so in your case everything thats not inside any methods - so those lines I put in `if __name__ == '__main__':`. That way it's much easier to see what will happen when you run the code - everything inside this `if` will be executed.
score: 1

http://stackoverflow.com/q/51209547
has comment: http://stackoverflow.com/comment/89399748
type: Question
tagged with: debugging
answer count: 2
tagged with: python-2.7
score: 0
has comment: http://stackoverflow.com/comment/89399737
has title: Trying to create finit sequences of numbers in python2: IndexError (beginner)
type: UnansweredQuestion
tagged with: python
has body: edit: The initial problem is solved now, look at the bottom of the question; I have another problem. I have a list, s2 that its first element (s[0]) is a list of numbers with the length of n (defined by user input) and its elements are also defined by the user. What I want to do is to create n-1 more sequences of numbers as other elements of s2. Each of those sequences is made of the subtraction of the sequential elements in the previous sequence. (the right element - the left element) so the second sequence's length is n-1, the third: n-2 ... and the nth sequence's length (s2[n-1]'s) is 1. for j in range(1, n): for k in range(0,n-j): s2[j].append(s2[j-1][k+1] - s2[j-1][k]) but I get this error: Traceback (most recent call last): File "[path]", line 9, in &lt;module&gt; s2[j].append(s2[j-1][k+1] - s2[j-1][k]) IndexError: list index out of range Can you help me debug this? edit: n = int(raw_input()) s = raw_input() s1 = [int(i) for i in s.split(" ")] s2 = [] s2.append(s1) for j in range(1, n): for k in range(0,n-j): s2[j].append(s2[j-1][k+1] - s2[j-1][k]) example input: 4 1 2 3 4 ps: Can you suggest me another method to get the nth one faster than this? instead of creating all of these lists? (I want it to take less than 1 sec even when n is very big)
tagged with: list
has answer: http://stackoverflow.com/a/51209759
tagged with: index-error
has answer: http://stackoverflow.com/a/51209669

http://stackoverflow.com/comment/89432665
score: 0
has text: Meanwhile, have you read [the help](https://www.crummy.com/software/BeautifulSoup/bs4/doc/#kinds-of-filters), or are you trying to guess at the rules by looking at random examples you find online?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51226138

http://stackoverflow.com/comment/89570267
comment on: http://stackoverflow.com/a/51295978
score: 0
type: AnswerComment
has text: *Why* must array have the same length as A?
type: Comment

http://stackoverflow.com/q/51170418
downvote count: 1
has title: Finding the line number of a matched pattern without using enumerate
type: Question
upvote count: 0
score: -1
tagged with: text-processing
has answer: http://stackoverflow.com/a/51172928
has body: I want to find the line number of a pattern in a file without using enumerate. Are there any Python libraries which directly give line numbers of a pattern?
answer count: 1
has comment: http://stackoverflow.com/comment/89323584
favorite count: 0
has comment: http://stackoverflow.com/comment/89324084
type: UnansweredQuestion
tagged with: python
tagged with: enumerate
has comment: http://stackoverflow.com/comment/89323512
has comment: http://stackoverflow.com/comment/89323998

http://stackoverflow.com/a/51255883
has body: Assuming that your numpy array x contains lines of the csv file in its rows, and the values in its columns, you could approach the problem like this (sort of the old fashion way). first_row_third_col_x = x[0][2] last_row_third_col_x = x[-1][2] if first_row_third_col_x , 0.5 or last_row_third_col_x &lt; 0.5: print('right') else: print('wrong')
type: Answer
score: 0
answers question: http://stackoverflow.com/q/51255828

http://stackoverflow.com/comment/89549365
type: Comment
has text: @mkheifetz That's interesting. It might be a difference in how Excel serializes numbers to dates and how MSSQL serializes numbers to dates. Here's a [post](https://stackoverflow.com/questions/27065040/sql-server-and-excel-float-to-date-offset) on this. What you could try (and it will involve some major code changes) is to use SQLAlchemy and then use panda's [`to_sql`](https://pandas.pydata.org/pandas-docs/version/0.23/generated/pandas.DataFrame.to_sql.html) method to dump the data to the db. The method will do the date abstractions for you.
type: AnswerComment
comment on: http://stackoverflow.com/a/51273292
score: 0

http://stackoverflow.com/q/51192294
tagged with: compare
has comment: http://stackoverflow.com/comment/89366258
tagged with: http://stackoverflow.com/tag/html
tagged with: python
has comment: http://stackoverflow.com/comment/89366864
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/51192781
accepted answer: http://stackoverflow.com/a/51192781
tagged with: web-scraping
type: Question
has body: I'm trying to webscrape only the number in this part, and after that compare it with another number. This number is a &quot;sum number&quot;, it is counting how many device are avaiable on the page. How can I webscraping only this number and put it into a variable? This number is &quot;39&quot; in this code: &lt;div class=&quot;search-results&quot;&gt; &lt;p class=&quot;search-results__text ff-nor fs-1-5 ng-binding&quot;&gt;39&lt;strong&gt;&amp;nbsp;tartozék&lt;/strong&gt; felelt meg a szűrési feltételeknek a 217-ből&lt;/p&gt; &lt;/div&gt; I tried this one: browser = webdriver.Firefox() datatable=[] link='https://....' browser.get(link) time.sleep(10) html = browser.page_source soup=BeautifulSoup(html,&quot;html.parser&quot;) table = soup.find('div', { &quot;class&quot; : &quot;search-results__text ff-nor fs-1-5 ng-binding&quot; })
has title: How to webscraping a specific text and convert it to a number?
has comment: http://stackoverflow.com/comment/89366959
has comment: http://stackoverflow.com/comment/89366484
upvote count: 1
answer count: 1
downvote count: 0
favorite count: 0

performance
tags question: http://stackoverflow.com/q/51179290
tags question: http://stackoverflow.com/q/51268370
tags question: http://stackoverflow.com/q/51170893
tags question: http://stackoverflow.com/q/51307407
tags question: http://stackoverflow.com/q/51303059
tags question: http://stackoverflow.com/q/51226866
tags question: http://stackoverflow.com/q/51189483
tags question: http://stackoverflow.com/q/51255592
tags question: http://stackoverflow.com/q/51281236
tags question: http://stackoverflow.com/q/51282706
tags question: http://stackoverflow.com/q/51225423
tags question: http://stackoverflow.com/q/51264692
tags question: http://stackoverflow.com/q/51267217
tags question: http://stackoverflow.com/q/51205061
tags question: http://stackoverflow.com/q/51186680
tags question: http://stackoverflow.com/q/51240548
tags question: http://stackoverflow.com/q/51298834
tags question: http://stackoverflow.com/q/51195958
tag name: performance
tags question: http://stackoverflow.com/q/51207723
tags question: http://stackoverflow.com/q/51315123
type: Tag
tags question: http://stackoverflow.com/q/51291281
tags question: http://stackoverflow.com/q/51250350
tags question: http://stackoverflow.com/q/51210152
tags question: http://stackoverflow.com/q/51223640
tags question: http://stackoverflow.com/q/51221951
tags question: http://stackoverflow.com/q/51228131

http://stackoverflow.com/comment/89421709
comment on: http://stackoverflow.com/q/51220389
type: Comment
type: QuestionComment
score: 1
has text: No that isn't what I am looking for, I am just wondering if I can return strings with operators like or in between them

http://stackoverflow.com/comment/89736537
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51270236
type: Comment
has text: @jaime-ac Could you mark as answered or give me an upvote?

http://stackoverflow.com/comment/89549901
comment on: http://stackoverflow.com/a/51285146
type: AnswerComment
score: 0
type: Comment
has text: Great thanks! But, the only thing that embarrasses me: a while loop in the main process. Do we can to use something like subscribers? E.g.: when something appends to queue, then run function `on_queue_append()`?

http://stackoverflow.com/comment/89380047
has text: i meant it takes 10 mins until i can accept ur answer haha
type: AnswerComment
comment on: http://stackoverflow.com/a/51199062
score: 0
type: Comment

http://stackoverflow.com/q/51227723
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/89435668
has body: Here is a sample of my dataset (7 columns) : ID_CPTE PERIODID_MY CurrentTotalBalance CashBalance CreditLimit DelqCycle TRANSACTION_AMT 99690111 2015-05-01 8497.84 4293.12 16200 0 176.8 99690111 2014-11-01 866 0 12000 0 0 99690111 2015-06-01 10790.95 5224.44 16200 0 303 99690111 2015-10-01 12388.46 4786.08 16200 0 244.8 99690111 2015-11-01 12746.5 4818.48 16200 0 250 99690111 2015-08-01 10610.05 4753.35 16200 0 267.5 99690111 2015-09-01 11417.12 4616.46 16200 0 226.6 99690111 2014-12-01 1151.85 0 12000 0 0 99690111 2015-02-01 4045.67 1148.45 16200 0 303 99690111 2015-12-01 13119.6 4791.44 16200 0 273 99690111 2015-01-01 2298.96 350 12000 0 262.5 99690111 2015-03-01 5926.2 2567.25 16200 0 200 99690111 2015-04-01 6916.62 3307.33 16200 0 288.8 99690111 2015-07-01 10560 5127.54 16200 0 618 57427180 2011-12-01 219 0 2800 0 0 57427180 2012-01-01 233.58 236.08 2800 0 494.6 57427180 2012-02-01 234 0 2800 0 0 57427180 2012-03-01 809.12 0 2800 1 0 57427180 2012-04-01 1058.84 1.01 2800 2 1076.25 57427180 2012-05-01 260 0 2800 0 454.5 57427180 2012-06-01 210.08 0 2800 0 412 57427180 2012-07-01 416 0 2800 0 884 57427180 2012-08-01 243.41 0 2800 0 252.5 57427180 2012-09-01 410.88 0 2800 0 393.9 57427180 2012-10-01 489.72 0 2800 0 476.89 57427180 2012-11-01 689.52 20 2800 0 0 57427180 2012-12-01 266.06 0 2800 0 0 Here is what i want to produce using pandas (54 columns (1+13+13+1+13+13)) : ID_CPTE CurrentTotalBalance_month_[1-13] CashBalance_month_[1-13] CreditLimit DelqCycle_month_[1-13] TRANSACTION_AMT_month_[1-13] 99690111 .. .. CreditLimitAverage .. .. 57427180 .. .. CreditLimitAverage .. .. My goal is to group the data by ID_CPTE while still keeping the detail of each month from the original dataset. The tricky part is that the data can have 13 or 14 month history, so I would only like to capture the last 13 month and create new columns from it. I would also like the data to be ordered by date, so ..._month_1 would be the oldest record while ..._month_13 would be the most recen…
type: Question
tagged with: dataframe
score: 0
tagged with: transformation
tagged with: pandas
has title: Pandas Translating column data to new columns following date
has comment: http://stackoverflow.com/comment/89435631
tagged with: python-3.x
type: UnansweredQuestion

http://stackoverflow.com/q/51295280
has comment: http://stackoverflow.com/comment/89568296
possible better answer: http://stackoverflow.com/a/51295421
has body: I have a document that I opened using python: with open('my_file.txt', 'r') as fin: myfile = fin.readlines() Inside myfile I have lines like this: 1HEE JJ 1 3.904 5.512 1.259\n 2HEE CJJ 2 4.199 5.292 1.353\n 2LLO SJJ 3 4.367 5.234 1.445\n 3LLO JJ 4 4.041 4.969 1.220\n 6.50000 6.50000 6.50000\n This is some other title.\n 3\n 1GOO HSC 1 4.088 4.816 1.041\n 1DDD H 2 9.018 0.828 7.094\n 2DDD H 3 19.018 0.828 7.094\n The ONLY lines that I need to keep are these ones: 1HEE JJ 1 3.904 5.512 1.259\n 2HEE CJJ 2 4.199 5.292 1.353\n 2LLO SJJ 3 4.367 5.234 1.445\n 3LLO JJ 4 4.041 4.969 1.220\n 1GOO HSC 1 4.088 4.816 1.041\n 1DDD H 2 9.018 0.828 7.094\n 2DDD H 3 19.018 0.828 7.094\n In other words, the lines that have information from information in: myfile[line][:44] I MUST keep. The other lines (the shorter lines) I must DELETE. Any ideas on how to do this?
has comment: http://stackoverflow.com/comment/89568391
has comment: http://stackoverflow.com/comment/89568167
has answer: http://stackoverflow.com/a/51295421
accepted answer: http://stackoverflow.com/a/51295581
has comment: http://stackoverflow.com/comment/89568166
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89568360
tagged with: python
has comment: http://stackoverflow.com/comment/89568168
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89568138
score: 1
has answer: http://stackoverflow.com/a/51295581
upvote count: 1
has comment: http://stackoverflow.com/comment/89568382
type: Question
answer count: 2
has title: How to delete lines with different style in a file (everything is str format)?
downvote count: 0

http://stackoverflow.com/a/51197298
has body: An alternative approach is to take the logarithm of a with respect to the base b. If the result is a whole number, than b**x = a for some x from math import log def is_power(a, b): return log(a, b).is_integer()
score: 6
answers question: http://stackoverflow.com/q/51197241
downvote count: 0
type: Answer
upvote count: 6
has comment: http://stackoverflow.com/comment/89376739

http://stackoverflow.com/q/51225090
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89430769
has title: HTML source while webscraping seems inconsistent for website
has comment: http://stackoverflow.com/comment/89430677
answer count: 0
has comment: http://stackoverflow.com/comment/89430734
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/89430584
tagged with: python-3.x
score: 0
has comment: http://stackoverflow.com/comment/89430813
has body: I checked out say: https://www.calix.com/search-results.html?searchKeyword=C7 And if I inspect element on the first link I get this: C7 Learning Path I coded: import requests, bs4 res = requests.get('https://www.calix.com/search-results.html? searchKeyword=C7',headers={'User-Agent':'test'}) print(res) #res.raise_for_status() bs_obj= bs4.BeautifulSoup(res.text, "html.parser") elems=bs_obj.findAll('a',attrs={"class","title viewDoc"}) print(elems) And there was [] as output (empty list). So, I thought about actually looking through the "view-source" for the page. view-source:https://www.calix.com/search-results.html?searchKeyword=C7 If you search through the "view-source" you will not find the code for the "inspect element" I mentioned earlier. There is no "a class="title viewDoc"" in the view-source of the page. That is probably why my code isn't returning anything. The I went to www.nba.com, and inspected a link Cousins on Warriors' potential: 'Scary' in 5 hours The content of "inspect" for this link was in the "view-source" of the page. And, obviously my code was working for this page. I have seen a few examples of issue #1. Just curious why the difference in html formats, or am I missing something?
has comment: http://stackoverflow.com/comment/89430563
has comment: http://stackoverflow.com/comment/89430706
has comment: http://stackoverflow.com/comment/89430647
has comment: http://stackoverflow.com/comment/89430755

http://stackoverflow.com/a/51281320
answers question: http://stackoverflow.com/q/51280830
has comment: http://stackoverflow.com/comment/89542625
has comment: http://stackoverflow.com/comment/89542570
score: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/89540315
has comment: http://stackoverflow.com/comment/89541003
has body: As I mentioned in the comment, you need to cl.exe folder. You can do it through Visual Studio installer. Install the following C++ compilers:
type: Answer
upvote count: 1

http://stackoverflow.com/q/51246518
tagged with: python
has body: I have a very basic Python program which alarms you at certain intervals for break...I want to make it a software so that I don't need to run that program everytime I open my computer ...and I want it for both windows and Linux....And is there universal way to create executable files from source code in any language
has comment: http://stackoverflow.com/comment/89471737
type: Question
has answer: http://stackoverflow.com/a/51249314
tagged with: programming-languages
has title: How can I make a Python program executable so that it automatically runs
answer count: 1
has comment: http://stackoverflow.com/comment/89472296
type: UnansweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/89474939

http://stackoverflow.com/comment/89470174
comment on: http://stackoverflow.com/q/51245686
type: Comment
has text: Joao Vitorino please bear with the code identation
score: 0
type: QuestionComment

http://stackoverflow.com/a/51173832
type: Answer
score: 2
upvote count: 3
downvote count: 1
has body: You need to create a Keras Model, then you can load your architecture and afterwards the model weights See the code below, model = keras.models.Sequential() # create a Keras Model model.load_weights('my_model_weights.h5') # load model weights More information in the Keras docs
answers question: http://stackoverflow.com/q/51173580
has comment: http://stackoverflow.com/comment/89331246

http://stackoverflow.com/a/51223618
answers question: http://stackoverflow.com/q/51221827
has body: if you are using jupyter notebook, please write %matplotlib inline
score: 0
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/51221827

task
type: Tag
tag name: task
tags question: http://stackoverflow.com/q/51299464

http://stackoverflow.com/comment/89491838
type: Comment
comment on: http://stackoverflow.com/a/51256425
score: 0
type: AnswerComment
has text: Try now. You're likely getting a `403: FORBIDDEN` error if your bot does not have the necessary permissions to ban/message people.

http://stackoverflow.com/q/51295101
favorite count: 0
has comment: http://stackoverflow.com/comment/89567843
has answer: http://stackoverflow.com/a/51295223
has body: Im making an python application to calculate percentages and I wanted to know how I can add an "0." in front of a variable to multiply it by the "percentOf" variable (would output the answer, but doesn't). I've tried this: import sys percent = input("Enter percent:") ofNumber = input("Enter number:") percent2 = percent++0. answer = percent2 * ofNumber print(answer) but it won't work :(
type: UnansweredQuestion
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/51295188
downvote count: 3
type: Question
has comment: http://stackoverflow.com/comment/89567854
score: -2
has comment: http://stackoverflow.com/comment/89567778
has title: How can I add a 0. before an variable in python
has comment: http://stackoverflow.com/comment/89567753
answer count: 2
has comment: http://stackoverflow.com/comment/89567761

http://stackoverflow.com/q/51228936
has comment: http://stackoverflow.com/comment/89437625
has comment: http://stackoverflow.com/comment/89494861
favorite count: 0
accepted answer: http://stackoverflow.com/a/51272650
tagged with: python
has comment: http://stackoverflow.com/comment/89447283
score: 1
upvote count: 1
type: AnsweredQuestion
tagged with: http://stackoverflow.com/tag/json
has answer: http://stackoverflow.com/a/51272650
has comment: http://stackoverflow.com/comment/89466474
has comment: http://stackoverflow.com/comment/89456853
has comment: http://stackoverflow.com/comment/89446849
has title: Turn several "Response" objects represented as nested dicts into multi dimensional list in python
type: Question
has comment: http://stackoverflow.com/comment/89437664
answer count: 1
downvote count: 0
has body: EDIT : I cannot seem to figure out how to iterate through this object correctly. I believe I am indexing things incorrectly as the error states that blank text does not match the format for datetime conversion I have. Below is the beginning of one of the response objects, it is long so I opted not to include the entire thing. There are no irregularities at any point, however, and continues to follow the initiated pattern. Please help me understand how to gain access to, and iterate through only the dates and there proceeding information. {u'Meta Data': {u'1. Information': u'Daily Prices (open, high, low, close) and Volumes', u'2. Symbol': u'MSFT', u'3. Last Refreshed': u'2018-07-06', u'4. Output Size': u'Compact', u'5. Time Zone': u'US/Eastern'}, u'Time Series (Daily)': {u'2018-02-13': {u'1. open': u'88.9300', u'2. high': u'90.0000', u'3. low': u'87.8000', u'4. close': u'89.8300', u'5. volume': u'26200053'}, u'2018-02-14': {u'1. open': u'88.5100', u'2. high': u'90.9900', u'3. low': u'88.4100', u'4. close': u'90.8100', u'5. volume': u'34314101'}, u'2018-02-15': {u'1. open': u'91.2100', u'2. high': u'92.7200', u'3. low': u'90.6200', u'4. close': u'92.6600', u'5. volume': u'27407914'}, I recieve this error indicating that I am parsing through the dict incorrectly, I have tried many things and I can't seem to get it. I believe this is the last hump to get this program running. (finally) ValueError: time data '' does not match format '%Y-%b-%d' And now my attempted UPDATED code import requests import json # Global Variables url = "https://www.alphavantage.co/query" function_type = "TIME_SERIES_DAILY" api_key = "***********" current_zero_time = "" main_list = [] symbols = ["AAPL", "HPQ", "IBM", "AMZN", "MSFT", "GOOGL", "INTC", "CSCO", "ORCL", "OCOM"] def get_data(symbol): global api_key global function_type request_data = {"function": function_type, "symbol": symbol, "apikey": api_key} data_dict = requests.get(url, params=request_data) return data_dict def date_dif(date0,…
tagged with: python-2.x

http://stackoverflow.com/comment/89638225
has text: Hmm, odd... if you try the sample code exactly as written, does the code generate the lines of text? This is a very large file and processing all the data can take a considerable amount of time, but it started printing results immediately for me.
type: AnswerComment
comment on: http://stackoverflow.com/a/51305721
type: Comment
score: 0

http://stackoverflow.com/comment/89526174
type: Comment
type: QuestionComment
score: 0
has text: I figured out the easy solution - rather than setting ticks manually, I changed the locator from the default (whatever that is for this case) to the ticker.LogLocator(), and that gave me reasonable ticks for the colorbar. I have no idea why the default locator decides to barf ticks all over the colorbar, but the new locator does the trick nicely.
comment on: http://stackoverflow.com/q/51272271

http://stackoverflow.com/q/51209749
tagged with: slice
downvote count: 1
type: Question
upvote count: 4
has answer: http://stackoverflow.com/a/55200461
has answer: http://stackoverflow.com/a/51213820
has answer: http://stackoverflow.com/a/51210193
linked to: http://stackoverflow.com/q/509211
accepted answer: http://stackoverflow.com/a/55200461
has answer: http://stackoverflow.com/a/51210577
favorite count: 0
has body: I'm looking for a general method on how to reverse a slice in Python. I read this comprehensive post, which has several nice explanations about how slicing works: Understanding Python&#39;s slice notation Yet I cannot figure out a generalized rule on how to calculate a reversed slice which addresses exactly the same elements in reverse order. I was actually surprised not to find a builtin method doing this. What I'm looking for is a method reversed_slice that works like this with arbitrary start, stop and step values including negative values: &gt;&gt;&gt; import numpy as np &gt;&gt;&gt; a = np.arange(30) &gt;&gt;&gt; s = np.s_[10:20:2] &gt;&gt;&gt; a[s] array([10, 12, 14, 16, 18]) &gt;&gt;&gt; a[reversed_slice(s,len(a))] array([18, 16, 14, 12, 10]) What I've tried but doesn't work is this: def reversed_slice(slice_, len_): """ Reverses a slice (selection in array of length len_), addressing the same elements in reverse order. """ assert isinstance(slice_, slice) instart, instop, instep = slice_.indices(len_) if instep &gt; 0: start, stop, step = instop - 1, instart - 1, -instep else: start, stop, step = instop + 1, instart + 1, -instep return slice(start, stop, step) This works fine for step of 1 and when the last addressed element coincides with stop-1. For other cases it does not: &gt;&gt;&gt; import numpy as np &gt;&gt;&gt; a = np.arange(30) &gt;&gt;&gt; s = np.s_[10:20:2] &gt;&gt;&gt; a[s] array([10, 12, 14, 16, 18]) &gt;&gt;&gt; a[reversed_slice(s,len(a))] array([19, 17, 15, 13, 11]) So it seems like I'm missing some relation like (stop - start) % step. Any help on how to write a general method is greatly appreciated. Notes: I do know that there a other possibilities to get a sequence with the same elements reversed, like calling reversed(a[s]). This is not an option here, as I need to reverse the slice itself. The reason is that I work on h5py datasets which do not allow negative step values in slices. An easy but not very elegant way would be the use of coor…
possible better answer: http://stackoverflow.com/a/51209862
answer count: 5
has title: Reversing an arbitrary slice in Python
has answer: http://stackoverflow.com/a/51209862
tagged with: python
type: AnsweredQuestion
tagged with: numpy-slicing
score: 3

dicom
tag name: dicom
type: Tag
tags question: http://stackoverflow.com/q/51313347

http://stackoverflow.com/a/51278197
score: 2
has body: This is a nice tutorial on texture extraction using gabor filter with scikit-image: http://scikit-image.org/docs/0.11.x/auto_examples/plot_gabor.html. You may want to have a look at it. You may want to use deep learning / transfer learning (depending on how much data you have) to extract the features automatically instead of hand-crafted features.
upvote count: 2
has comment: http://stackoverflow.com/comment/89583953
has comment: http://stackoverflow.com/comment/89549284
has comment: http://stackoverflow.com/comment/89538280
has comment: http://stackoverflow.com/comment/89536079
answers question: http://stackoverflow.com/q/51277949
downvote count: 0
has comment: http://stackoverflow.com/comment/89534334
type: Answer
has comment: http://stackoverflow.com/comment/89536550

http://stackoverflow.com/a/51201537
type: Answer
has body: Thanks to @DrawT for this answer: https://stackoverflow.com/a/35920186/6108107 path = path.replace('\\','/') # replaces backslashes with forward slashes path = path[1:len(path)-1] # to remove quote marks replaces the backslashes with forward slashes which are still recognised as a filedpath but don't need escaping, then cleans the quotes. pandas will then accept that file path variable as the location of a excel file or csv.
answers question: http://stackoverflow.com/q/51184260
score: 0
accepted answer of: http://stackoverflow.com/q/51184260
type: AcceptedAnswer

http://stackoverflow.com/q/51225794
has answer: http://stackoverflow.com/a/53189811
answer count: 1
tagged with: scikit-learn
favorite count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: python
has body: After doing clustering I end up with an object which stores all the cluster labels, something like this: clusterer.labels_ The above is typically a list or an array. Then I always assign the labels to the original pandas dataframe (dataset) like this: df['cluster_lables] = cluster.labels_ At the end I assume that each element of cluster.labels_ corresponds to each row to my original dataset, is that assumption correct? For example from the above column creation I end up with something like this: ColA ColB cluster_labels 1 3 -1 2 4 2 ... 89 90 45
score: 1
type: Question
has title: How to know to which matrix row corresponds each cluster label?
downvote count: 0
tagged with: hdbscan
tagged with: pandas

http://stackoverflow.com/comment/89436940
type: Comment
comment on: http://stackoverflow.com/a/51228516
has text: As you said, the kst column is already sorted in ascending order. But I'd like to sort kst column in descending orde NOT ascending order. Your suggested code doesn't woks. It means kst colume is still ascending order.
score: 0
type: AnswerComment

http://stackoverflow.com/q/51228063
possible better answer: http://stackoverflow.com/a/51228088
has title: How to instantiate a list of classes using for loop?
has answer: http://stackoverflow.com/a/51228088
accepted answer: http://stackoverflow.com/a/51228092
tagged with: python-3.x
has body: How can I instantiate objects from a list of different classes, each defined in a different module? Something like: a.py: class a(): def __init__(): print('a called') b.py: class b(): def __init__(): print('b called') main.py import a import b classes = ['a', 'b'] for class in classes: class = class()
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51247692
type: Question
has answer: http://stackoverflow.com/a/51228092
tagged with: class
score: 0
answer count: 3

http://stackoverflow.com/q/51268579
score: 0
has answer: http://stackoverflow.com/a/53521931
has title: Error in Compiling the CPU Module for Python
tagged with: tensorflow
type: Question
answer count: 1
has comment: http://stackoverflow.com/comment/89516125
linked to: http://stackoverflow.com/q/44080677
has comment: http://stackoverflow.com/comment/89515703
tagged with: c++
has body: System information Have I written custom code: No OS Platform and Distribution: Windows 10 64bit TensorFlow installed from: Latest master source TensorFlow version: commit dfcec82 Python version: 3.6.5 CMake version: 3.12.0-rc2 MS C+_+ Compiler version: 19.00.24234.1 CPU model and memory: i5-4460 with 16GB of RAM Exact command to reproduce: Opening Developer Command Line as admin Choosing the 64bit compiler "C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\Common7\Tools\vsdevcmd\ext\vcvars.bat" amd64 cd D:\opencv\tensorflow\tensorflow\contrib\cmake\build 4. cmake .. -A x64 -T host=x64 -DCMAKE_BUILD_TYPE=Release -DSWIG_EXECUTABLE=D:/opencv/swigwin-3.0.12/swig.exe -DPYTHON_EXECUTABLE="C:/Users/FiFo/AppData/Local/Programs/Python/Python36/python.exe" -DPYTHON_LIBRARIES="C:/Users/FiFo/AppData/Local/Programs/Python/Python36/libs/python36.lib" -Dtensorflow_WIN_CPU_SIMD_OPTIONS=/arch:AVX2 -Dtensorflow_BUILD_CC_TESTS=OFF -Dtensorflow_BUILD_PYTHON_TESTS=OFF -Dtensorflow_BUILD_MORE_PYTHON_TESTS=OFF -Dtensorflow_BUILD_CC_EXAMPLE=ON -Dtensorflow_BUILD_PYTHON_BINDINGS=ON -Dtensorflow_BUILD_CC_TESTS=OFF -Dtensorflow_OPTIMIZE_FOR_NATIVE_ARCH=ON -Dtensorflow_ENABLE_MKL_SUPPORT=ON -Dtensorflow_ENABLE_MKLDNN_SUPPORT=ON -Dtensorflow_VERBOSE=ON -Dtensorflow_BUILD_SHARED_LIB=ON MSBuild /p:Configuration=Release ALL_BUILD.vcxproj SUCCESS MSBuild /p:Configuration=Release INSTALL.vcxproj SUCCESS MSBuild /p:Configuration=Release tf_python_build_pip_package.vcxproj Fails with: Generating init.py files for Python API. Traceback (most recent call last): File "D:\opencv\tensorflow\tensorflow\contrib\cmake\build\tf_python\tensorflow\python\pywrap_tensorflow_internal.py", line 14, in swig_import_helper return importlib.import_module(mname) File "C:\Users\FiFo\AppData\Local\Programs\Python\Python36\lib\importlib_init_.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 994, in _gcd_import File "", line 971, in _find_and_load File ""…
type: UnansweredQuestion
tagged with: python
tagged with: cmake
has comment: http://stackoverflow.com/comment/89517574

http://stackoverflow.com/comment/90030132
type: AnswerComment
has text: Hmmm, I am not sure whether docker need to setup firewalls on host machine. I remember that docker will create an bridge adapter for connections. But I did not dig into it to see if it need firewall setting. Besides, "docker start" need "-p 5555:5555" argument to map container port to host port.
type: Comment
comment on: http://stackoverflow.com/a/51473092
score: 0

http://stackoverflow.com/comment/89621070
has text: Works perfectly fine on my machine. It must be some kind of setup that you have on your Excel.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51321694

http://stackoverflow.com/a/51269426
answers question: http://stackoverflow.com/q/51263783
type: Answer
downvote count: 0
score: 1
has body: This has an easy part and an NP part. Here's the solution to the easy part. Let's assume you have the full correlation matrix: &gt;&gt;&gt; c = a + a.T &gt;&gt;&gt; c array([[0. , 0.96078379, 0.05498203, 0.46005028, 0.1030161 ], [0.96078379, 0. , 0.0552454 , 0.45468466, 0.10350956], [0.05498203, 0.0552454 , 0. , 0.11167813, 0.00109096], [0.46005028, 0.45468466, 0.11167813, 0. , 0.00928037], [0.1030161 , 0.10350956, 0.00109096, 0.00928037, 0. ]]) What you're doing is converting this into an adjacency matrix: &gt;&gt;&gt; adj = (a &gt;= .11) &amp; (a &lt;= .99) &gt;&gt;&gt; adj.astype(int) # for readability below - False and True take a lot of space array([[0, 1, 0, 1, 0], [1, 0, 0, 1, 0], [0, 0, 0, 1, 0], [1, 1, 1, 0, 0], [0, 0, 0, 0, 0]]) This now represents a graph where columns and rows corresponds to nodes, and a 1 is a line between them. We can use networkx to visualize this: import networkx g = networkx.from_numpy_matrix(adj) networkx.draw(g) You're looking for maximal fully-connected subgraphs, or "cliques", within this graph. This is the Clique problem, and is the NP part. Thankfully, networkx can solve that too: &gt;&gt;&gt; list(networkx.find_cliques(g)) [[3, 0, 1], [3, 2], [4]] Here [3, 0, 1] is one of your triplets.
accepted answer of: http://stackoverflow.com/q/51263783
upvote count: 1
type: AcceptedAnswer

http://stackoverflow.com/a/51179269
answers question: http://stackoverflow.com/q/51179236
downvote count: 1
upvote count: 37
has body: Array.prototype.find() returns the first matching element in an array, given a predicate function, or undefined when there is no match. Python has the filter() function, which filters an iterable on a predicate, and next(), which produces the first element of an iterable or an optional default. Combining these give you the equivalent: next(filter(pred, iter), None) where pred is a callable that returns True when an element matches the search criteria. Demo: &gt;&gt;&gt; iterable = [42, 81, 117] &gt;&gt;&gt; parity_odd = lambda v: v % 2 == 1 &gt;&gt;&gt; next(filter(parity_odd, iterable), None) 81 &gt;&gt;&gt; iterable = [42, 2, 4] &gt;&gt;&gt; next(filter(parity_odd, iterable), None) is None True If you remove the second argument to next(), a StopIteration exception is raised when there is no matching element.
score: 36
type: Answer

http://stackoverflow.com/q/51310604
has body: Code looks something like this: import multiprocessing as mp from functools import partial import boto3 import numpy as np s3 = boto3.client('s3') def _something(**kwargs): # Some mixed integer programming stuff related to the variable archive return np.array(some_variable_related_to_archive) def do(s3): archive = np.load(s3.get_object('some_key')) # Simplified -- details not relevant pool = mp.pool() sub_process = partial(_something, slack=0.1) parts = np.array_split(archive, some_int) target_parts = np.array(things) out = pool.starmap(sub_process, [x for x in zip(parts, target_parts)] # Error occurs at this line pool.close() pool.join() do(s3) The error: _pickle.PicklingError: Can't pickle &lt;class 'botocore.client.S3'&gt;: attribute lookup S3 on botocore.client failed I have very limited experience with the Python multiprocessing library. I'm not sure why, when the S3 client is not a parameter in any of the functions, it throws the above error. Note that the code is able to run okay if the archive file is loaded from disk, and not from S3. Any help/guidance would be greatly appreciated.
has answer: http://stackoverflow.com/a/51381489
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/1816958
type: Question
tagged with: python-multiprocessing
upvote count: 12
accepted answer: http://stackoverflow.com/a/51381489
tagged with: boto3
score: 12
answer count: 2
has title: How to use boto3 client with Python multiprocessing?
tagged with: starmap
downvote count: 0
has comment: http://stackoverflow.com/comment/92090502
favorite count: 0
possible better answer: http://stackoverflow.com/a/52630957
has answer: http://stackoverflow.com/a/52630957
tagged with: python

http://stackoverflow.com/comment/89451658
type: Comment
has text: Thank you very much!! I had like 30 tabs open on how to do this. I ran it without the combine and it worked! df1['Test'] = pd.to_datetime(df1['Date'], format="%y/%d/%m %H:%M:%S", errors='coerce')
comment on: http://stackoverflow.com/a/51235866
type: AnswerComment
score: 0

http://stackoverflow.com/q/51310778
has comment: http://stackoverflow.com/comment/89631320
type: UnansweredQuestion
tagged with: python
answer count: 0
downvote count: 0
score: 1
type: Question
has title: GCS: SignatureDoesNotMatch Error when I try to do a PUT request to a signed URL using POSTMAN
has comment: http://stackoverflow.com/comment/89630644
has body: I have been searching for a solution for a while now, however I have been unable to find anything to solve my issue. I am a bit new to using signed URLs so forgive me if I am missing something obvious. I am attempting to upload .tif/.tiff files to a GCS Bucket and am able to successfully sign the URL with the following code: def _Base64Sign(self, plaintext): """Signs and returns a base64-encoded SHA256 digest.""" shahash = SHA256.new(plaintext) signer = PKCS1_v1_5.new(self.key) signature_bytes = signer.sign(shahash) return base64.b64encode(signature_bytes) def _MakeSignatureString(self, verb, path, content_md5, content_type): """Creates the signature string for signing according to GCS docs.""" signature_string = ('{verb}\n' '{content_md5}\n' '{content_type}\n' '{expiration}\n' '{resource}') return signature_string.format(verb=verb, content_md5=content_md5, content_type=content_type, expiration=self.expiration, resource=path) def _MakeUrl(self, verb, path, content_type='', content_md5=''): """Forms and returns the full signed URL to access GCS.""" newpath = "/" + path base_url = '%s%s' % (self.gcs_api_endpoint, newpath) signature_string = self._MakeSignatureString(verb, newpath, content_md5, content_type) logging.info("1. " + signature_string) signature_signed = self._Base64Sign(signature_string) logging.info("2. " + signature_signed) query_params = {'GoogleAccessId': self.client_id_email, 'Expires': str(self.expiration), 'Signature': signature_signed} return base_url, query_params def Get_Signed_Url(self, fileName, md5): """Performs a POST request Args: filename: The file to upload. md5: the md5 hash Returns: A signed url to upload a file. """ base_url, query_params = self._MakeUrl('PUT', fileName, 'image/tiff', md5) url_formatted_sig = urllib.urlencode(query_params) signed_url = "{}?{}".format(base_url,url_formatted_sig) return signed_url The headers I use to sign are verb, Content-MD5, Content-Type, expiration, and resource. After receiving the signed URL, I use …
tagged with: google-cloud-storage
upvote count: 1
tagged with: postman
has comment: http://stackoverflow.com/comment/89625856
favorite count: 0
tagged with: pre-signed-url

http://stackoverflow.com/comment/89322602
type: Comment
type: QuestionComment
has text: `obj["first"][0]["second"].pop("third")` should work
score: 1
comment on: http://stackoverflow.com/q/51169932

http://stackoverflow.com/a/51296875
upvote count: 0
score: -2
answers question: http://stackoverflow.com/q/51296770
downvote count: 2
type: Answer
has comment: http://stackoverflow.com/comment/89571408
has body: Try this: sudo apt-get remove python-pip python-dev This will remove the pip and Python. Then install the required version of Python and pip.

http://stackoverflow.com/comment/89549179
type: Comment
has text: This being said, dynamically modifying globals is usually a bad idea. It's hard to tell which variables are defined from looking at the code (plus if you use an IDE it will be very sad).
score: 0
comment on: http://stackoverflow.com/a/51285864
type: AnswerComment

http://stackoverflow.com/comment/89549542
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51285762
type: AnswerComment
has text: I know that I make it by Django ORM, but I'd like to searching by Django Admin search box defined by search_fields. By default, by searching this field, milliseconds are also included.

binary
tags question: http://stackoverflow.com/q/51256151
tags question: http://stackoverflow.com/q/51231608
tags question: http://stackoverflow.com/q/51200077
tag name: binary
type: Tag
tags question: http://stackoverflow.com/q/51263691

http://stackoverflow.com/comment/89514785
has text: The error is pretty self-explanatory. You can't convert `raouf` to an integer. Did you define one of your models incorrectly?
comment on: http://stackoverflow.com/q/51268192
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/51232534
has comment: http://stackoverflow.com/comment/89445292
has title: Python flask RESTful: Directory structure
score: -2
tagged with: flask
has answer: http://stackoverflow.com/a/51232724
has body: I am fairly new to python and flask, I have created an authentication stystem, A JWT token based authentication. Currently my directory structure is : Note : If possible, Please answer in detail. -Project -- venv (folder) -- models.py -- resources.py -- run.py -- views.py As the names are self explanatory, models.py have a class which named UserModel, In resources,py there are many classes like UserRegistration, UserLogin, UserLogoutAccess, UserLogoutRefresh, TokenRefresh, AllUsers. run.py have the server related and app initialization code, And also the endpoints resource are defined here like : api.add_resource(resources.UserRegistration, '/registration') I know its messy, But also i have no idea about the python Flask conventions, Should each class have its own file, Should the authentication code be placed in one directory, As the project will obviously grow. I am thinking about the following directory structure : -Project -- venv -- Authentication -- login.py -- registration.py -- logout.py -- userLogoutRefresh.py .... .... -- Models -- UserModel.py .... .... -- run.py Looking for suggestions.
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python
downvote count: 3
tagged with: flask-restful
upvote count: 1
type: Question

http://stackoverflow.com/comment/89320369
has text: He should try by himself actually.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/51168761
score: 4

http://stackoverflow.com/q/51211191
upvote count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python
has body: I have a table in hive which i am using to create a dataframe. The column of the table are : [mer_name,year,month,sum_qty,sum_ln,sum_orders] I want to plot a graph which will have sum_orders of all mer_name month wise. something like this: https://assets.digitalocean.com/articles/eng_python/pandas/name_plot-m-list.png I tried with matplotlib but i am not able to plot. code : dataDF=sqlContext.sql("select * from db.testtable where year = 2015") pdDF = dataDF.toPandas() ax=pdDF.plot(x=['mer_name','month'], y='sum_orders', rot=45) fig = ax.get_figure() fig.savefig('demo.pdf') Also tried by making pivot table but it didn't work for me. code: df=pd.pivot_table(pdDF,index= ["mer_name","year","month"],values= ["sum_orders"]) ax=df.plot(rot=45) fig = ax.get_figure() fig.savefig('pivot') please help. thanks in advance
has title: How to use matplotlib to plot pyspark sql results for each row?
answer count: 0
downvote count: 0
score: 1
tagged with: matplotlib
type: Question
tagged with: pyspark
tagged with: python-2.7
tagged with: pandas

http://stackoverflow.com/q/51256968
has comment: http://stackoverflow.com/comment/89492586
has body: I got the following recursive function to compute the longest path of a binary tree. I'm new to recursive function, can someone help walk through how does this function derive the result = 4 with the given example? class Solution: def maxDepth(self, root): """ :type root: TreeNode :rtype: int """ if root is None: return 0 else: lDepth = self.maxDepth(root.left) rDepth = self.maxDepth(root.right) if lDepth &gt; rDepth: return lDepth+1 else: return rDepth+1
possible better answer: http://stackoverflow.com/a/51257055
has answer: http://stackoverflow.com/a/51257055
downvote count: 1
type: Question
tagged with: recursion
has comment: http://stackoverflow.com/comment/89492729
score: -1
has answer: http://stackoverflow.com/a/51257053
has title: To understand this recursive function
accepted answer: http://stackoverflow.com/a/51257056
has comment: http://stackoverflow.com/comment/89492645
answer count: 3
upvote count: 0
favorite count: 0
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89492632
has answer: http://stackoverflow.com/a/51257056

http://stackoverflow.com/comment/89510176
type: QuestionComment
comment on: http://stackoverflow.com/q/51264897
score: 0
has text: what if a file got deleted in source directory? Should that be reflected in destination directory?
type: Comment

http://stackoverflow.com/comment/89519784
has text: I ran your tests for your sample project and it worked.
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51270719

http://stackoverflow.com/comment/89373200
comment on: http://stackoverflow.com/q/51195525
has text: 1. How many times do you see `Successful Connection to...`? Do you see a message for each entry in `ipaddressrouter.txt` or only the last one too? 2. You open the file `out.txt` multiple times but never close it. Try `with open('out.txt', 'a') as out:` 3. You open the file `ipaddressrouter.txt` twice and use only one (and also never close it).
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/a/51281426
score: 1
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/51272304
downvote count: 0
has body: Python's native matplotlib can of course create this kind of graph. It is just a categorical scatter plot with variable markersizes. Using your toy data set: import numpy as np import matplotlib.pyplot as plt import pandas as pd #create markersize column from values to better see the difference #you probably want to edit this function depending on min, max, and range of values df["markersize"] = np.square(df.Count) + 10 fig = plt.figure() #plot categorical scatter plot plt.scatter(df.Var1, df.Var2, s = df.markersize, edgecolors = "red", c = "white", zorder = 2) #plot grid behind markers plt.grid(ls = "--", zorder = 1) #take care of long labels fig.autofmt_xdate() plt.tight_layout() plt.show() Output: Regarding the definition of your markersize function for the scatter plot, you might want to read this answer.

http://stackoverflow.com/comment/89420083
type: Comment
comment on: http://stackoverflow.com/a/51219151
score: 0
type: AnswerComment
has text: Yes, this works now. What exactly did I change? I am creating static objects out of filename strings? Why does this work now?

http://stackoverflow.com/comment/89490552
comment on: http://stackoverflow.com/q/51255286
type: Comment
type: QuestionComment
has text: @MrName 'doc' and `time.time()` are more like an example, I'll manage it my way but what is DRF ViewSets solution? If I could upload file anyhow (safely, without being damaged) then I could simply change Model fields using returned id
score: 0

http://stackoverflow.com/comment/89568043
has text: If `null` is acceptable, why not add a new `fk` field instead of modifying the existing one?
score: 0
type: Comment
comment on: http://stackoverflow.com/q/51294765
type: QuestionComment

http://stackoverflow.com/a/51172333
score: 2
has body: You have to add the contact dictionary inside the for loop. import re import json results = [] source = open('zen_id.txt') output = open('zen_id_js.json', 'w') for line in source: contact = { "id": "", "email": "" } email = re.search(r'[\w\.-]+@[\w\.-]+', line) contact['email'] = email.group(0) p = re.search(r'\d\d\d\d\d', line) contact['id'] = p.group(0) results.append(contact) json.dump(results, output)
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/51172081
upvote count: 2

http://stackoverflow.com/q/51308998
has answer: http://stackoverflow.com/a/51309172
accepted answer: http://stackoverflow.com/a/51309172
type: AnsweredQuestion
has title: Python,ConfigParser-Referencing in earlier directory
type: Question
has body: In my downloads folder, I have a folder called bin. Within the folder bin I have a file called config_template.ini, and another folder called SN. Within the folder SN I have a file called sample.py. In sample.py I use: config = configparser.ConfigParser() config.read('config_template.ini') Since 'config_template.ini' is not in the same folder, how would I reference it? This is the file address of sample.py: C:\Users\user1\Downloads\bin\SN\sample.py This is the file address of the config_template file. C:\Users\user1\Downloads\bin\config_template.ini Any help would be appreciated!
tagged with: configparser
score: 0
answer count: 1
tagged with: python

http://stackoverflow.com/q/51232477
tagged with: pygame
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89444951
tagged with: python
has comment: http://stackoverflow.com/comment/89444932
accepted answer: http://stackoverflow.com/a/51233008
tagged with: audio
type: AnsweredQuestion
score: 0
has title: How to store sounds in Python?
type: Question
answer count: 1
tagged with: pyaudio
has answer: http://stackoverflow.com/a/51233008
has body: I'm trying to make a beat pad. I've programmed this in such a way that a kick plays with the press of a and snare at the press of s. If I make a basic beat by pressing a-s-a-s, is there any way for me to save the sound being made? import pygame pygame.init() screen = pygame.display.set_mode((800,800)) while True: screen.fill((255,255,255)) for event in pygame.event.get(): if event.type == pygame.KEYDOWN: if event.key == pygame.K_a: pygame.mixer.music.load('Kick1.mp3') pygame.mixer.music.play() if event.key == pygame.K_s: pygame.mixer.music.load('Snare1.mp3') pygame.mixer.music.play() if event.key == pygame.K_w: pygame.quit() quit() pygame.display.update() pygame.display.set_caption('Beat pad')

http://stackoverflow.com/comment/89432317
type: QuestionComment
has text: Make sure the image has 3 or 4 channels. To get the image dimensions , do `print(img.shape)`. The result will be in the form of (height,width,channels).
comment on: http://stackoverflow.com/q/51225657
score: 0
type: Comment

http://stackoverflow.com/a/51311937
type: Answer
has body: Instead of using nine row variables, you could use one 2D array called "grid". var grid = [[5,3,0,0,7,0,0,0,0], [6,0,0,1,9,5,0,0,0], [0,9,8,0,0,0,0,6,0], [8,0,0,0,6,0,0,0,3], [4,0,0,8,0,3,0,0,1], [7,0,0,0,2,0,0,0,6], [0,6,0,0,0,0,2,8,0], [0,0,0,4,1,9,0,0,5], [0,0,0,0,8,0,0,7,9]] That way, copying the grid could be done in one line.
has comment: http://stackoverflow.com/comment/89600751
accepted answer of: http://stackoverflow.com/q/51311809
answers question: http://stackoverflow.com/q/51311809
upvote count: 4
has comment: http://stackoverflow.com/comment/89600969
downvote count: 0
score: 4
type: AcceptedAnswer

http://stackoverflow.com/comment/89591984
type: Comment
has text: Your example code fails to pass mypy checks. The function implementation and calls were not at fault, the *type hint declarations were*. It didn't matter that the keys were missing (that was not the issue in the question). (Your code *still* produces `Incompatible return value type (got "Tuple[Union[str, int], Union[str, int]]", expected "Tuple[int, int]")`, *and* it adds `Dict entry 0 has incompatible type "str": "List[int]"; expected "str": "Union[str, int]"` and `Dict entry 1 has incompatible type "str": "List[int]"; expected "str": "Union[str, int]"`, because you are using lists).
comment on: http://stackoverflow.com/a/51304082
score: 0
type: AnswerComment

http://stackoverflow.com/comment/89558718
score: 0
has text: All i need is to plot the date/time on the x axis and then the turbdiity on the y. Also how to i take the datafram for volts and convert it to turbidity with the equation i gave.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51290182

http://stackoverflow.com/a/66114105
score: 0
answers question: http://stackoverflow.com/q/51284583
type: Answer
has body: You can use IsAdminUser permission by rest framework from rest_framework import permissions class AdminView(generic.ListView): permission_classes = (permissions.IsAdminUser, ) ...

http://stackoverflow.com/comment/89522831
type: Comment
type: QuestionComment
has text: Just what do you mean by "point" and "vector" in python? There is no standard meaning for those--there are multiple implementations. Please show example input, expected output, and some of your own attempts at a solution.
comment on: http://stackoverflow.com/q/51272288
score: 0

http://stackoverflow.com/comment/89510024
type: AnswerComment
has text: Thanks for the answer. I still cannot understand why the results differ. In my understanding, the algorithm does calculate the `n_init` times the centroids and returns the best one. If multiple jobs are wanted, this step is calculated in parallel (stated in the documentation of kmeans). Does this mean the `n_init=10` are calulated in a split way, meaning 2 cores do 5 calculations each or in a "multiplicative" way, meaning 2 cores each do 10 calculations? In both cases I do not understand why the results should differ. Plus why multiple jobs are faster if they do not split the task
type: Comment
score: 0
comment on: http://stackoverflow.com/a/51265006

http://stackoverflow.com/comment/89636081
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51314050
has text: Oh, I see now... I assumed userinput was a single character, not an entire row. But your solution does match to what the OP had.

http://stackoverflow.com/q/51233314
has answer: http://stackoverflow.com/a/51233479
score: 0
answer count: 1
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89445814
has body: I'm trying to find the most efficient way to handle determinants close to 0. Is there a way to do this without using if-else statements? The code is below. import numpy as np array = np.arange(16) array = array.reshape(4, -1) determinant = np.linalg.det(array) print("Determinant is %s" % determinant) print("Determinant is %d" % determinant) print("Determinant is %f" % determinant)
has title: Handle small determinants in python
has comment: http://stackoverflow.com/comment/89445757
type: Question

http://stackoverflow.com/q/51233506
score: 1
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/89446074
has title: VPython fractal: Can't create an array of shapes
tagged with: vpython
has comment: http://stackoverflow.com/comment/89446090
tagged with: fractals
has answer: http://stackoverflow.com/a/51233542
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python
has body: I'm trying to create a menger sponge using VPython. I built the base piece with no problem (image below) and I'm trying to create an array filled with the base piece in the same configuration. However, I can't get it to work. The display doesn't change and still shows just one base piece. Here is the code: from vpython import * l,w,h = 1,1,1 cubes = [] def basePiece(): L = 1 for i in range(-L,L+1): for j in range(-L,L+1): for k in range(-L,L+1): sum = abs(i) + abs(j) + abs(k) if sum &gt; 1: cube=box(color=vector(1,1,1), opacity=0.9, pos=vector(i,j,k), length=l, height=h, width=w) cubes.append(cube) return cubes fract = [] L = 1 for x in range(L,L+1): for y in range(L,L+1): for z in range(L,L+1): sum = abs(x) + abs(y) + abs(z) if sum &gt; 1: fract.append(basePiece()) Any help would be appreciated. Thanks in advance.
accepted answer: http://stackoverflow.com/a/51233542
type: AnsweredQuestion

http://stackoverflow.com/comment/138521111
has text: The import seems to be incorrect and should be: from IPython.display import display
type: AnswerComment
type: Comment
score: 0
comment on: http://stackoverflow.com/a/51316108

http://stackoverflow.com/a/51273056
downvote count: 1
has comment: http://stackoverflow.com/comment/89530749
answers question: http://stackoverflow.com/q/51272768
upvote count: 0
score: -1
has comment: http://stackoverflow.com/comment/89530387
type: Answer
has comment: http://stackoverflow.com/comment/89726267
has comment: http://stackoverflow.com/comment/89657936
has comment: http://stackoverflow.com/comment/89531177
has body: You can use getattr: import requests, json from bs4 import BeautifulSoup as soup d = soup(requests.get('https://th.jbl.com/bluetooth-portables').text, 'html.parser') category = d.find('h2', {'property':'name'}).text subcategory = d.find('span', {'class':'breadcrumb-last'}).text products = [i for i in d.find_all('div', {'class':'product-tile'})] headers = [['a', {'class':'productname-link'}], ['div', {'class':'swatch-data'}]] new_products = [[getattr(i, 'find', lambda *_:None)(*b) for b in headers] for i in products] final_products = [[getattr(a, 'attrs', lambda x:{'title':None}[x]).get('title'), json.loads(getattr(b, 'text', '{}')).get('productID')] for a, b in new_products] Output: Wireless Portables [['JBL Flip 4', 'JBLFLIP4BLKAM'], [None, None], ['JBL Flip 3', 'JBLFLIP3BLK'], ['JBL Flip 3 Special Edition', 'JBLFLIP3MALTA'], ['JBL Charge 3', 'JBLCHARGE3BLKAS'], ['JBL Charge 3 Special Edition', 'JBLCHARGE3MOSAICAS'], ['JBL Clip 2', 'JBLCLIP2BLK'], ['JBL Clip 2 Special Edition', 'JBLCLIP2MALTA'], ['JBL Pulse 2', 'JBLPULSE2BLKAS'], ['JBL GO', 'JBLGOBLK'], ['JBL Xtreme', 'JBLXTREMEBLKAS'], ['JBL Xtreme Special Edition', 'JBLXTREMESQUADAS'], ['Xtreme 2', None]] To write to a csv file, you can use this: import csv with open('product_listings.csv', 'w') as f: write = csv.writer(f) write.writerows([['category', 'subcategory', 'title', 'id'], [category, subcategory]+(['']*2)]+[(['']*2)+['' if not i else i for i in b] for b in final_products if any(b)]) Output: category,subcategory,title,id Wireless,Portables,, ,,JBL Flip 4,JBLFLIP4BLKAM ,,JBL Flip 3,JBLFLIP3BLK ,,JBL Flip 3 Special Edition,JBLFLIP3MALTA ,,JBL Charge 3,JBLCHARGE3BLKAS ,,JBL Charge 3 Special Edition,JBLCHARGE3MOSAICAS ,,JBL Clip 2,JBLCLIP2BLK ,,JBL Clip 2 Special Edition,JBLCLIP2MALTA ,,JBL Pulse 2,JBLPULSE2BLKAS ,,JBL GO,JBLGOBLK ,,JBL Xtreme,JBLXTREMEBLKAS ,,JBL Xtreme Special Edition,JBLXTREMESQUADAS ,,Xtreme 2, Edit: using selenium: from selenium import webdriver import time d = webdriver.Chrome('/path/t…
has comment: http://stackoverflow.com/comment/89531036
has comment: http://stackoverflow.com/comment/89530591
has comment: http://stackoverflow.com/comment/89531111
has comment: http://stackoverflow.com/comment/89530278

http://stackoverflow.com/comment/89574912
has text: Although argument names support your statement, their type (`uint32_t*`) doesn't as they are all pointers. Are you sure you posted the correct function signature? Just the eliminate the other factor, in the *Python* code (as it is in my answer) replace the line `dll = ctypes.CDLL("USB_IO_for_VB6.dll")` by `dll = ctypes.WinDLL("USB_IO_for_VB6.dll")` and see if there is any difference.
type: Comment
comment on: http://stackoverflow.com/a/51293382
score: 0
type: AnswerComment

http://stackoverflow.com/comment/89490780
type: Comment
score: 0
has text: Also, it would really help if you could copy and paste each command—including the prompt, and the full error output—into your question, instead of just adding comments.
type: QuestionComment
comment on: http://stackoverflow.com/q/51255533

http://stackoverflow.com/comment/89425894
has text: @AbdulAhad What would be the criterion for the text to be multiline, do you want it to have a maximum width?
type: AnswerComment
comment on: http://stackoverflow.com/a/51222284
score: 0
type: Comment

http://stackoverflow.com/comment/89366836
type: AnswerComment
comment on: http://stackoverflow.com/a/51177430
type: Comment
has text: and also interpreter option should be "-m PyInstaller". Capitalization is important.
score: 0

http://stackoverflow.com/q/51170986
has comment: http://stackoverflow.com/comment/89325477
tagged with: default
favorite count: 0
has comment: http://stackoverflow.com/comment/89325778
tagged with: path
has answer: http://stackoverflow.com/a/51171026
has answer: http://stackoverflow.com/a/51172827
tagged with: python
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/51171026
accepted answer: http://stackoverflow.com/a/51172827
upvote count: 3
has comment: http://stackoverflow.com/comment/89328835
has title: Python 3.6 is not default when I run a script
has comment: http://stackoverflow.com/comment/89325306
type: Question
has body: I have set the environment variables so that python 3.6 is the version that is run when I use the python command in the terminal, but when I run a python script from the terminal it uses python 2.7. I have included a folder called MyScripts in the path so that i can run these scripts directly from the terminal without specifying the path. Running just python shows Python 3.6.4 But executing the script shows 2.7.14. This is the script v27.py import sys print(sys.version) print(sys.executable) And this is the output
has comment: http://stackoverflow.com/comment/89324687
score: 3
has comment: http://stackoverflow.com/comment/89325590
answer count: 2
has comment: http://stackoverflow.com/comment/89329072
downvote count: 0

http://stackoverflow.com/comment/89484678
score: 1
comment on: http://stackoverflow.com/a/51252873
type: AnswerComment
type: Comment
has text: This is worth adding to the canonical question, which I believe is [this one](https://stackoverflow.com/questions/11206884/how-to-write-python-sort-key-functions-for-descending-values).

http://stackoverflow.com/q/51300364
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/89577521
upvote count: 1
answer count: 1
has answer: http://stackoverflow.com/a/51300735
has comment: http://stackoverflow.com/comment/89577638
has title: directory file import error in python
type: UnansweredQuestion
tagged with: python-2.7
has body: i am having file structure like /home/ec2-user/wep-rs/WEPR/weprs/api/voucher.py /home/ec2-user/wep-rs/WEPR/weprs/api/scrappers/quotes/quotes.py i want to access voucher.py from quotes.py i have tried these import sys sys.path.append("..")# ValueError: attempted relative import beyond top-level package from .. .. import api # ValueError: attempted relative import beyond top-level package sys.path.append("/home/ec2-user/wep-rs/WEPR/weprs/api/") from api.voucher import Voucher error i am getting is ModuleNotFoundError: No module named 'api'
downvote count: 0
score: 1
favorite count: 0
tagged with: python-3.x
type: Question

http://stackoverflow.com/comment/89583070
type: QuestionComment
has text: @Georgy thanks for your advice. I will move it.
comment on: http://stackoverflow.com/q/51302378
score: 0
type: Comment

http://stackoverflow.com/comment/89325555
score: 0
comment on: http://stackoverflow.com/q/51169773
type: Comment
type: QuestionComment
has text: I don't want to do that, I have built a model on existing data and want to improve the model with new data. Storing the previous feature matrices is not efficient. I can always train a new model with the combined data. Isn't there any other way?

http://stackoverflow.com/comment/89568062
type: Comment
has text: In fact, if you wrote this on a more normal OO style, and took advantage of those classes, your problem would solve itself. You would, e.g., construct a new `team = Team()` and `game = Game(team)` each time through the loop, so `objdata.append(team)` would be building up a list of 200 different objects, instead of a list of the same object 200 times.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51295220

http://stackoverflow.com/comment/89456839
type: AnswerComment
has text: Wait, let me try it with python 3.6.6, maybe it will work
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51238817

http://stackoverflow.com/comment/126410130
type: AnswerComment
comment on: http://stackoverflow.com/a/51201378
type: Comment
score: 2
has text: @Reihan_amn Groupby level=0 is grouping by the dataframe index level = 0 if multiindex, if not, it just groups by index. head(1) gets the first records. So, in each group get only the first record.

http://stackoverflow.com/comment/89410306
type: Comment
comment on: http://stackoverflow.com/a/51172766
type: AnswerComment
has text: This will replace `(3 blind mice)` with `-3 blind mice` - are you sure that's the right thing to do?
score: 0

vlc
tags question: http://stackoverflow.com/q/51201534
tag name: vlc
type: Tag

http://stackoverflow.com/a/51967978
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51251355
has body: If the file have format have any rule (not unique format for each record), then I suggest you write your own convertion tool. Here I suggest what the tool should do Read file as plain text. Put 4 lines into 1 records/class object ( as I see in picture, 4 records seem to have 4 lines) Parse the line (split by comma, tab, whatever you have) to get attribute Write attribute in another file, split by tab (or comma) => your csv Now, you can load your csv to Pandas.

http://stackoverflow.com/a/51286921
score: 2
upvote count: 2
accepted answer of: http://stackoverflow.com/q/51225823
has body: This turned out to be due to a combination of: Not having created an environment here: https://developer.twitter.com/en/account/environments as described here: https://developer.twitter.com/en/docs/accounts-and-users/subscribe-account-activity/guides/getting-started-with-webhooks using the wrong consumer secret in the function that created the token returned at the /webhook endpoint
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51225823
type: Answer

http://stackoverflow.com/q/51239428
favorite count: 0
has comment: http://stackoverflow.com/comment/89462881
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/89463567
has comment: http://stackoverflow.com/comment/89457932
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/89458533
has comment: http://stackoverflow.com/comment/89459899
has comment: http://stackoverflow.com/comment/89458782
has answer: http://stackoverflow.com/a/51242590
has comment: http://stackoverflow.com/comment/89458901
has comment: http://stackoverflow.com/comment/89458363
has comment: http://stackoverflow.com/comment/89461875
has comment: http://stackoverflow.com/comment/89461935
has comment: http://stackoverflow.com/comment/89458136
tagged with: mysql
has comment: http://stackoverflow.com/comment/89458810
answer count: 1
has comment: http://stackoverflow.com/comment/89460718
has comment: http://stackoverflow.com/comment/89462276
has comment: http://stackoverflow.com/comment/89461362
has comment: http://stackoverflow.com/comment/89459000
has comment: http://stackoverflow.com/comment/89458345
accepted answer: http://stackoverflow.com/a/51242590
has comment: http://stackoverflow.com/comment/89461500
has title: Django 'Cannot add foreign key constraint' error while doing makemigrations operation
has comment: http://stackoverflow.com/comment/89462455
has comment: http://stackoverflow.com/comment/89458625
has body: I am using Django 1.9.5 and python 2.7. I am also using MySQL as db. When i try to make migrations i get below error "Cannot add foreign key constraint" I get this error as i am trying to add many to many field to an existing table. When i make migration and migrate, the many to many relation table is created but without foreign key constraint. While runserver it also says; "You have unapplied migrations; your app may not work properly until they are applied." Run 'python manage.py migrate' to apply them. I can add new data to this table ,but without foreign key constraint, through the web site. But i need the table fields to be created with foreignkey constraint for the relations. The operation will create many to many relation between Worker and Workerduty tables. MySQL is InnoDB configured. Error Logs : # python manage.py migrate Operations to perform: Apply all migrations: authtoken, sessions, admin, auth, reversion, contenttypes, company Running migrations: Rendering model states... DONE Applying company.0005_Worker_duty_type...Traceback (most recent call last): File "manage.py", line 10, in &lt;module&gt; execute_from_command_line(sys.argv) File "/home/dataproj/Env/dataproj/lib/python2.7/site-packages/django/core/management/__init__.py", line 353, in execute_from_command_line utility.execute() File "/home/dataproj/Env/dataproj/lib/python2.7/site-packages/django/core/management/__init__.py", line 345, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/dataproj/Env/dataproj/lib/python2.7/site-packages/django/core/management/base.py", line 348, in run_from_argv self.execute(*args, **cmd_options) File "/home/dataproj/Env/dataproj/lib/python2.7/site-packages/django/core/management/base.py", line 399, in execute output = self.handle(*args, **options) File "/home/dataproj/Env/dataproj/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 200, in handle executor.migrate(targets, plan, fake=fake, fake_initial=fake_ini…
type: AnsweredQuestion
score: 2
has comment: http://stackoverflow.com/comment/89460834
downvote count: 0

http://stackoverflow.com/a/51228567
has body: You are almost right. You can merge the masks of lower RED and higher RED together to a single mask. For this ColorChecker.png: My Steps to find the RED: Read the image and convert to hsv. I choose the red ranges (lower 0~5, upper 175~180) using this colormap: Then merge the masks, you can judge whether the pixel is red or not by the mask. Or "crop" the region(s) for visualization: #!/usr/bin/python3 # 2018.07.08 10:39:15 CST # 2018.07.08 11:09:44 CST import cv2 import numpy as np ## Read and merge img = cv2.imread("ColorChecker.png") img_hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) ## Gen lower mask (0-5) and upper mask (175-180) of RED mask1 = cv2.inRange(img_hsv, (0,50,20), (5,255,255)) mask2 = cv2.inRange(img_hsv, (175,50,20), (180,255,255)) ## Merge the mask and crop the red regions mask = cv2.bitwise_or(mask1, mask2 ) croped = cv2.bitwise_and(img, img, mask=mask) ## Display cv2.imshow("mask", mask) cv2.imshow("croped", croped) cv2.waitKey() Choosing the correct upper and lower HSV boundaries for color detection with`cv::inRange` (OpenCV) How to detect two different colors using `cv2.inRange` in Python-OpenCV?
type: Answer
score: 6
answers question: http://stackoverflow.com/q/51225657
downvote count: 0
upvote count: 6
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51225657

http://stackoverflow.com/q/51180864
type: Question
has body: Following this tutorial, I get the error in the screenshot below when I run the command: df = web.DataReader("TSLA", 'morningstar', start, end) This is the error I get. What to do?
has answer: http://stackoverflow.com/a/69928811
has title: JSONDecodeError when using Pandas Datareader
tagged with: pandas
downvote count: 0
answer count: 1
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89683204
type: UnansweredQuestion
tagged with: python
score: 2
upvote count: 2
tagged with: pandas-datareader
tagged with: jsondecoder

http://stackoverflow.com/comment/128202049
comment on: http://stackoverflow.com/a/51291059
type: AnswerComment
has text: Awesome information. Thank you!
score: 0
type: Comment

http://stackoverflow.com/comment/89407303
score: 0
type: AnswerComment
type: Comment
has text: How can you use format?
comment on: http://stackoverflow.com/a/51197368

http://stackoverflow.com/comment/89555630
comment on: http://stackoverflow.com/a/51288738
type: AnswerComment
score: 0
type: Comment
has text: Thank you! I feel stupid now ^_^. No other characters are allowed for filenames other than '-', '_', and alphanumeric values right?

http://stackoverflow.com/q/51216070
has answer: http://stackoverflow.com/a/51216317
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89413374
score: 1
has body: I'm still a newb to this, so sorry if I mess up :D So I'm trying to write a script that goes through some .xml files to get certain lines and put's them into an excel sheet. Code: import os import openpyxl def main(): print_header() folder = get_folder_from_user() if not folder: print("Sorry, that folder doesn't exist.") return text = get_search_text_from_user() if not text: print("Sorry, I can't search for nothing.") return count = input("Show match count? y/n") name = "output.xlsx" # name = input("Name for workbook: ") x = [] output = search_file(folder, text) match_count = 0 for i in output: match_count += 1 string = i string = string.split("&gt;") string = string[1] string = string.split("&lt;") string = string[0] i = string print(i) x.extend([i]) write_to_workbook(name, x) if count == "y": print("==================") print("Found {} matches".format(match_count)) print("==================") def write_to_workbook(name, x): wb = openpyxl.Workbook() ws = wb.active a = 1 ws.append(x) wb.save("C:/Users/Kevin/Desktop/{}".format(name)) a += 1 def print_header(): print("-----------------------------------") print("----------File Search App----------") print("-----------------------------------") print() def get_folder_from_user(): folder = input("Which folder do you want to search? ") if not folder or not folder.strip(): return None if not os.path.isdir(folder): return None return os.path.abspath(folder) def get_search_text_from_user(): print("Which data do you want me to copy for you?") print("[1]SeqTest Read") print("[2]SeqTest Write") print("[3]Random 4K1TTest Read") print("[4]Random 4K1TTest Write") print("[5]Random 4K64TTest Read") print("[6]Random 4K64TTest Write") print("[7]AccTimeTest Read") print("[8]AccTimeTest Write") print("[9]Score") print("[0]All") choice = int(input("Choose now: ")) if choice == 1: line = 15 elif choice == 2: line = 16 elif choice == 3: line = 19 elif choice == 4: line = 20 elif choice == 5: line = 23 elif choice == 6: line = 24 elif choi…
type: Question
answer count: 2
upvote count: 1
has comment: http://stackoverflow.com/comment/89413299
has comment: http://stackoverflow.com/comment/89413501
favorite count: 0
tagged with: python
has title: Permission denied once code is changed
tagged with: permissions
has comment: http://stackoverflow.com/comment/89413546
has answer: http://stackoverflow.com/a/51216490
downvote count: 0

http://stackoverflow.com/comment/89381393
type: QuestionComment
score: 5
comment on: http://stackoverflow.com/q/51199868
has text: Possible duplicate of [Flatten multiple columns in a dataframe to a single column](https://stackoverflow.com/questions/46435329/flatten-multiple-columns-in-a-dataframe-to-a-single-column)
type: Comment

http://stackoverflow.com/comment/89394141
type: AnswerComment
type: Comment
has text: @ADIN Just don't convert ndarray to UMat in the first place?
comment on: http://stackoverflow.com/a/51205604
score: 0

http://stackoverflow.com/comment/89415584
type: QuestionComment
has text: @abarnert I think you might be right - I've posted the full example - do you think this could be the issue?
comment on: http://stackoverflow.com/q/51216219
score: 0
type: Comment

remote-debugging
tag name: remote-debugging
tags question: http://stackoverflow.com/q/51249904
type: Tag

http://stackoverflow.com/comment/89502099
comment on: http://stackoverflow.com/q/51262015
score: 1
has text: Can you show form class?
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51244304
tagged with: python
answer count: 1
score: 8
tagged with: filtering
tagged with: fastparquet
has answer: http://stackoverflow.com/a/51245341
has body: I am trying to read parquet files using thedask read_parquet method and the filters kwarg. however it sometimes doesn't filter according to the given condition. Example: creating and saving data frame with a dates column import pandas as pd import numpy as np import dask.dataframe as dd nums = range(1,6) dates = pd.date_range('2018-07-01', periods=5, freq='1d') df = pd.DataFrame({'dates':dates, 'nums': nums}) ddf = dd.from_pandas(df, npartitions=3).to_parquet('test_par', engine = 'fastparquet') when i read and filter on the dates column from the 'test_par' folder it doesn't seem to work filters=[('dates', '&gt;', np.datetime64('2018-07-04'))] df = dd.read_parquet('test_par', engine='fastparquet', filters=filters).compute() as you can see in the output, 2018-07-03 and 2018-07-04 are present. +-------+------------+------+ | | dates | nums | +-------+------------+------+ | index | | | +-------+------------+------+ | 2 | 2018-07-03 | 3 | +-------+------------+------+ | 3 | 2018-07-04 | 4 | +-------+------------+------+ | 4 | 2018-07-05 | 5 | +-------+------------+------+ Am i doing something wrong ? or should i report this on github ?
tagged with: dataframe
accepted answer: http://stackoverflow.com/a/51245341
type: AnsweredQuestion
downvote count: 0
favorite count: 0
has title: filtering with dask read_parquet method gives unwanted results
tagged with: dask
upvote count: 8
type: Question

http://stackoverflow.com/q/51206209
downvote count: 1
linked to: http://stackoverflow.com/q/15891038
tagged with: sum
has answer: http://stackoverflow.com/a/51206359
tagged with: dataframe
type: Question
has answer: http://stackoverflow.com/a/51207680
has answer: http://stackoverflow.com/a/51209442
has comment: http://stackoverflow.com/comment/89399375
favorite count: 0
has comment: http://stackoverflow.com/comment/89397466
answer count: 3
tagged with: pandas
score: 1
has title: Summing an entire column with another column in pandas
upvote count: 2
has body: I'm trying to sum an entire column by country, but when I use my_df.groupby('COUNTRY').VALUES.mean() It throws a DataError: No numeric types to aggregate And when I use my_df.groupby('COUNTRY').VALUES.sum() It produces really big values that are far from realistic (maybe by adding them as strings together?) Could it be that it interprets the values in the column as strings, or am I using the function the wrong way? I'm trying to accomplish exactly what this guy is doing at 1:45 https://www.youtube.com/watch?v=qy0fDqoMJx8 i.e the values column contains integers that I want to sum by each country.
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/51241445
has title: How to filter records for fixed, regular blocks of time in PySpark?
downvote count: 1
tagged with: dataframe
score: -1
type: Question
answer count: 2
upvote count: 0
tagged with: pyspark
favorite count: 0
has answer: http://stackoverflow.com/a/51245395
has body: I'm interested in capturing user behaviour during specific hours of the day, everyday. Suppose I have a dataframe with the columns +-------+-----+----------+ | start | end | activity | +-------+-----+----------+ Both start and end are in Unix timestamps. Is there any way to filter for a specific interval of time, like 10 a.m. to 11 a.m. every day in PySpark? Note that start may start before 10 and end may end after 11. I want to find all time periods which overlap.
tagged with: python
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51282660

http://stackoverflow.com/comment/89541380
comment on: http://stackoverflow.com/a/51281345
score: 1
type: AnswerComment
type: Comment
has text: Umm... another random idea: `df.name.apply(lambda name, counts=Counter(df.name): name if counts[name] > 1 else 'other')`

http://stackoverflow.com/comment/89477894
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51233859
has text: I suspect it'll boil down to what signal does your remote process receive and how it reacts to it. In case you've called `ssh -t` from the console, it's gonna get `SIGINT`. When you kill `subprocess`, I suspect it gets `SIGHUP`. I was also curious what you run, and if shell is involved in Python side. I suspect it is with that command line, but it probably does not need to spawn another process for the `ssh` call and can just `execve` it. You can check try to find your run ssh from the command line, find its pid and send it both signals see if it makes that difference.

http://stackoverflow.com/comment/89421174
score: 0
type: AnswerComment
type: Comment
has text: I now see that it is because your input string actually uses the slanted double-quotes, `“` and `”`, not the standard double-quote, `"`.
comment on: http://stackoverflow.com/a/51219822

http://stackoverflow.com/a/51318021
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51253748
has body: You can read from the text file as a dataframe using pandas: Let Countries.txt be the text file with the following contents: China Greece Ireland France The contents can be read to a dataframe using the following lines of code: import pandas as pd list_countries = pd.read_csv('Countries.txt', header = None) list_countries.columns = ["countries"] To write list_countries to Excel: Writer = pd.ExcelWriter('Countries.xlsx') list_countries.to_excel(Writer,'Sheet1', index = False) Writer.save() It will output the Countries.xlsx file with the country names under the column title countries

http://stackoverflow.com/comment/89569622
comment on: http://stackoverflow.com/q/51295904
type: Comment
type: QuestionComment
score: 0
has text: Your code have no problem. And the reason why length of the new array is shorter than the A array may because there are some value B have A donot have and some value A have but B donot have, for both scenarios, there wonot be result in new_array. And this results in you new_array's length <= any of both arrays.

http://stackoverflow.com/a/51269940
has body: given that your DataFrame is called df, you can do this the following way: columns_to_keep = df.iloc[-1, :]&gt;=0.3 new_df = df.loc[:, columns_to_keep] in this case df.iloc[-1, :] takes the last row as a pd.Series. &gt;=0.3 will create a boolean Series which we can then use with .loc to only keep the columns for which the last row's value is bigger than or equal to 0.3. I have prepared a minimal, complete and verifiable example below: In [7]: import pandas as pd In [8]: df = pd.DataFrame({'A':[0.1, 0.1, 0.2], 'B':[0.2, 0.3, 0.3], 'C':[0.2, 0.4, 0.4], 'D':[0.2, 0.2, 0.2], 'E':[0.1, 0.2, 0.4], 'F':[0.3 ...: , 0.3, 0.4]}, index=['08-Jul-18', '09-Jul-18', '10-Jul-18']) In [9]: df Out[9]: A B C D E F 08-Jul-18 0.1 0.2 0.2 0.2 0.1 0.3 09-Jul-18 0.1 0.3 0.4 0.2 0.2 0.3 10-Jul-18 0.2 0.3 0.4 0.2 0.4 0.4 In [10]: df.loc[:, df.iloc[-1, :] &gt;=.3] Out[10]: B C E F 08-Jul-18 0.2 0.2 0.1 0.3 09-Jul-18 0.3 0.4 0.2 0.3 10-Jul-18 0.3 0.4 0.4 0.4
has comment: http://stackoverflow.com/comment/89606564
has comment: http://stackoverflow.com/comment/89518054
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/89555462
score: 1
has comment: http://stackoverflow.com/comment/89518569
has comment: http://stackoverflow.com/comment/89534844
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51269871
downvote count: 0
answers question: http://stackoverflow.com/q/51269871
has comment: http://stackoverflow.com/comment/89518314

http://stackoverflow.com/comment/89551997
comment on: http://stackoverflow.com/q/51284879
type: Comment
type: QuestionComment
has text: It may be sent often. However the structure always remains the same with the same number of values in the tables. However the values are constantly different
score: 0

http://stackoverflow.com/q/51276796
has answer: http://stackoverflow.com/a/51276870
has title: How to split list of lists to each list in list to one dictionary using python
favorite count: 0
has answer: http://stackoverflow.com/a/51276883
accepted answer: http://stackoverflow.com/a/51276870
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/51277154
answer count: 4
score: 2
type: AnsweredQuestion
tagged with: list
has body: I currently have this list: a = [[ 'abc=lalalla', 'appa=kdkdkdkd', 'kkakaka=oeoeoeo'],[ 'abc=lalalla', 'appa=kdkdkdkd', 'kkakaka=oeoeoeo' ],[ 'abc=lalalla', 'appa=kdkdkdkd', 'kkakaka=oeoeoeo']] I want to convert it to this dictionary: [{'abc': 'lalalla', 'appa': 'kdkdkdkd', 'kkakaka': 'oeoeoeo'}, {'abc': 'lalalla', 'appa': 'kdkdkdkd', 'kkakaka': 'oeoeoeo'}, {'abc': 'lalalla', 'appa': 'kdkdkdkd', 'kkakaka': 'oeoeoeo'}] I have tried using dict along with split: d = (dict(x.split('=') for s in a for x in s)) I am getting only one dictionary because of keys are same so I how can I get every list as one dictionary?
upvote count: 3
possible better answer: http://stackoverflow.com/a/51276838
downvote count: 1
has answer: http://stackoverflow.com/a/51276838
type: Question
has comment: http://stackoverflow.com/comment/89531308
has comment: http://stackoverflow.com/comment/89531330

http://stackoverflow.com/tag/zip
tags question: http://stackoverflow.com/q/51170000
type: Tag
tags question: http://stackoverflow.com/q/51223791
tags question: http://stackoverflow.com/q/51231247
tag name: zip

http://stackoverflow.com/comment/89502072
score: 3
type: QuestionComment
type: Comment
has text: [why not simply try it out?](https://repl.it/repls/HideousColdDeclarations)
comment on: http://stackoverflow.com/q/51261969

http://stackoverflow.com/q/51258962
has body: I am trying to fetch twitters data in python using tweepy, I want to set the number of tweets returned. Here is my block of code class StdOutListener(StreamListener): def on_data(self, data): print (data) return True def on_error(self, status): print (status) if __name__ == '__main__': #This handles Twitter authetification and the connection to Twitter Streaming API l = StdOutListener() auth = OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_key, access_secret) stream = Stream(auth, l) #This line filter Twitter Streams to capture data by the keywords: 'python', 'javascript', 'ruby' stream.filter(track=['hello', 'javascript', 'python'])
has comment: http://stackoverflow.com/comment/89533231
tagged with: python
tagged with: tweepy
has comment: http://stackoverflow.com/comment/89535001
has title: Apply limits on tweets
type: Question
has comment: http://stackoverflow.com/comment/89496877
has answer: http://stackoverflow.com/a/51779239
has comment: http://stackoverflow.com/comment/89533254
score: 0
has comment: http://stackoverflow.com/comment/89533267
answer count: 1
has comment: http://stackoverflow.com/comment/89533299
tagged with: data-retrieval
type: UnansweredQuestion

http://stackoverflow.com/q/51290499
has answer: http://stackoverflow.com/a/51291552
type: Question
has answer: http://stackoverflow.com/a/51290634
tagged with: java
has comment: http://stackoverflow.com/comment/89618911
tagged with: ui-automation
has comment: http://stackoverflow.com/comment/89558858
answer count: 2
has comment: http://stackoverflow.com/comment/89558871
tagged with: javascript
has title: Validation error even is Drop Down value selected by Selenium
tagged with: python
score: 0
type: UnansweredQuestion
tagged with: selenium
has body: I am automating the website testing using selenium, I have a scenario in which I need to fill the drop-down mandatory. I am filling the drop-down value using below code which is working fine: select = Select(find_element_by_name('feet') select.select_by_value("5") Now the problem is when I click on Next button after selecting a drop-down value(5) using automation script, it throws validation error saying: "Please select the value from the drop-down". I have tried to execute javascript from browser console as well and received the same result. But when I select the drop-down value manually Next button is taking me to other page and it's working fine. So the bottom line is If I use automation script in order to select the drop-down value browser will not detect the change made to the drop down, hence when I click on Next button it throws the validation error Any help/hint on this highly appreciated. Thank you.

http://stackoverflow.com/comment/89505310
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51263370
type: Comment
has text: yes. use these: `num_data = pd.read_csv('/home/user/Documents/MOOC dataset cleaned/student_reg_vle_info_assessment.csv')` then `x = num_data.iloc[:,:10]` and `y = num_data.iloc[:,10:11]`

http://stackoverflow.com/q/51191735
has body: I want to simulate n random choices with given probabilities prob. My current solution is the following: from random import choices result = [0]*len(prob) population = list(range(0,len(prob))) ch = choices(population, weights=prob, k=n) for i in ch: result[i] += 1 My problem is that I call this code a large number of times and usually with large n and this solution does not seem efficient at all. Is there a better way of doing it (like a pre-build function of some library)? To sumarize I want the most efficient way of building a random list summing to $n$ such that the probability of obtaining a given list is equal to the probability of obtaining this list as n random choices with probability prob. Thank you [EDIT to add context] What I am really doing is n random walks in a kind of Markov chain as follow: def rand_walk(n,state): next_states,prob = complicated_function(state) // compute the next states and their probability succ = distribute_over_next_states(n, prob) // compute how many walk goes to which states accu = complicated_function_2(state) // accumulator for the result for ns in range(0,len(next_states)): accu += rand_walk(succ[i],next_states[I]) return accu The point is that the computation of the next states and their probability is costly thus I avoid computing it to many times (thus I avoid doing n runs sequential). That is why I want to distribute the n following the given probability. I hope this is somehow clear enough to understand ...
has comment: http://stackoverflow.com/comment/89365082
linked to: http://stackoverflow.com/q/3589214
has comment: http://stackoverflow.com/comment/89366838
has comment: http://stackoverflow.com/comment/89365070
has answer: http://stackoverflow.com/a/51193403
accepted answer: http://stackoverflow.com/a/51193403
tagged with: python
has comment: http://stackoverflow.com/comment/89367409
type: AnsweredQuestion
score: 2
has comment: http://stackoverflow.com/comment/89365204
has comment: http://stackoverflow.com/comment/89365495
linked to: http://stackoverflow.com/q/18659858
downvote count: 0
favorite count: 0
possible better answer: http://stackoverflow.com/a/51191925
has comment: http://stackoverflow.com/comment/89367394
has comment: http://stackoverflow.com/comment/89365127
has comment: http://stackoverflow.com/comment/89366302
has comment: http://stackoverflow.com/comment/89365785
has answer: http://stackoverflow.com/a/51191925
type: Question
has comment: http://stackoverflow.com/comment/89366718
upvote count: 2
answer count: 2
has comment: http://stackoverflow.com/comment/89365439
tagged with: random
has comment: http://stackoverflow.com/comment/89367246
has title: Genrating random (int) list of given sum python

http://stackoverflow.com/comment/89463423
type: QuestionComment
has text: @roganjosh yes, it is, but I do not want to use any CSV library coz I would like to reduce memory requirement as much as possible
comment on: http://stackoverflow.com/q/51208937
score: 0
type: Comment

http://stackoverflow.com/comment/93327409
comment on: http://stackoverflow.com/a/51289294
type: Comment
score: 0
has text: Hello! Your example is helpful. Can you also tell how can we implement an activation like tanh?
type: AnswerComment

http://stackoverflow.com/tag/mp3
tags question: http://stackoverflow.com/q/51263512
type: Tag
tag name: mp3
tags question: http://stackoverflow.com/q/51262309
tags question: http://stackoverflow.com/q/51300281

http://stackoverflow.com/comment/89616697
type: QuestionComment
comment on: http://stackoverflow.com/q/51319979
has text: added code to generate input
score: 0
type: Comment

http://stackoverflow.com/a/51226872
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51226859
type: Answer
has body: You should use elif to put the other two tests on the same level as the test for 'mama'; otherwise ime needs to be 'mama' first in order to be tested for 'lovro', which can never happen. imena_i_rodjendani={'mama':'1-2-1981','lovro':'3-12-2004','tata':'1-5-1982'} ime=str(input("ime: ")) if ime==str('mama'): print(imena_i_rodjendani.get('mama')) elif ime==str('lovro'): print(imena_i_rodjendani.get('lovro')) else: print(imena_i_rodjendani.get('tata'))
accepted answer of: http://stackoverflow.com/q/51226859
score: 0

http://stackoverflow.com/q/51181765
tagged with: python-3.x
upvote count: 5
has answer: http://stackoverflow.com/a/51181789
tagged with: python
tagged with: generator
type: AnsweredQuestion
downvote count: 0
accepted answer: http://stackoverflow.com/a/51181775
has body: There is a code segment. running the program gets the following error epoch, step, d_train_feed_dict, g_train_feed_dict = inf_data_gen.next() AttributeError: 'generator' object has no attribute 'next' The corresponding code segment is listed as follows. What can be the reason underlying it? inf_data_gen = self.inf_get_next_batch(config) def inf_get_next_batch(self, config): """Loop through batches for infinite epoches. """ if config.dataset == 'mnist': num_batches = min(len(self.data_X), config.train_size) // config.batch_size else: self.data = glob(os.path.join("./data", config.dataset, self.input_fname_pattern)) num_batches = min(len(self.data), config.train_size) // config.batch_size epoch = 0 while True: epoch += 1 for (step, d_train_feed_dict, g_train_feed_dict) in \ self.get_next_batch_one_epoch(num_batches, config): yield epoch, step, d_train_feed_dict, g_train_feed_dict
type: Question
linked to: http://stackoverflow.com/q/12274606
possible better answer: http://stackoverflow.com/a/51181789
has title: Getting next item from generator fails
has answer: http://stackoverflow.com/a/51181775
answer count: 2
score: 5
has comment: http://stackoverflow.com/comment/89345950
linked to: http://stackoverflow.com/q/1073396
favorite count: 0

http://stackoverflow.com/comment/89340266
score: 0
has text: Yes, using this `if query and query1:` condition I can get desired results. However, can you tell me why I'm getting that big row count even when they are empty?
type: Comment
comment on: http://stackoverflow.com/a/51178557
type: AnswerComment

http://stackoverflow.com/a/59435837
type: Answer
upvote count: 14
has body: This is what solved my issue Install MySQL Connector/C (Archived Versions) from here It is probably installed in the following location C:\Program Files\MySQL\MySQL Connector C 6.1 Copy the entire folder MySQL Connector C 6.1 to C:\Program Files (x86)\MySQL\MySQL Connector C 6.1 Try executing the command pip3 install mysqlclient. Successful? Good Job! Unsuccessful? Install MariaDB connector from here Probably installed in the location C:\Program Files\MariaDB\MariaDB Connector C 64-bit Copy the contents from C:\Program Files\MariaDB\MariaDB Connector C 64-bit\include and Paste into a folder. Name it as mariadb and paste it to the location C:\Program Files (x86)\MySQL\MySQL Connector C 6.1\include\ Copy the contents from C:\Program Files\MariaDB\MariaDB Connector C 64-bit\lib and Paste into a folder name it as mariadb and paste it to the location `C:\Program Files (x86)\MySQL\MySQL Connector C 6.1\lib` Try executing the command pip3 install mysqlclient. This worked for me
has comment: http://stackoverflow.com/comment/129435544
score: 14
downvote count: 0
answers question: http://stackoverflow.com/q/51294268

http://stackoverflow.com/a/62405535
downvote count: 0
has body: The * is interpreted as regex. As that's not what you want, you can escape * by \ df2 = df[df.Team != 'Fin\*'] Or simply use df2 = df[~dfTeam.str.contains('Fin')]
type: Answer
score: 2
answers question: http://stackoverflow.com/q/51182182
upvote count: 2

http://stackoverflow.com/comment/89398116
score: 2
comment on: http://stackoverflow.com/q/51208552
has text: `range(0, len(a1)-2)` is only evaluated once, but you change `len` of the list with `remove`. [How does a for loop evaluate its argument](//stackoverflow.com/a/35439647)
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89569294
comment on: http://stackoverflow.com/q/51295808
score: 0
type: QuestionComment
type: Comment
has text: Thank you! I'll try that and report my results.

http://stackoverflow.com/a/51328433
answers question: http://stackoverflow.com/q/51309693
upvote count: 3
has body: Here is a working solution derived from Pault's answer: Create the Dataframe: rdd = sc.parallelize([(1,"19:00:00", "19:30:00", 30), (1,"19:30:00", "19:40:00", 10),(1,"19:40:00", "19:43:00", 3), (2,"20:00:00", "20:10:00", 10), (1,"20:05:00", "20:15:00", 10),(1,"20:15:00", "20:35:00", 20)]) df = spark.createDataFrame(rdd, ["user_id", "start_time", "end_time", "duration"]) df.show() +-------+----------+--------+--------+ |user_id|start_time|end_time|duration| +-------+----------+--------+--------+ | 1| 19:00:00|19:30:00| 30| | 1| 19:30:00|19:40:00| 10| | 1| 19:40:00|19:43:00| 3| | 1| 20:05:00|20:15:00| 10| | 1| 20:15:00|20:35:00| 20| +-------+----------+--------+--------+ Create an indicator column that indicates whenever the time has changed, and use cumulative sum to give each group a unique id: import pyspark.sql.functions as f from pyspark.sql import Window w1 = Window.partitionBy('user_id').orderBy('start_time') df = df.withColumn( "indicator", (f.col("start_time") != f.lag("end_time").over(w1)).cast("int") )\ .fillna( 0, subset=[ "indicator"] )\ .withColumn( "group", f.sum(f.col("indicator")).over(w1.rangeBetween(Window.unboundedPreceding, 0)) ) df.show() +-------+----------+--------+--------+---------+-----+ |user_id|start_time|end_time|duration|indicator|group| +-------+----------+--------+--------+---------+-----+ | 1| 19:00:00|19:30:00| 30| 0| 0| | 1| 19:30:00|19:40:00| 10| 0| 0| | 1| 19:40:00|19:43:00| 3| 0| 0| | 1| 20:05:00|20:15:00| 10| 1| 1| | 1| 20:15:00|20:35:00| 20| 0| 1| +-------+----------+--------+--------+---------+-----+ Now GroupBy on user id and the group variable. +-------+----------+--------+--------+ |user_id|start_time|end_time|duration| +-------+----------+--------+--------+ | 1| 19:00:00|19:43:00| 43| | 1| 20:05:00|20:35:00| 30| +-------+----------+--------+--------+
downvote count: 0
type: Answer
score: 3

http://stackoverflow.com/a/51195543
accepted answer of: http://stackoverflow.com/q/51195502
has comment: http://stackoverflow.com/comment/89372906
has body: You have to wait until it will be clickable: # I have fixed xpath element = WebDriverWait(driver, 10).until( EC.element_to_be_clickable((By.XPATH, "//*[@id='AutoNumber1']//a[contains(., 'qui.')]")) ) element.click() Note: you have to do some imports: from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC There is also possible to use CSS Selector to locate the element: #AutoNumber1 &gt; tbody &gt; tr:nth-child(3) &gt; td:nth-child(2) &gt; p:nth-child(3) &gt; font &gt; a and element = WebDriverWait(driver, 10).until( EC.element_to_be_clickable((By.CSS_SELECTOR, "#AutoNumber1 &gt; tbody &gt; tr:nth-child(3) &gt; td:nth-child(2) &gt; p:nth-child(3) &gt; font &gt; a")) ) element.click() EDIT: you have to switch to the frame before locate your element like this: driver.switch_to.frame(driver.find_element_by_xpath("//frame[@name = 'principale']")) So the full code will be like this: from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC url = "https://www.coeweb.istat.it/" driver = webdriver.Chrome() driver.get(url) driver.switch_to.frame(driver.find_element_by_xpath("//frame[@name = 'principale']")) # switches to frame element = WebDriverWait(driver, 10).until( EC.element_to_be_clickable((By.XPATH, "//*[@id='AutoNumber1']//a[contains(., 'qui.')]")) ) element.click() driver.switch_to.default_content() # switch back to default content Explanation: you cannot interact with the elements which are in iframe or in a frame. To be able to do this, you have to find a frame, switch to it, do stuff and then switch back to default content
type: Answer
has comment: http://stackoverflow.com/comment/89373057
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/89372828
has comment: http://stackoverflow.com/comment/89373410
answers question: http://stackoverflow.com/q/51195502
has comment: http://stackoverflow.com/comment/89423371
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/51179906
type: Question
answer count: 1
has body: My code is: import wrds db = wrds.Connection() compustatq = db.raw_sql(""" select * from comp.fundq """) compustatq.to_csv('path.csv',index=False) The problem is that the dataset is so large that I run out of RAM memory. I was therefore thinking if it is possible to download/save the data directly on the disk? Hence, avoiding the 2 step procedure of downloading into a dataframe and then exporting to a csv file.
score: 0
has comment: http://stackoverflow.com/comment/89342438
has comment: http://stackoverflow.com/comment/89350522
has comment: http://stackoverflow.com/comment/89358463
tagged with: python
accepted answer: http://stackoverflow.com/a/51184846
has comment: http://stackoverflow.com/comment/89358951
tagged with: wrds
has answer: http://stackoverflow.com/a/51184846
type: AnsweredQuestion
tagged with: mysql
has title: Save WRDS SQL query to file in python

http://stackoverflow.com/q/51263420
type: Question
has comment: http://stackoverflow.com/comment/89510591
has comment: http://stackoverflow.com/comment/89505256
has title: Python :0 being appended to string
tagged with: string
tagged with: tensorboard
tagged with: python
answer count: 0
tagged with: tensor
score: 0
type: UnansweredQuestion
has body: I am trying to print the name of a layer in tensorflow using this code. ## Creating the convolutional layer layer = tf.nn.conv2d(input=input, filter=weights, strides=[1, 1, 1, 1], padding='SAME') print("layer name is", str(layer.name)) The output is 'Conv2D:0'. In tensorboard its name is displayed as Conv2D. Why is the :0 being appended to the name? Or is this the actual name?
has comment: http://stackoverflow.com/comment/89505225
has comment: http://stackoverflow.com/comment/89504711
tagged with: tensorflow

http://stackoverflow.com/a/51219803
downvote count: 0
has comment: http://stackoverflow.com/comment/89420620
has body: Matrices cannot be used as keys for dictionaries. If you want to know more about dictionary keys, check out this site. Even though it has a __hash__, mutable objects should not be used as hashes, as if you change the value, then you will most likely get KeyError. According to this, hash method for numpy matrix does not satisfy one of the basic condition of hash: for all i1, i2, if hash(i1) != hash(i2), then i1 != i2 However, when I tried using hash(np.matrix('1 2; 3 4)), I got : &gt;&gt;&gt; from numpy import matrix &gt;&gt;&gt; hasattr(matrix,'__hash__') True &gt;&gt;&gt; hash(matrix('1 2; 3 4')) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: unhashable type: 'matrix' One possible solution (which may or may not work for all cases): &gt;&gt;&gt; l = matrix([[0.],[1.]]),matrix([[ 1.],[ 0.]]),matrix([[ 1.],[ 0.]]) &gt;&gt;&gt;dict = {str(matrix([[ 0.],[ 1.]])): '1' ,str(matrix([[ 1.],[ 0.]])):'0'} &gt;&gt;&gt; output = [dict[str(i)] for i in l] &gt;&gt;&gt; output ['1', '0', '0'] String are hashable, unlike matrix
has comment: http://stackoverflow.com/comment/89420816
type: Answer
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/51219761
answers question: http://stackoverflow.com/q/51219761
type: AcceptedAnswer

http://stackoverflow.com/a/51291459
answers question: http://stackoverflow.com/q/51291013
score: 0
has comment: http://stackoverflow.com/comment/89566245
type: AcceptedAnswer
has body: import csv def filter_dates(csv_filepath) with open(csv_filepath, 'r') as in_file: csv_in = list(csv.reader(in_file)) # create accumulator for new list to add only valid values filtered_list = [] filetered_list.append(csv_in[0]) # append header to new list # filter the list making sure no errors appear BEFORE writing to the file for row in csv_in[1:]: #skip header (first row) if int(row[2]) &gt;= 2011: # if entry is NEWER OR EQUAL TO than 7 years, we add it to filtered_list filtered_list.append(row) # now filtered_list contains only entires where index position 2 contains valid years with open(csv_filepath, 'w') as out_file: writer = csv.writer(out_file) writer.writerows Here is a fully independent example: csv_in = [ ['name', 'sbin', 'year'], ['moby_dick', 'sbin', '1851'], ['new_book', 'sbin', '2011'], ['newest_book', 'sbin', '2018'], ] filtered_list = [] filtered_list.append(csv_in[0]) # this is where the header is added for row in csv_in[1:]: #skip header (first row) if int(row[2]) &gt;= 2011: filtered_list.append(row) print(filtered_list) A couple of notes: it's generally good to store this kind of stuff in memory before you open the file to write (or overwrite in this case) so that any error while reading and filtering the file happens before we try to modify the output easiest way to overwrite a file is to first read it, commit the contents to memory (csv_in the array I've defined in the first with block this case), and then *finally8 once the data is ready (filtered_list) for 'shipping' commit it to a file never ever use the global declaration in python, it's never worth it and causes a lot of headaches down the line test
has comment: http://stackoverflow.com/comment/89566650
type: Answer
has comment: http://stackoverflow.com/comment/89566385
accepted answer of: http://stackoverflow.com/q/51291013

http://stackoverflow.com/a/51186690
score: 1
has comment: http://stackoverflow.com/comment/89367382
answers question: http://stackoverflow.com/q/51186586
upvote count: 1
has comment: http://stackoverflow.com/comment/89371919
has comment: http://stackoverflow.com/comment/89421690
type: Answer
has body: Simply try this: def first_and_last_4(x): return x[:4]+x[-4:] #you had indentation problem here
has comment: http://stackoverflow.com/comment/89421676
downvote count: 0

http://stackoverflow.com/comment/89353585
type: QuestionComment
has text: I don't see any `None` in your code.
comment on: http://stackoverflow.com/q/51185735
score: 0
type: Comment

http://stackoverflow.com/a/78061321
has body: This is probably a Python version mixup. You have more than one version of Python installed and while your notebook is "using" one version, pip is defaulting to the other. Try to run the following commmands: python3 -m pip install scikit-learn notebook python3 -m notebook Alternatively, try running: pip install scikit-learn Directly from a notebook cell without an exclamation point prefix. This should install scikit-learn on the notebook's python kernel.
type: Answer
answers question: http://stackoverflow.com/q/51313599
score: 1
upvote count: 1
downvote count: 0

http://stackoverflow.com/q/51249794
upvote count: 9
accepted answer: http://stackoverflow.com/a/51250015
answer count: 1
has comment: http://stackoverflow.com/comment/89478516
downvote count: 0
has comment: http://stackoverflow.com/comment/89478694
has title: Do I need to activate virtual environment when using venv
favorite count: 0
has answer: http://stackoverflow.com/a/51250015
tagged with: python
has body: Using Python 3.7.0 on Mac. Trying to use venv module that was added post python 3.4. I setup my virtual env using python3 venv -m path/to/my/dir - my question is do I need to activate this virtual env to use? The documentation seem to imply I don't need to? You don’t specifically need to activate an environment; activation just prepends the virtual environment’s binary directory to your path, so that “python” invokes the virtual environment’s Python interpreter and you can run installed scripts without having to use their full path. However, all scripts installed in a virtual environment should be runnable without activating it, and run with the virtual environment’s Python automatically. If I don't have to activate, what is the benefit of prepending venv to binary directory? Wouldn't this have to happen regardless for a venv to work?
type: AnsweredQuestion
type: Question
score: 9
tagged with: python-venv

http://stackoverflow.com/comment/89510140
comment on: http://stackoverflow.com/a/51265645
type: AnswerComment
score: 0
type: Comment
has text: If the "starting point", `rootDir`, is `C:\\New Folder`, does this solution print it? It seem to me that it doesn't...

http://stackoverflow.com/comment/89554810
type: AnswerComment
has text: Why should I look for values? I will just open the page with the cookie and then download the html and take out the table? Right? No?
comment on: http://stackoverflow.com/a/51287551
score: 0
type: Comment

http://stackoverflow.com/a/51181024
has comment: http://stackoverflow.com/comment/89354560
type: Answer
upvote count: 5
downvote count: 0
has body: Sorry I just realized this was a dumb question. I am doing far fewer updates -- by a factor of 1,024. That's why the accuracy is much lower. I could adjust the learning rate but there is clearly a tradeoff between batch size and learning rate that I am just learning about now.
answers question: http://stackoverflow.com/q/51180423
score: 5

http://stackoverflow.com/comment/89434869
type: QuestionComment
has text: Perhaps I'm missing something, but doesn't `format(dhash_bits, '032x')` also produce the `dhash_hex` output?
comment on: http://stackoverflow.com/q/51227416
score: 0
type: Comment

http://stackoverflow.com/comment/89598630
score: 0
type: Comment
type: QuestionComment
has text: @jdv i apologize im new to coding in general, I want to order the files from smallest to largest in number, I am unsure what the word for that is.
comment on: http://stackoverflow.com/q/51310619

http://stackoverflow.com/comment/89319741
has text: @a_guest Yeah, that's why my comment to the question for clarification, because I don't think OP meant odd, even rows, but more like permuting axes. I will wait for the clarification.
type: Comment
score: 0
comment on: http://stackoverflow.com/a/51168225
type: AnswerComment

http://stackoverflow.com/comment/89614441
has text: @MoRe - No, problem is above, `df_amounts.loc[:, 'text'] = df_amounts.text.str.strip("EUR€")` only modify filtered data, so warning.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51319238

http://stackoverflow.com/q/51273748
linked to: http://stackoverflow.com/q/8548030
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89528353
tagged with: python
tagged with: installation
tagged with: openai-gym
has body: I have python 3.5 installed on OSX, however 'pip' does not work for some reason and 'install' is a syntax error, could some body give me step by step beginners directions to get this sorted.
has comment: http://stackoverflow.com/comment/89525700
score: -4
tagged with: pip
has comment: http://stackoverflow.com/comment/89525687
has answer: http://stackoverflow.com/a/51683014
type: Question
has title: Errors with 'pip' and 'install'
downvote count: 4
upvote count: 0
answer count: 1

http://stackoverflow.com/comment/89383016
has text: yes! it compares and giving accurate result . how to make it efficient ?
comment on: http://stackoverflow.com/a/51200342
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/89357980
type: AnswerComment
has text: So when I run pyi-makespec I can check the spec file in folder and see that new path to dependencies has been added but then when I run pyinstaller scriptname.py the spec file is overwritten and so the dependency path is lost.
comment on: http://stackoverflow.com/a/51177430
type: Comment
score: 0

http://stackoverflow.com/a/51316432
answers question: http://stackoverflow.com/q/51316333
accepted answer of: http://stackoverflow.com/q/51316333
has comment: http://stackoverflow.com/comment/89609210
has comment: http://stackoverflow.com/comment/89609322
has comment: http://stackoverflow.com/comment/89609590
has body: I am not sure what you really want but try doing this: l=[] for Pr in range(150,370,20): for Te in range(250,320,10): maxvGuess = np.array([0.04]) y = fsolve(F_vol, maxvGuess, Pr)*1000 forphp = pd.Series({'Volume': str(y).lstrip('[').rstrip(']'), 'Pressure': Pr, 'Temperature': Te}) l.append(dict(forphp)) jsonobj = json.dumps(l) print (jsonobj)
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89609580
type: Answer

http://stackoverflow.com/comment/89388312
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51192145
has text: Can you please post one complete response, and what you want?
score: 0

http://stackoverflow.com/comment/89334481
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51172867
has text: You can *only* apply SSIM to two images, so you have to reshape the 784-input to [28, 28, 1]. And please do [not forget](https://stackoverflow.com/help/someone-answers)
score: 0

http://stackoverflow.com/comment/89373747
comment on: http://stackoverflow.com/a/51193905
has text: Nice! This is the only solution that matches the intended idx's.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/89373895
type: Comment
type: QuestionComment
has text: Are they all the same size ?
score: 0
comment on: http://stackoverflow.com/q/51196028

http://stackoverflow.com/q/51250110
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/51250486
upvote count: 2
tagged with: python
tagged with: dictionary
score: 2
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/42176498
type: Question
has title: Find Excel/CSV File's Actual Column References- Python Pandas
has answer: http://stackoverflow.com/a/51250486
answer count: 2
accepted answer: http://stackoverflow.com/a/51250556
tagged with: dataframe
has comment: http://stackoverflow.com/comment/89479351
has answer: http://stackoverflow.com/a/51250556
tagged with: pandas
has body: Let say I have an excel sheet like this, If I read this file in pandas, I can get Column1, Column2, Column3 as headers. However, I want to know/create an output possibly a dictionary that is like this, {Column1: 'A', Column2: 'B', Column3: 'C'} The reason is I have another dictionary from master mapping file (that already had the references for each column done manually) that has all the references to each Column like this, {Column1: 'A', Column2: 'B', Column3: 'C', Column4: 'D'} This way, I can cross check keys and values and then if there is any mismatch, I can identify those mismatches. How can I get the original column name such as A for Column1 etc.. while reading a file into pandas?? Any ideas??
downvote count: 0
favorite count: 0

http://stackoverflow.com/comment/89440447
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51230457
has text: My code is very complicated and it is called occasionally. Since Python has a lot of tricks, I though it would be great idea to ask the community and expect some good advice or warnings rather than a "yes" or "no".
score: 0

http://stackoverflow.com/q/51221846
has answer: http://stackoverflow.com/a/51222749
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89424357
tagged with: installation
score: 0
tagged with: pip
type: Question
has title: Pip cannot find a Version that satistfies the Requirement XX, (beatifulsoup4)
has body: I use macOS and python 2.7. When I try 'pip install beautifulsoup4' I get back: Collecting beautifulsoup4 Could not find a version that satisfies the requirement beautifulsoup4 (from versions: ) No matching distribution found for beautifulsoup4 also: You are using pip version 7.1.2, however version 10.0.1 is available. You should consider upgrading via the 'pip install --upgrade pip' command. If I try to upgrade I get back that requirments are already up-to-date. How can install beatifulsoup4?
answer count: 1

http://stackoverflow.com/comment/89402680
type: Comment
comment on: http://stackoverflow.com/a/51208861
has text: That's what I was trying actually and just like my original try, at times it succeeds to click and other times it doesn't
type: AnswerComment
score: 0

http://stackoverflow.com/comment/89872632
type: Comment
type: QuestionComment
has text: The error tells you exactly what is wrong: it's looking for a driver called `'ODBC Driver 13 for SQL Server'`, but: `file not found` it can't find a file with that name. I'd suggest you Google the error, and also consult the documentation for the type of database you're trying to connect to. Also to point out, the Port# is mentioned twice. (Details matter!) Another good resource for connection strings: **https://www.connectionstrings.com/**
comment on: http://stackoverflow.com/q/51182199
score: 0

http://stackoverflow.com/comment/89368948
type: Comment
type: QuestionComment
has text: It is dumb, make no sense. But, it make sense if you really think : )
comment on: http://stackoverflow.com/q/51192310
score: 0

http://stackoverflow.com/comment/89658401
comment on: http://stackoverflow.com/a/51308418
type: Comment
has text: Thanks again. So, will the list have two signs inside it? The first half of the list would be the signal obtained by one channel and the other half of the list will be the another signal?
score: 0
type: AnswerComment

http://stackoverflow.com/comment/89488917
score: 0
comment on: http://stackoverflow.com/q/51254627
type: Comment
type: QuestionComment
has text: As I said in the first place,I think `where pip` is how you get the location of `pip.exe`. Also, given that you didn't read that, let me ask this again as well: After removing 3.6 from your `PATH`, did you start a new command prompt window?

http://stackoverflow.com/comment/96829247
has text: It is not clear what exactly is your question, the information you provide is not sufficient. What leads you to conclude the thread is blocked? I would suggest adding print statements and/or using a thread-aware debugger to track the problem down. Such as the excellent debugger built-in to PyCharm.
score: 3
comment on: http://stackoverflow.com/q/51234994
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89366621
score: 0
comment on: http://stackoverflow.com/q/51192220
type: Comment
type: QuestionComment
has text: Yes that's right @jkm . But the values must be higher or not? like 0.80 , 0.20 no?

http://stackoverflow.com/q/51264488
has answer: http://stackoverflow.com/a/51445970
tagged with: flask-sqlalchemy
score: 0
tagged with: python
has body: I'm trying to apply the recipe described here: http://alexmic.net/flask-sqlalchemy-pytest/ to use pytest to test an application using Flask-SQLAlchemy. In the section Writing tests, it is stated: Notice that we are free to commit the session as we would do normally. This is achieved because the session “joins” the external transaction created by the connection we explicitly created in the session fixture, hence only the outermost BEGIN/COMMIT pair has any effect. But this does not work for me when if I use the session.add method in my test. It works however when I'm using session.execute instead. Here is an example which shows the issue: database.py from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy() models.py from database import db class Employee(db.Model): __tablename__ = "employee" id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String, nullable=False) test_employee.py from models import Employee def test_employee(session): my_employee = Employee() my_employee.name = "Toto" session.add(my_employee) # session.execute("INSERT INTO employee (id, name) VALUES (1, 'Tata');") session.commit() conftest.py (Slightly adapted from the example) import os import pytest from flask import Flask from database import db as _db TESTDB = 'test_utte.db' TESTDB_PATH = "/tmp/{}".format(TESTDB) TEST_DATABASE_URI = 'sqlite:///' + TESTDB_PATH @pytest.fixture(scope='session') def app(request): """Session-wide test `Flask` application.""" settings_override = { 'TESTING': True, 'SQLALCHEMY_DATABASE_URI': TEST_DATABASE_URI, 'SQLALCHEMY_TRACK_MODIFICATIONS': False # Disabled to remove warning } app = Flask(__name__) app.config.update(settings_override) # Establish an application context before running the tests. ctx = app.app_context() ctx.push() def teardown(): ctx.pop() request.addfinalizer(teardown) return app @pytest.fixture(scope='session') def db(app, request): """Session-wide test database.""" if os.path.exists(TESTDB_PATH): os.unlink(TESTDB_PATH) def teardown(…
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51445970
has title: Different behaviour of Flask-SQLAlchemy transaction rollback using session.add or session.execute
type: Question
tagged with: pytest
tagged with: sqlalchemy
answer count: 2
possible better answer: http://stackoverflow.com/a/51433996
has answer: http://stackoverflow.com/a/51433996

http://stackoverflow.com/q/51183947
answer count: 1
upvote count: 6
favorite count: 0
has body: Why does json.dumps() encode emojis into unicode? See code and output below: import json obj = {"key": "hello "} print(obj) {'key': 'hello '} print(json.dumps(obj)) '{"key": "hello \ud83d\ude00"}' I have tried print(json.dumps(obj)).encode('utf-8') and some variants (.decode()...) but it didn't change the output much. Im working on Python 3.6.1
score: 6
tagged with: python
linked to: http://stackoverflow.com/q/4184108
has comment: http://stackoverflow.com/comment/89368679
has comment: http://stackoverflow.com/comment/89388775
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/25707222
has answer: http://stackoverflow.com/a/51183984
duplicate of: http://stackoverflow.com/q/4184108
has comment: http://stackoverflow.com/comment/89350023
tagged with: python-unicode
accepted answer: http://stackoverflow.com/a/51183984
has title: Python json.dumps() doesn't encode emojis properly
type: Question
has comment: http://stackoverflow.com/comment/89349743
has comment: http://stackoverflow.com/comment/89404256
has comment: http://stackoverflow.com/comment/89349627
downvote count: 0
tagged with: unicode

http://stackoverflow.com/comment/89434253
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51226727
has text: Thank you for the reply. What said does make sense but not in the context of my problem. As stated the values of x can vary, therefore I simply can't just state the index where the match is found.
type: AnswerComment

http://stackoverflow.com/q/51257312
has body: I have a folder (A) that is structured like this: A\b A\c A\d I would like to copy folder b, c, and d one level down 3 times like this: A\b\b1\b2\b3 A\c\c1\c2\c3 A\d\d1\d2\d3 Where b1,b2, and b3 are copies of the folder b, the same goes for c and d. When I run the code below I end up with the desired structure but also adds three copies in each sub-folder so A\b\b1 has b1,b2, and b3 folders. The problem has to do with the loop but I can't pinpoint it import os import sys import shutil list1= [1,2,3] path = "C:\ladg\oner" root, dirs, files = os.walk(path).next() for dir in dirs: for i in list1: new_folder_path = os.path.join(root,dir, dir+ str(i)) shutil.copytree(os.path.join(root, dir), new_folder_path)
tagged with: python
tagged with: shutil
has answer: http://stackoverflow.com/a/51257538
has title: os.walk one level down
linked to: http://stackoverflow.com/q/2422798
upvote count: 1
downvote count: 1
tagged with: os.walk
type: Question
tagged with: python-os
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51257538
answer count: 2
possible better answer: http://stackoverflow.com/a/51257566
favorite count: 0
score: 0
has answer: http://stackoverflow.com/a/51257566
has comment: http://stackoverflow.com/comment/89493484

http://stackoverflow.com/q/51213202
has body: Let us say I have a Dataframe which has a column Quality, with values [Poor, Average, Good, Excellent]. The frame has 120 values out of which 20 are NaN and the rest 100 have 20, 30, 40, 10 each of [Poor, Average, Good, Excellent]. Is there any easy way to replace the 20 NaN rows with values from [Poor, Average, Good, Excellent] such that the proportion of the overall frame remains at 20% Poor, 30% Average, 40% Good and 10% Excellent, using Python, Pandas and NumPy? The idea is to retain the original proportion after filling the NaN irrespective of the size of the dataset.
favorite count: 0
accepted answer: http://stackoverflow.com/a/51214104
tagged with: python
score: -2
type: AnsweredQuestion
has title: Replace NaN with existing values proportionately
downvote count: 2
has comment: http://stackoverflow.com/comment/89408302
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/51214104
has comment: http://stackoverflow.com/comment/89412615
tagged with: dataframe
tagged with: pandas
upvote count: 0
answer count: 1

http://stackoverflow.com/q/51265809
has title: tensorflow save/restore queue
score: 0
tagged with: tensorflow
type: UnansweredQuestion
has body: How can I use a saved graph to make a prediction when the graph is feed from a queue? This is how I define the graph and the enqueue/ dequeue: X_placeholder = tf.placeholder(tf.int32, [None, FLAGS.max_words], name="X_placeholder") Y_placeholder = tf.placeholder(tf.int32, [None, output_classes], name="Y_placeholder") q = tf.FIFOQueue(capacity=1000, dtypes=[tf.int32, tf.int32]) enqueue_op = q.enqueue_many([X_placeholder, Y_placeholder], name="enque_op") X, Y = q.dequeue() ....... This is how I run the enqueue and training: with tf.Session() as sess: sess.run(tf.global_variables_initializer()) coord = tf.train.Coordinator() threads = tf.train.start_queue_runners(coord=coord) sess.run(enqueue_op, feed_dict={X_placeholder: X_array, Y_placeholder: Y_array}) for i in range(100): sess.run(optimize, feed_dict=feed) coord.request_stop() coord.join(threads) And this is how I save the graph: saver = tf.train.Saver() saver.save(sess, checkpoint_path) gd = sess.graph.as_graph_def() converted_graph_def = graph_util.convert_variables_to_constants(sess, gd, ["prediction"]) tf.train.write_graph(converted_graph_def, FLAGS.export_dir, 'model' + s + '.pb', as_text=False) How can I run the enqueue op after importing this graph? I tried restoring the queue tensor but I can't call "q.enqueue_many" on it. q = graph.get_tensor_by_name('queue/fifo_queue:0')
tagged with: queue
answer count: 1
has answer: http://stackoverflow.com/a/51266377
type: Question
tagged with: python

http://stackoverflow.com/q/51271647
favorite count: 0
tagged with: python-3.x
upvote count: 5
tagged with: circleci
tagged with: python
has answer: http://stackoverflow.com/a/51306900
accepted answer: http://stackoverflow.com/a/51306900
linked to: http://stackoverflow.com/q/49028611
linked to: http://stackoverflow.com/q/50155464
type: AnsweredQuestion
downvote count: 0
tagged with: pytest
has comment: http://stackoverflow.com/comment/89527467
type: Question
score: 5
has title: ImportError - tests failing on CircleCI but pass locally
has comment: http://stackoverflow.com/comment/89523478
answer count: 1
has body: Exactly as title says - my folder structure is something like this: venv/ __init__.py .circleci/ config.yml Dockerfile docker-compose.yml config.py requirements.txt src/ __init__.py other_scripts.py tests/ __init__.py test_a.py test_b.py the test files have a from config import * line. Running $ pytest from the root directory locally or through a bash shell into the container (inside a virtualenv) works as expected, but on CircleCI the build fails with an ImportError: No module named 'config' for the above line of code. I'm using python3.5 and circleCI 2.0. Thanks in advance!

http://stackoverflow.com/q/51296431
tagged with: pandas-groupby
tagged with: pandas
accepted answer: http://stackoverflow.com/a/51297632
tagged with: python
tagged with: pandas-apply
downvote count: 0
has answer: http://stackoverflow.com/a/51297632
has body: This is similar to the following, however I wanted to take it one question further: pandas groupby apply on multiple columns to generate a new column I have this dataframe: Group Value Part Ratio 0 A 6373 10 0.637300 1 A 2512 10 0.251200 2 A 603 10 0.060300 3 A 512 10 0.051200 4 B 5200 20 0.472727 5 B 4800 20 0.436364 6 B 501 20 0.045545 7 B 499 20 0.045364 And this function that uses BOTH the 'Ratio' and 'Part' column that I'd like to apply to each 'Group': def allocation(df, ratio, part): k = df[part].max() frac, results = np.array(np.modf(k * df[ratio])) remainder = int(k - results.sum()) indices = np.argsort(frac)[::-1] results[indices[0:remainder]] += 1 return results.astype(int) Notice that the difference between my function and the function shown in the question I referred to at the top is that my function returns an array of values for the whole group instead of a single value. I tried the following: data.groupby('Group', group_keys=False).apply(allocation, ratio='Ratio', part='Part') Out[67]: Group A [6, 2, 1, 1] B [9, 9, 1, 1] dtype: object These numbers are correct. However, I need the output to be a series that I can assign back into the original dataframe, so that it would look something like this: Group Value Part Ratio Allocate 0 A 6373 10 0.637300 6 1 A 2512 10 0.251200 2 2 A 603 10 0.060300 1 3 A 512 10 0.051200 1 4 B 5200 20 0.472727 9 5 B 4800 20 0.436364 9 6 B 501 20 0.045545 1 7 B 499 20 0.045364 1 How would I go about doing this? Is using apply the correct approach?
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/51296474
tagged with: group-by
type: Question
linked to: http://stackoverflow.com/q/47227280
has title: Pandas groupby function using multiple columns
answer count: 2
favorite count: 0
upvote count: 3
possible better answer: http://stackoverflow.com/a/51296474

http://stackoverflow.com/q/51238106
score: 1
has title: Searching for multiple minimums in a dictionary of tuples
type: Question
has answer: http://stackoverflow.com/a/51238124
tagged with: min
upvote count: 1
has body: I have a dictionary of 2-element-tuples as values: d = {key0:(x0,y0), key1:(x1,y1),...,keyn:(xn,yn)} How may I find the key with the smallest x value? If there were repeated x values, I need the key which tuple has the smallest y value. Example 1: INPUT: d = {key1:(3,9), key2:(2,5), key3:(8,1)} OUTPUT: key2 Example 2: INPUT: d = {key1:(3,9), key2:(2,5), key3:(8,1), key4:(2,1)} OUTPUT: key4
answer count: 1
favorite count: 0
tagged with: tuples
type: UnansweredQuestion
tagged with: python
tagged with: dictionary
downvote count: 0

http://stackoverflow.com/q/51253619
score: 3
has answer: http://stackoverflow.com/a/52194625
linked to: http://stackoverflow.com/q/33982143
has comment: http://stackoverflow.com/comment/89487166
has comment: http://stackoverflow.com/comment/89522129
has comment: http://stackoverflow.com/comment/89518694
linked to: http://stackoverflow.com/q/38972250
answer count: 3
has comment: http://stackoverflow.com/comment/89487012
tagged with: api
downvote count: 0
tagged with: static-analysis
favorite count: 0
has answer: http://stackoverflow.com/a/51672839
tagged with: android
tagged with: apk
tagged with: python
has comment: http://stackoverflow.com/comment/89487049
has body: Using Python, I am trying to extract the API calls that an Android application makes, given it's .apk file. Is there a way to parse/extract names of the APIs used by a package through static analysis of its APK? Here's what I've tried/discovered so far.... I have seen this question posted before but haven't been able to follow the (very limited) answers to a working solution. I know there are some tools such as Cartographer that accomplish this among other things, but I haven't been able to get the relevant portions of the code working. Another tool CHABADA can do it but is not open-source. I have been able to get some other information from APKs, such as the external classes using Androguard, the components of the AndroidManifest.xml file using APK Static Analyzer, and using Apktool, I can decode the manifest into a readable format and also get the smali files. Another previous post asks about parsing the smali files for APIs, from lines like the follwing: invoke-virtual {p0, v0}, Landroid/net/ConnectivityManager;-&gt;getNetworkInfo(I)Landroid/net/NetworkInfo; but this doesn't appear to be a useful method since invoke-virtual or invoke-direct do not always indicate API usage, and parsing the smali files is a heavier task than if there were some way to just extract the called APIs by statically-analyzing the APK itself. Dexlib2 has also been recommended but I don't see where it can extract API calls, and it's all in Java whereas I've been working in Python. The tool API Key detector is giving me the API Keys used, but I don't know how to get the API names from this. Any solutions? Update #1 I've used Androguard to generate CFG's in the .gexf format as per @ShirishSingh, which can give me nodes in the form: &lt;node id="0" label="Landroid/support/v4/widget/SearchViewCompatHoneycomb; newOnQueryTextListener (Landroid/support/v4/widget/SearchViewCompatHoneycomb$OnQueryTextListenerCompatBridge;)Ljava/lang/Object;"&gt; &lt;attvalues&gt; &lt;attvalue id="1" value="Landroid…
has comment: http://stackoverflow.com/comment/89486817
has comment: http://stackoverflow.com/comment/89487471
upvote count: 3
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/58445517
has comment: http://stackoverflow.com/comment/89487289
has title: How can I extract API calls from an APK file?
type: Question

http://stackoverflow.com/a/51320624
type: Answer
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/51319105
has body: Let's take a step back and evaluate the intended goal of your code. You want it to basically parse the contents of an email file, and then write contents that are in text/plain format from line 7 and beyond. Therefore, we can safely assume that we are dealing with string types. Now, your implementation uses a temporary file as a middleman for getting lines 7+. However, you can actually skip the usage of the temporary file by parsing the string itself and grabbing lines 7+. Simply split the string by \n, the newline escape sequence, and then rebuild the string from lines 7+. Let's assume the contents of your email part is: &gt;&gt;&gt; mystr = "This is\na message\nwith\nmultiple\nlines\nin the\nstring.\n\nEnd of file" If I print this, it will show: &gt;&gt;&gt; print(mystr) This is a message with multiple lines in the string. End of file You can simply split the string now, splitting by \n, which returns a list where each element represents a line. From there, you can just grab lines from 7 and beyond, and rejoin the elements with a \n. &gt;&gt;&gt; mystr_split = mystr.split('\n') &gt;&gt;&gt; mystr_split ['This is', 'a message', 'with', 'multiple', 'lines', 'in the', 'string.', '', 'End of file'] &gt;&gt;&gt; to_write = '\n'.join(mystr_split[6:]) &gt;&gt;&gt; to_write 'string.\n\nEnd of file' &gt;&gt;&gt; print(to_write) string. End of file So, back to your question, you can simply parse the text/plain content of your email, and just write lines 7+ into one file without using a temporary file. for part in email_message.walk(): if part.get_content_type() == 'text/plain': body = part.get_payload(decode=True) save_string = r'C:/Email/file.txt' body_split = body.split('\n') to_write = '\n'.join(body_split[6:]) with open(save_string, 'w') as f: f.write(to_write)
upvote count: 1

http://stackoverflow.com/comment/89449026
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51234986
has text: your solution with `sp.Popen()` is working. Thank you very much :)

http://stackoverflow.com/comment/89625797
has text: That error indicates that the actual dataframes you're using are very different from the example, to the point that this is not a usefully phrased question. For instance my answer which someone (you)? downvoted does give the correct answer for the sample you have posted.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51314302
type: Comment

http://stackoverflow.com/comment/89343439
score: 0
type: Comment
has text: @QianLi that is a different problem, maybe ask another question?
type: AnswerComment
comment on: http://stackoverflow.com/a/51180392

http://stackoverflow.com/comment/118328692
has text: Oh, I made it after I finished the 25.6GB update of this game...
type: Comment
comment on: http://stackoverflow.com/a/51225121
score: 1
type: AnswerComment

http://stackoverflow.com/comment/89475935
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51248455
type: Comment
has text: Note that the same might be necessary for the outer element as well, since there is a global list wrapper as well.

http://stackoverflow.com/comment/89636207
comment on: http://stackoverflow.com/q/51316688
type: Comment
type: QuestionComment
has text: Graham - thank you so much for all the help! I learned a lot in this process and really appreciate your efforts to maintain mod-wsgi!
score: 0

http://stackoverflow.com/comment/89434153
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51225589
score: 1
has text: Possible duplicate of [Load a tiff stack in a numpy array with python](https://stackoverflow.com/questions/37722139/load-a-tiff-stack-in-a-numpy-array-with-python)

http://stackoverflow.com/a/51533597
type: Answer
answers question: http://stackoverflow.com/q/51255947
score: 0
has body: Can you delete your old virtualenv C:\Users\danie01\.virtualenvs Check the version of python inside Pipfile [requires] python_version = "3.5" After go to your project to create again your virtualenv cd C:\Users\danie01\fox\test\robotframework pipenv install

http://stackoverflow.com/q/51262857
tagged with: python
tagged with: ibm-watson
has answer: http://stackoverflow.com/a/51263097
tagged with: http://stackoverflow.com/tag/json
upvote count: 1
answer count: 1
has body: I'm using IBM Watson and python3 to translate an audio file into a text file. It returns the results in a JSON-format. The resulting JSON is like this... { "results": [ { "alternatives": [ { "transcript": "Marcus white is the managing director of quartz power group an energy company ", "confidence": 0.85, "word_confidence": [ [ "Marcus", 0.678 ], [ "white", 0.99 ], [ "is", 0.988 ], [ "the", 1.0 ], [ "managing", 1.0 ], [ "director", 1.0 ], [ "of", 1.0 ], [ "quartz", 0.394 ], [ "power", 0.737 ], [ "group", 0.968 ], [ "an", 0.783 ], [ "energy", 0.989 ], [ "company", 0.844 ] ], "timestamps": [ [ "Marcus", 12.28, 12.78 ], [ "white", 12.78, 13.17 ], [ "is", 13.17, 13.33 ], [ "the", 13.33, 13.42 ], [ "managing", 13.42, 13.83 ], [ "director", 13.83, 14.39 ], [ "of", 14.39, 14.52 ], [ "quartz", 14.52, 15.0 ], [ "power", 15.0, 15.36 ], [ "group", 15.36, 15.79 ], [ "an", 15.93, 16.08 ], [ "energy", 16.08, 16.45 ], [ "company", 16.45, 16.95 ] ] } ], "final": true }, { "alternatives": [ { "transcript": "every month the departmental manages meet to discuss high level issues in the company ", "confidence": 0.925, "word_confidence": [ [ "every", 1.0 ], [ "month", 0.993 ], [ "the", 0.728 ], [ "departmental", 1.0 ], [ "manages", 0.7 ], [ "meet", 0.77 ], [ "to", 1.0 ], [ "discuss", 1.0 ], [ "high", 0.835 ], [ "level", 0.984 ], [ "issues", 1.0 ], [ "in", 0.67 ], [ "the", 0.927 ], [ "company", 0.994 ] ], "timestamps": [ [ "every", 18.1, 18.39 ], [ "month", 18.39, 18.93 ], [ "the", 18.96, 19.07 ], [ "departmental", 19.07, 19.73 ], [ "manages", 19.73, 20.29 ], [ "meet", 20.29, 20.56 ], [ "to", 20.56, 20.66 ], [ "discuss", 20.66, 21.12 ], [ "high", 21.12, 21.33 ], [ "level", 21.33, 21.64 ], [ "issues", 21.64, 22.08 ], [ "in", 22.08, 22.18 ], [ "the", 22.18, 22.27 ], [ "company", 22.27, 22.75 ] ] } ], "final": true }, This format repeats itself for each translated segment. I'm trying to extract all transcriptions, that is the value for transcript. I tried this: index = 0 for [index]["transc…
accepted answer: http://stackoverflow.com/a/51263097
type: AnsweredQuestion
downvote count: 0
has title: Extracting nested items in JSON file with Python
score: 1
favorite count: 0
tagged with: python-3.x
type: Question

http://stackoverflow.com/q/51191820
has body: Hi I am new to Django and web development. I want to use the data in my model in order to do some calculations in views.py. What is the syntax required in views to access the data fields which is in the model?
favorite count: 0
has comment: http://stackoverflow.com/comment/89377481
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89365263
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/51192044
type: Question
has comment: http://stackoverflow.com/comment/89365206
score: -2
tagged with: django-models
has comment: http://stackoverflow.com/comment/89367614
has title: How to access fields in model in view?
downvote count: 3
upvote count: 1
answer count: 1

http://stackoverflow.com/q/51208399
type: Question
has title: How to slice and loop through a netCDF variable in Python?
tagged with: slice
has answer: http://stackoverflow.com/a/51212619
answer count: 1
tagged with: variables
favorite count: 0
has body: I have a netCDF variable with 372 time-steps, I need to slice this variable to read in each individual time-step for subsequent processing. I have used glob. to read in my 12 netCDF files and then defined the variables. NAME_files = glob.glob('RGL*nc') NAME_files = NAME_files[0:12] for n in (NAME_files): RGL = Dataset(n, mode='r') footprint = RGL.variables['fp'][:] lons = RGL.variables['lon'][:] lats = RGL.variables['lat'][:] I now need to repeat the code below in a loop for each of the 372 time-steps of the variable 'footprint'. footprint_2 = RGL.variables['fp'][:,:,1:2] I'm new to Python and have a poor grasp of looping. Any help would be appreciated, including better explanation/description of my issue.
type: UnansweredQuestion
tagged with: python
score: 0
tagged with: netcdf
tagged with: loops
upvote count: 1
downvote count: 1

http://stackoverflow.com/comment/89477854
comment on: http://stackoverflow.com/q/51249417
has text: Actually, before uninstalling anaconda for the first time, I tried this. But then again I uninstalled anaconda.
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/89361567
type: QuestionComment
has text: Do not load pylab prior to importing matplotlib. Better: do not import pylab :-)
comment on: http://stackoverflow.com/q/51186909
type: Comment
score: 0

http://stackoverflow.com/comment/89583834
has text: If you mean the absolute distance, you can double your speed by only computing half of your matrix. The other half is symmetric if you're using `abs(coords[i]-coords[j])`.
comment on: http://stackoverflow.com/q/51303551
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89598827
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51310999
has text: I'm using 0.23. No worries, I'll post a solution for that. @min2bro see edited answer
score: 0

http://stackoverflow.com/q/51201888
tagged with: vtk
tagged with: python
type: AnsweredQuestion
downvote count: 0
score: 7
accepted answer: http://stackoverflow.com/a/51371909
has title: Retrieving facets and point from VTK file in python
has body: I have a vtk file containing a 3d model, I would like to extract the point coordinates and the facets. Here is a minimal working example: import vtk import numpy from vtk.util.numpy_support import vtk_to_numpy reader = vtk.vtkPolyDataReader() reader.SetFileName('test.vtk') reader.Update() polydata = reader.GetOutput() points = polydata.GetPoints() array = points.GetData() numpy_nodes = vtk_to_numpy(array) This works as numpy_nodescontains the x,y,z coordinates of all points, but I am at loss to retrieve the list that relates the facets of this model to the corresponding points. I tried: facets= polydata.GetPolys() array = facets.GetData() numpy_nodes = vtk_to_numpy(array) But then numpy_nodes is just a 1D array where I would expect a 2D array (size 3*number of facets) where the first dimension contains the number of the corresponding points to the facet (as in a .ply file). Any advise on how to proceed would be welcome
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/51371909
has comment: http://stackoverflow.com/comment/89715852
has comment: http://stackoverflow.com/comment/89679262
upvote count: 7
answer count: 1
has comment: http://stackoverflow.com/comment/89706123
favorite count: 0

http://stackoverflow.com/q/51306780
score: 2
upvote count: 2
type: UnansweredQuestion
tagged with: pip
type: Question
tagged with: setuptools
has body: I noticed that when I do an editable install (pip install --user -e .), sometimes, setuptools make a build directory and egg-links to /.../my_module/build/lib. While sometimes (if I do it in another project), it does not create this directory and simply egg-links to /.../my_module However, I can't figure out why. In the first case, the project is not really editable (since it seems to build the package, and link to the build version) What does cause setup tools to use build/lib rather than the package dev directory ? (Note : these are full python projects that are intended to be distributed with sdist)
answer count: 2
downvote count: 0
favorite count: 0
has title: When does setuptools install editable link to /.../my_module/build/lib/ andwhen does it link to /.../my_module?
linked to: http://stackoverflow.com/q/50155219
has answer: http://stackoverflow.com/a/51307342
has answer: http://stackoverflow.com/a/51308868
tagged with: python

http://stackoverflow.com/q/51314752
tagged with: python
tagged with: plotly
has answer: http://stackoverflow.com/a/51329853
type: Question
has body: I have a data structure that is a nested dictionary called team_dict. Team_dict looks like this: team_dict[teams][players][stats]. Team_dict = {'gs': {'Steph': {'PPG':26 ,'Reb':10 'Ast':10} }} The problem I am having is that I can plot all of my data fine but i want to get the markers to be the same color for each team. I know that the reason is because i is iterated over the loop for each player. Right now my code for the scatter plot is: 'data': [ go.Scatter( x=[team_dict[i][p]['Salary']], y=[team_dict[i][p]['PPG']], text=p, mode='markers', opacity=0.7, marker={ 'size': 15, 'line': {'width': .5, 'color': 'black'} }, name= i, ) for i in team_initials for p in team_dict[i] ], Here is an image of how it looks like now: scatterplot so far I have tried looking at the dash documentation and other methods but nothing seems to work. Am I not supposed to use nested dictionaries to plot dash graphs?
tagged with: plotly-dash
score: 0
linked to: http://stackoverflow.com/q/13575090
has title: How to have individual names for each dictionary in Dash scatter's plot?
answer count: 1
type: UnansweredQuestion

http://stackoverflow.com/a/52333108
type: Answer
upvote count: 0
answers question: http://stackoverflow.com/q/51258786
score: -1
downvote count: 1
has body: Kindly use http url instead of local, It will work else upload the file first and then get the file_id then send that file id to the bot.

http://stackoverflow.com/q/51183066
tagged with: python
tagged with: regex
type: AnsweredQuestion
has body: from re import match pattern = r"(.+) \2" ＃Change "\1" to "\2" and Error raised match = match(pattern, "q q") if match: print(1) raise source.error("invalid group reference %d" % group, len(escape) - 1) sre_constants.error: invalid group reference 2 at position 6 This is from the official document but I don't understand its meaning. I tried /1 and /2. For /1, it is ok. For /2, error happened. "\number Matches the contents of the group of the same number. "
type: Question
accepted answer: http://stackoverflow.com/a/51183108
has title: What's the meaning of python regular expression “\2”
has answer: http://stackoverflow.com/a/51183108
score: 0
answer count: 1

http://stackoverflow.com/comment/89471457
comment on: http://stackoverflow.com/q/51246242
has text: What file system you are using with hadoop cluster? HDFS/S3 etc etc??
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/51227437
score: 0
answer count: 2
favorite count: 0
has title: If a car is recognized take a picture
tagged with: python
tagged with: opencv
type: AnsweredQuestion
has body: Run this code for Python and OpenCv. What i want to do, is to save in my dataset/test all the images of all the cars that the tool is detecting. Run my code with python3 car_detection y0d$ python3 build_car_dataset.py -c cars.xml -o dataset/test So when i detect the face and put the rectangle on the face, i created an if function that is saying that if the face is recognized and has the rectangle on the image, then please save the pic of that face to my desired output if rects: p = os.path.sep.join([args["output"], "{}.png".format(str(total).zfill(5))]) cv2.imwrite(p, orig) total += 1 So the error i got is: ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() What should i do? Thank you in advance! My full code is: # USAGE # python3 build_car_dataset.py --cascade haarcascade_frontalface_default.xml --output dataset/test # python3 build_face_dataset.py -c haarcascade_licence_plate_rus_16stages_original.xml -o dataset/test #python3 build_face_dataset.py -c haarcascade_licence_plate_rus_16stages_original.xml -o dataset/test #python3 build_car_dataset.py -c cars.xml -o dataset/test from imutils.video import VideoStream import argparse, imutils, time, cv2, os # construct the argument parser and parse the arguments ap = argparse.ArgumentParser() ap.add_argument("-c", "--cascade", required=True, help = "path to where the face cascade resides") ap.add_argument("-o", "--output", required=True, help="path to output directory") args = vars(ap.parse_args()) # load OpenCV's Haar cascade for face detection from disk detector = cv2.CascadeClassifier(args["cascade"]) # initialize the video stream, allow the camera sensor to warm up and initialize the total number of example faces written to disk thus far print("[INFO] starting video stream...") vs = VideoStream(src=0).start() # vs = VideoStream(usePiCamera=True).start() time.sleep(2.0) total = 0 # loop over the frames from the video stream while True: # grab the frame from the thre…
upvote count: 1
has answer: http://stackoverflow.com/a/51228160
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/51229026
possible better answer: http://stackoverflow.com/a/51228160
accepted answer: http://stackoverflow.com/a/51229026

heroku
tags question: http://stackoverflow.com/q/51257153
tags question: http://stackoverflow.com/q/51178632
tags question: http://stackoverflow.com/q/51182199
tags question: http://stackoverflow.com/q/51315151
tags question: http://stackoverflow.com/q/51233831
tags question: http://stackoverflow.com/q/51286264
tags question: http://stackoverflow.com/q/51201194
tags question: http://stackoverflow.com/q/51213444
tags question: http://stackoverflow.com/q/51189327
tags question: http://stackoverflow.com/q/51285205
tags question: http://stackoverflow.com/q/51232282
type: Tag
tags question: http://stackoverflow.com/q/51278257
tags question: http://stackoverflow.com/q/51202121
tags question: http://stackoverflow.com/q/51242735
tags question: http://stackoverflow.com/q/51250847
tags question: http://stackoverflow.com/q/51238387
tag name: heroku
tags question: http://stackoverflow.com/q/51215040

http://stackoverflow.com/q/51211452
tagged with: ttk
has title: intersect a progress bar in Tkinter
has body: Like the title says, I want to intersect a progress bar in Tkinter at some variable position. See the image for what I want to achieve, those red vertical lines that I edited into the image. The idea is to put text like "||" inside the bar and color it differently so it should look like what I want to achieve. I have seen a couple of examples with text being put into the progress bar, but it was always right in the middle of the bar which doesn't work for me. Here is the code that generates progress bars. import ttk from Tkinter import * import random master = Tk() stl = ttk.Style() stl.theme_use("winnative") stl.configure("colour.Horizontal.TProgressbar", background="lime green") for i in range(0,4): prgb = ttk.Progressbar(master, orient = "horizontal", length = 150, mode = "determinate", style = "colour.Horizontal.TProgressbar") prgb.grid(row=i, column=0, pady=10) prgb["maximum"] = 1.0 x = random.random() prgb["value"] = x master.mainloop()
tagged with: python-2.7
answer count: 1
downvote count: 0
favorite count: 0
upvote count: 2
has answer: http://stackoverflow.com/a/51211654
tagged with: python
score: 2
type: AnsweredQuestion
tagged with: tkinter
type: Question
accepted answer: http://stackoverflow.com/a/51211654

http://stackoverflow.com/comment/89526406
has text: @flameboi Consider to make another question then.
comment on: http://stackoverflow.com/a/51273523
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/89416653
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51217328
has text: It also doesn't help that `as_matrix` is deprecated

http://stackoverflow.com/comment/89604042
type: AnswerComment
score: 0
type: Comment
has text: Awesome I appreciate the help!
comment on: http://stackoverflow.com/a/51313554

http://stackoverflow.com/comment/89565213
has text: The inputs dont need to be on the file, just the printed information. IS there a way to print and write to the file, sir? Thank you, as I said im a noob :)
type: Comment
comment on: http://stackoverflow.com/a/51225461
score: 0
type: AnswerComment

http://stackoverflow.com/comment/89484991
type: Comment
comment on: http://stackoverflow.com/a/51252710
has text: Can you provide a reference to your claim "there is not pass by value in Python"? My proof, let's assume `a=5`, `b=a`, `a=7`, `print(b)` will yield to `5` because the `a=b` has been passed by value. so how come python doesn't support pass-by-value :)
type: AnswerComment
score: 0

http://stackoverflow.com/q/51227600
type: AnsweredQuestion
tagged with: recursion
has title: python recursion type errors
type: Question
possible better answer: http://stackoverflow.com/a/51227759
answer count: 2
has comment: http://stackoverflow.com/comment/89435339
has body: I'd be grateful if someone could tell me why sum_all([1,[2,[3,[4]]]]) doesn't work? It says that it can only concatenate list (not "int") to list but if my code works as I think it should that shouldn't happen. Btw my code uses recursion to sum all elements of a list regardless of whether they're an integer or another list def rec_sum(numbers): lnum = len(numbers) if lnum == 0: return 0 elif lnum == 1: return numbers[0] else: numbers[0] = numbers[-1] + numbers[0] del numbers[-1] return rec_sum(numbers) def sum_all(numbers): lnum = len(numbers) if lnum == 0: return 0 elif lnum == 1: if isinstance(numbers[0], int): return numbers[0] elif isinstance(numbers[0], list): return rec_sum(numbers[0]) else: if isinstance(numbers[-1], list) and isinstance(numbers[0], list): numbers[0] = rec_sum(numbers[0]) + rec_sum(numbers[-1]) del numbers[-1] return sum_all(numbers) elif isinstance(numbers[-1], list) and isinstance(numbers[0], int): numbers[0] = numbers[0] + rec_sum(numbers[-1]) del numbers[-1] return sum_all(numbers) elif isinstance(numbers[-1], int) and isinstance(numbers[0], list): numbers[0] = rec_sum(numbers[0]) + numbers[-1] del numbers[-1] return sum_all(numbers) elif isinstance(numbers[-1], int) and isinstance(numbers[0], int): numbers[0] = numbers[0] + numbers[-1] del numbers[-1] return sum_all(numbers) Traceback (most recent call last): File "&lt;pyshell#8&gt;", line 1, in &lt;module&gt; sum_all([1, [2, [3, [4]]]]) File "C:/Users/#/Documents/python/recursion.py", line 36, in sum_all numbers[0] = numbers[0] + rec_sum(numbers[-1]) File "C:/Users/#/Documents/python/recursion.py", line 17, in rec_sum numbers[0] = numbers[-1] + numbers[0] TypeError: can only concatenate list (not "int") to list
has answer: http://stackoverflow.com/a/51227759
tagged with: types
has comment: http://stackoverflow.com/comment/89435374
score: 0
upvote count: 1
accepted answer: http://stackoverflow.com/a/51227738
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/51227738
tagged with: python

http://stackoverflow.com/q/51272531
tagged with: machine-learning
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51272850
has comment: http://stackoverflow.com/comment/89523650
has answer: http://stackoverflow.com/a/51273488
type: Question
possible better answer: http://stackoverflow.com/a/51272850
has comment: http://stackoverflow.com/comment/89523183
answer count: 2
tagged with: neural-network
score: 0
has comment: http://stackoverflow.com/comment/89523198
accepted answer: http://stackoverflow.com/a/51273488
tagged with: pandas
has body: Converting Y to indicator matrix works fine: file = 'dataset.csv' X, Y = readFile(file) N = len(Y) T = np.zeros((N, K)) for i in range(N): T[i, Y[i]] = 1 but when I do the same thing after dividing into training and testing, like this: I get error X, Y = shuffle(X, Y) Ntrain = int(0.7*len(X)) Xtrain, Ytrain = X[:Ntrain], Y[:Ntrain] Xtest, Ytest = X[Ntrain:], Y[Ntrain:] N1 = len(Ytrain) T1 = np.zeros((N1, K)) for i in range(N1): T1[i, Ytrain[i]] = 1 It shows error on last line: T1[i, Ytrain[i]] = 1 , Where I am going wrong? K is the number of classes = 9 print(np.unique(Y)) print(np.unique(Ytrain)) The above print statements give : [0 1 2 3 4 5 6 7 8] [0 1 2 3 4 5 6 7 8]
has title: Converting labels to indicator matrix after dividing the dataset to training and testing
has comment: http://stackoverflow.com/comment/89523216
has comment: http://stackoverflow.com/comment/89523281
has comment: http://stackoverflow.com/comment/89524400
has comment: http://stackoverflow.com/comment/89523579

http://stackoverflow.com/q/51270441
has comment: http://stackoverflow.com/comment/89520493
accepted answer: http://stackoverflow.com/a/51271032
downvote count: 0
type: AnsweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/89520625
favorite count: 0
has body: I am working on a calendar (this is a school assignment) The assignment is, Given a month and the day of the week that’s the first of that month entered as arugments on the command line, write a program that prints a calendar for the month. So, if I want to print Sept and it starts on Thursday, I would enter "python calendar.py 9 5" in the command line, and get a calendar that starts september on Thursday. Here's the code: #!/usr/bin/python import sys import calendar day = int(sys.argv[1]) month = int(sys.argv[2]) cal = calendar.TextCalendar(day) print(cal.formatmonth(2018, month) The error I get is File "calendar.py", line 4, in &lt; module> import calendar File "/home/myname/calendar.py", line 5, in &lt; module> import TextCalendar ImportError: No module named TextCalendar Can someone tell me how to correct this? Thanks for any help!
type: Question
upvote count: 1
tagged with: python
answer count: 1
has title: TextCalendar Import error in Python
has comment: http://stackoverflow.com/comment/89519053
has answer: http://stackoverflow.com/a/51271032
linked to: http://stackoverflow.com/q/28223774

google-chrome
tags question: http://stackoverflow.com/q/51199026
tags question: http://stackoverflow.com/q/51220732
tags question: http://stackoverflow.com/q/51289116
tags question: http://stackoverflow.com/q/51280539
tags question: http://stackoverflow.com/q/51288093
type: Tag
tags question: http://stackoverflow.com/q/51255521
tag name: google-chrome
tags question: http://stackoverflow.com/q/51243290
tags question: http://stackoverflow.com/q/51281805

http://stackoverflow.com/comment/89464381
type: Comment
has text: So `contentdataframes = [pd.read_excel(f) for f in listoffiles]` should work
comment on: http://stackoverflow.com/a/51242754
type: AnswerComment
score: 0

http://stackoverflow.com/comment/89479919
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51249652
has text: No, unfortunately. The output was a list of all the numbers that are in the text file, so basically a list of 40 numbers.

http://stackoverflow.com/comment/89465652
comment on: http://stackoverflow.com/a/51209014
score: 0
type: AnswerComment
has text: Then convert it into a dict after reading it: `d = {x[0]: x for x in data}` to get a mapping on the left-most column. In Python, those are called [ist comprehensions](https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions). One of the most important parts to learn if you do Python.
type: Comment

http://stackoverflow.com/comment/89614219
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51319065
score: 0
has text: Most examples are in the form of finding A in data A to Z. A DB table does not have a single field from A to Z. When a DB table has several fields together, I want to know the field I'm looking for as a field value and I want to figure out another value with that field value. For example, searching for a specific name in a DB that contains information from all the students will determine the age.

http://stackoverflow.com/q/51287109
tagged with: tensorflow
type: AnsweredQuestion
score: 3
upvote count: 3
type: Question
answer count: 1
downvote count: 0
tagged with: neural-network
tagged with: training-data
has answer: http://stackoverflow.com/a/53197786
has title: Simultaneous training and testing in Tensorflow
has body: I am trying to perform training and testing of a neural network in Tensorflow in the same script, same graph, same session. I read that it is possible, however when I look at the accuracy/loss results from the training and testing ops, it seems as if both ops are just a continuation of the training process somehow. E.g. train.acc. will end the epoch at .84, then testing will start at 0.84, end at 0.87, and then training will resume with an acc. of 0.87... My code is constructed like this: 1) defining calculations for acc and loss calc_loss = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=labels, logits=logits) acc, acc_op = tf.metrics.accuracy(labels=labels, predictions=predictions) loss = tf.metrics.mean(calc_loss) 2) running the above in one and the same tf.session, e.g. for acc: acc_value, acc_op_value = sess.run([acc, acc_op], feed_dict=feed_dict_train) test_acc_value, test_acc_op_value = sess.run([acc, acc_op], feed_dict=feed_dict_test) the two dictionaries contain different data. My question is, do I need to define different ops for training and testing - is this where the training and testing get mixed up? Or is it impossible to test and train in one session? What would be a clean and simple way to go about this? A link to a code example that illustrates this would also be of help (as I am not managing to find anything that directly answers my question).
tagged with: python
favorite count: 0
accepted answer: http://stackoverflow.com/a/53197786

eclipse
tag name: eclipse
tags question: http://stackoverflow.com/q/51229714
tags question: http://stackoverflow.com/q/51314478
type: Tag

http://stackoverflow.com/q/51305516
type: Question
has body: I am trying to build an automatic cat feeder that uses flask as the server. when I go to a certain webpage on my raspberry pi, 127.0.0.1:5000/open to be exact, the servo moves without issue. On other devices on my network, the site can't be reached, so I'm assuming I didn't make it available to the local network. I'm following this tutorial. there is a dead link for the python server code so here is his github.
tagged with: flask
tagged with: portforwarding
tagged with: python-2.7
tagged with: ssh
answer count: 1
has answer: http://stackoverflow.com/a/51306953
linked to: http://stackoverflow.com/q/7023052
has title: Flask Server running only on localhost
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/7023052
tagged with: python
score: 0

communication
tag name: communication
tags question: http://stackoverflow.com/q/51245263
type: Tag

http://stackoverflow.com/comment/89625495
type: AnswerComment
type: Comment
has text: Thanks. It works in Python 2.7 too. But you're right that passing a list to it wouldn't work because this solution relies on using set to eliminate duplicates, and a sequence needs to be hashable in order to be added to a set, which a list is not. You can always cast the list to a tuple before passing in though.
comment on: http://stackoverflow.com/a/51218926
score: 0

http://stackoverflow.com/q/51234279
has comment: http://stackoverflow.com/comment/89447653
has answer: http://stackoverflow.com/a/51267302
upvote count: 0
has title: Is there difference for adding the 'raise' statement or not?
has body: import sys try: f = open('myile.txt') s = f.readline() i = int(s.strip()) except OSError as err: print("OS Error: {0}".format(err)) except ValueError: print("Not integer") except: print("Unexpected Error:", sys.exc_info()[0]) # raise I found there is the same result with/without the raise statement. Could anyone can tell me the difference, please? Thanks.
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/89498432
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89512719
has comment: http://stackoverflow.com/comment/89491392
downvote count: 2
type: Question
score: -2

http://stackoverflow.com/q/51293326
has comment: http://stackoverflow.com/comment/89565153
type: Question
has title: Breaking up a with statement
has body: Originally, I have been opening and simultaneously reading through two files with something like this: with open(file1, 'r') as R1: with open(file2, 'r') as R2: ### my code But now the input file names may sometimes be gzipped. So, I thought to split up the with statement and use an if statement to handle the two scenarios with something like this: if zipped: R1 = gzip.open(file1, 'r') R2 = gzip.open(file2, 'r') else: R1 = open(file1, 'r') R2 = open(file2, 'r') with R1: with R2: ### my code Does the second code function like the first? Or is there even a better way to do this?
has comment: http://stackoverflow.com/comment/89565277
score: 4
has comment: http://stackoverflow.com/comment/89564224
has comment: http://stackoverflow.com/comment/89565095
has comment: http://stackoverflow.com/comment/89565101
has comment: http://stackoverflow.com/comment/89565508
answer count: 3
has answer: http://stackoverflow.com/a/51293691
has answer: http://stackoverflow.com/a/51293589
has answer: http://stackoverflow.com/a/51293748
accepted answer: http://stackoverflow.com/a/51293748
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/89564835
upvote count: 4
type: AnsweredQuestion
downvote count: 0
possible better answer: http://stackoverflow.com/a/51293691

http://stackoverflow.com/comment/89443919
type: QuestionComment
has text: Please reduce your code to a *minimal example*. We don't need this much code.
score: 0
comment on: http://stackoverflow.com/q/51232412
type: Comment

http://stackoverflow.com/comment/89491128
has text: Thanks for your solution. Can you show me a bit of code for the "extending or create your own user model and extend all your models from it", please?
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/51256050
type: Comment

http://stackoverflow.com/a/55178863
downvote count: 0
has body: SerialGroup expects string not Connection so you need import fabric pool = fabric.group.SerialGroup("192.168.3.151", "192.168.3.123", user="pi", port=22, connect_kwargs={"password": "Raspberry"}) pool.run("touch /home/pi/Desktop/new_file65.txt") pool.close() print("hi") You can also use login@host if you need different users. But you can't use different passwords. pool = fabric.group.SerialGroup("pi@192.168.3.151", "pi@192.168.3.123", port=22, connect_kwargs={"password": "Raspberry"}) Documentation: http://docs.fabfile.org/en/2.4/api/group.html#fabric.group.SerialGroup
type: Answer
answers question: http://stackoverflow.com/q/51252054
score: 1
upvote count: 1

http://stackoverflow.com/comment/89502046
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51261969
has text: There's no concept of pointers on python (at least within my limited knowledge).
score: 1

http://stackoverflow.com/a/51170102
type: Answer
answers question: http://stackoverflow.com/q/51170065
accepted answer of: http://stackoverflow.com/q/51170065
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer
has body: foo.objects.filter(type='c').latest('date_added')

http://stackoverflow.com/a/51241485
accepted answer of: http://stackoverflow.com/q/51170941
score: 1
has body: Disclaimer: I'm the author of Pykka. Aside: Pykka isn't dead, it just works quite well for what it was made for: providing an concurrency abstraction for the Mopidy music server and its 100+ extensions. Pykka's behavior with properties isn't optimal, but there's a reason it is the way it is. To create a proxy object Pykka must introspect the API of the target object. When testing if the attributes available on the target object are callables, attributes, or "traversible attributes", getattr() is called once on each attribute. This causes the property getter to be called. See Proxy._get_attributes() and Actor._get_attribute_from_path() for . As there is no way in Python to capture a return value from a property setter, property setting on Pykka proxy takes the safe default of waiting on the setter to complete so that any exceptions raised in the setter can be reraised on the call site in mainThread(). The alternative would be to leave any exceptions raised by property setters unhandled. See Proxy.__setattr__() for details. In summary, properties "works" with Pykka, but you get more control by using method calls, as you then always get a future back and can decide yourself if you need to wait for the result or not. Whether you are using Pykka or not, I find it good practice to not do any expensive work in property getters, but instead use proper methods to do "expensive" work. API design directly affects how your users will use the API: An object with a property invites to repeated use of the same property, and thus repeated recalculation. Keep properties dead simple and cheap. An object exposing a method returning a result will usually lead to a caller to keep the result in a variable and reuse the same result instead of calling the method multiple times. Use methods for any non-trivial work. If it is really expensive, consider another prefix than get_, for example load_, fetch_, or calculate_, further indicating that the user should keep a handle on the result and r…
has comment: http://stackoverflow.com/comment/89559176
upvote count: 1
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/105296192
type: Answer
answers question: http://stackoverflow.com/q/51170941

http://stackoverflow.com/comment/89567048
has text: For sending post requests, I'm using python requests module, for get requests I usually use browser. What configuration would be helpful to you?
type: Comment
score: 0
comment on: http://stackoverflow.com/q/51294340
type: QuestionComment

http://stackoverflow.com/a/51314876
score: 0
type: Answer
has body: Why does it happen that sometimes ORDER BY does not work as expected? Given standard SQL, the results of your query are indeterminate, so it is not very valuable to know why it works most of the time and fails rarely. There are two things that make the results vary: Generally you should not rely on the order of rows of a subquery in enclosing queries, even if you apply an ordering. Some database implementations may have additional guarantees, but on others for example optimizers may deem the ORDER BY unnecessary – which MySQL 5.7 and up does, it removes the subquery entirely. Usually databases, such as SQLite and MySQL1, that allow selecting non-aggregate items that are not functionally dependent on, or are not named in the GROUP BY clause, leave it unspecified from which row in the group the values are taken: SQLite: ... Otherwise, it is evaluated against a single arbitrarily chosen row from within the group. If there is more than one non-aggregate expression in the result-set, then all such expressions are evaluated for the same row. MySQL: ... In this case, the server is free to choose any value from each group, so unless they are the same, the values chosen are nondeterministic, which is probably not what you want. Furthermore, the selection of values from each group cannot be influenced by adding an ORDER BY clause. Trying out the query on SQLite failed the assertion on this machine, while on MySQL it passed. This is probably due to implementation of selecting the row from within the group, but you should not rely on such details. What you seem to be after is a greatest-n-per-group query, or top-1. Not knowing which database you are using here's a somewhat generic way to do just that using an EXISTS subquery expression: renew_alias = db.aliased(OrderEntryVacancyRenew) renew_vacancies = db.session.query(OrderEntryVacancyRenew).\ join(OrderEntryVacancyRenew.vacancy).\ options( load_only('remaining'), contains_eager(OrderEntryVacancyRenew.vacancy).load_only('renew…
answers question: http://stackoverflow.com/q/51296437

http://stackoverflow.com/a/51305721
type: Answer
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/89638225
has comment: http://stackoverflow.com/comment/89613459
answers question: http://stackoverflow.com/q/51244854
has body: The problem is that the gzip module unzips the whole file at once, storing the uncompressed file in memory. For a file this large, the more practical approach is to uncompress the file a little bit at a time, streaming the results. #!/usr/bin/env python3 import io import zlib def stream_unzipped_bytes(filename): """ Generator function, reads gzip file `filename` and yields uncompressed bytes. This function answers your original question, how to read the file, but its output is a generator of bytes so there's another function below to stream these bytes as text, one line at a time. """ with open(filename, 'rb') as f: wbits = zlib.MAX_WBITS | 16 # 16 requires gzip header/trailer decompressor = zlib.decompressobj(wbits) fbytes = f.read(16384) while fbytes: yield decompressor.decompress(decompressor.unconsumed_tail + fbytes) fbytes = f.read(16384) def stream_text_lines(gen): """ Generator wrapper function, `gen` is a bytes generator. Yields one line of text at a time. """ try: buf = next(gen) while buf: lines = buf.splitlines(keepends=True) # yield all but the last line, because this may still be incomplete # and waiting for more data from gen for line in lines[:-1]: yield line.decode() # set buf to end of prior data, plus next from the generator. # do this in two separate calls in case gen is done iterating, # so the last output is not lost. buf = lines[-1] buf += next(gen) except StopIteration: # yield the final data if buf: yield buf.decode() # Sample usage, using the stream_text_lines generator to stream # one line of RDF text at a time bytes_generator = (x for x in stream_unzipped_bytes('freebase-rdf-latest.gz')) for line in stream_text_lines(bytes_generator): # do something with `line` of text print(line, end='')
accepted answer of: http://stackoverflow.com/q/51244854
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/89538240
score: 0
type: AnswerComment
type: Comment
has text: @LeoK Thanks, made some edits. By now I am also convinced that using `NodeTransformer` is the right approach (for handling "arbitrary" expressions). Also it's very clean and without any side effects. Nice one :)
comment on: http://stackoverflow.com/a/51254736

http://stackoverflow.com/q/51198474
upvote count: 1
answer count: 1
favorite count: 0
tagged with: gradient-descent
has comment: http://stackoverflow.com/comment/89379831
has title: PyTorch Linear Regression Issue
tagged with: python
has comment: http://stackoverflow.com/comment/89380456
type: AnsweredQuestion
downvote count: 0
tagged with: pytorch
score: 1
tagged with: regression
tagged with: machine-learning
has answer: http://stackoverflow.com/a/51199519
accepted answer: http://stackoverflow.com/a/51199519
type: Question
has comment: http://stackoverflow.com/comment/89380985
has body: I am trying to implement a simple linear model in PyTorch that can be given x data and y data, and then trained to recognize the equation y = mx + b. However, whenever I try to test my model after training, it thinks that the equation is y= mx + 2b. I'll show my code, and hopefully someone will be able to spot an issue. Thank you in advance for any help. import torch D_in = 500 D_out = 500 batch=200 model=torch.nn.Sequential( torch.nn.Linear(D_in,D_out), ) Next I create some data and set a rule. Let's do 3x+4. x_data=torch.rand(batch,D_in) y_data=torch.randn(batch,D_out) for i in range(batch): for j in range(D_in): y_data[i][j]=3*x_data[i][j]+5 # model thinks y=mx+c -&gt; y=mx+2c? loss_fn=torch.nn.MSELoss(size_average=False) optimizer=torch.optim.Adam(model.parameters(),lr=0.001) Now to training... for epoch in range(500): y_pred=model(x_data) loss=loss_fn(y_pred,y_data) optimizer.zero_grad() loss.backward() optimizer.step() Then I test my model with a Tensor/matrix of just 1's. test_data=torch.ones(batch,D_in) y_pred=model(test_data) Now, I'd expect to get 3*1 + 4 = 7, but instead, my model thinks it is 11. [[ 10.7286, 11.0499, 10.9448, ..., 11.0812, 10.9387, 10.7516], [ 10.7286, 11.0499, 10.9448, ..., 11.0812, 10.9387, 10.7516], [ 10.7286, 11.0499, 10.9448, ..., 11.0812, 10.9387, 10.7516], ..., [ 10.7286, 11.0499, 10.9448, ..., 11.0812, 10.9387, 10.7516], [ 10.7286, 11.0499, 10.9448, ..., 11.0812, 10.9387, 10.7516], [ 10.7286, 11.0499, 10.9448, ..., 11.0812, 10.9387, 10.7516]]) Similarly, if I change the rule to y=3x+8, my model guesses 19. So, I am not sure what is going on. Why is the constant being added twice? By the way, if I just set the rule to y=3x, my model correctly infers 3, and for y=mx in general my model correctly infers m. For some reason, the constant term is throwing it off. Any help to solve this problem is much appreciated. Thanks!

http://stackoverflow.com/q/51198258
tagged with: io
has title: Is it faster to do a bulk file write or write to it in smaller parts?
tagged with: python
possible better answer: http://stackoverflow.com/a/51198695
has comment: http://stackoverflow.com/comment/89378367
type: AnsweredQuestion
has body: I have a python script that reads a flat file and writes the records to a JSON file. Would it be faster to do a write all at once: dict_array = [] for record in records: dict_array.append(record) # writes one big array to file out_file.write(json.dumps(dict_array)) Or write to the file as the iterator yields each record? for record in records: out_file.write(json.dumps(record) + '\n') The amount of records in records is around 81,000. Also, the format of JSON can be one big array of objects (case 1) or line-separated objects (case 2).
has comment: http://stackoverflow.com/comment/89378512
accepted answer: http://stackoverflow.com/a/51198567
type: Question
has comment: http://stackoverflow.com/comment/89381261
tagged with: http://stackoverflow.com/tag/json
has answer: http://stackoverflow.com/a/51198695
has comment: http://stackoverflow.com/comment/89380521
has comment: http://stackoverflow.com/comment/89378454
has answer: http://stackoverflow.com/a/51198567
score: 0
answer count: 2
tagged with: file-io

http://stackoverflow.com/q/51195491
tagged with: bootstrap-4
has body: I'm trying to submit Django forms in Bootstrap 4 modals with AJAX, but it doesnt submit for some reason. When you click on the submit button it just closes the modal and nothing else happens. The content shows correctly in the modal body at least, but it just doesnt submit. Here is my view class GaasWaferDesignFormView(SuccessMessageMixin, AjaxTemplateMixin, CreateView): template_name = 'engineering/gaas_wafer_designs/gaas_wafer_design_form.html' ajax_template_name = 'engineering/gaas_wafer_designs/gaas_wafer_design_form_inner.html' form_class = GaasWaferDesignForm model = GaasWaferDesign form = GaasWaferDesignForm() success_url = reverse_lazy('engineering:gaas_wafer_design_list') success_message = "Success!" def form_valid(self, form): object = form.save(commit=False) object.created_by = self.request.user object.save() return super(GaasWaferDesignCreateView, self).form_valid(form) And here is my template which has the modal structure and button for the modal(gaas_wafer_design_list.html)... {% extends "pages/list_template.html" %}{% load static from staticfiles %} {% load widget_tweaks %} {% block title %}GaAs Wafer Design List{% endblock %} {% block list_title %}GaAs Wafer Designs{% endblock %} {% block list_title_2 %}Design Inventory{% endblock %} {% block extra_js%} {% endblock %} {% block buttons %} Create a new wafer design View Recycling Bin {% endblock %} {% block table %} Add Wafer Design × Close Wafer Design UI Emitting Type Contact Location Optical Power Design Date Designer Designer UI Created At Wafer Design UI Emitting Type Contact Location Optical Power Design Date Designer Designer UI Created At {% for gaas_wafer_design in gaas_wafer_designs %} {{ gaas_wafer_design.design_ui }} {{ gaas_wafer_design.get_emitting_display }} {{ gaas_wafer_design.contact_location }} {{ gaas_wafer_design.optical_power }} {{ gaas_wafer_design.designer }} {{ gaas_wafer_design.designer_ui }} {{ gaas_wafer_design.created_at }} {…
accepted answer: http://stackoverflow.com/a/51628396
tagged with: django
tagged with: python
type: AnsweredQuestion
type: Question
has title: Django/Bootstrap Modal not submitting
has answer: http://stackoverflow.com/a/51628396
tagged with: ajax
score: 0
answer count: 1

http://stackoverflow.com/q/51320140
tagged with: python
has answer: http://stackoverflow.com/a/51320352
answer count: 4
score: 2
downvote count: 2
type: Question
has answer: http://stackoverflow.com/a/51320782
has answer: http://stackoverflow.com/a/51320310
has body: How do I find the words in the list and remove any other words after the word found? For example: remove_words = ['stack', 'over', 'flow'] Input: 0 abc test test stack yxz 1 cde test12 over ste 2 def123 flow test123 3 yup over 4562 Would like to find the words from a list remove_words list in the pandas dataframe column and remove those words and any words after. Results: 0 abc test test 1 cde test12 2 def123 3 yup
has answer: http://stackoverflow.com/a/51320406
upvote count: 4
has title: Find the words in a list, then remove the word and any other trailing words in the column
tagged with: pandas
tagged with: string
favorite count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/89333821
has text: try `mail = open(file_path, encoding='utf-8')`, not `utf`
comment on: http://stackoverflow.com/q/51175519
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51262904
has comment: http://stackoverflow.com/comment/89507713
type: Question
upvote count: 2
has title: Python Pandas .groupby().mean() with NaN values
duplicate of: http://stackoverflow.com/q/35587459
has comment: http://stackoverflow.com/comment/89504141
tagged with: pandas
downvote count: 1
tagged with: python
favorite count: 0
linked to: http://stackoverflow.com/q/35587459
answer count: 0
has comment: http://stackoverflow.com/comment/89533025
linked to: http://stackoverflow.com/q/20109391
type: UnansweredQuestion
has body: I want to use .groupby().mean() on this DataFrame, however, it doesn't omit the NaN values. Here is the picture of my DataFrame 'Quarters' is my last row so I do transpose to make it the last column, and groupby 'Quarters', then do .mean() for all the counties. I expect to store the new DataFrame in a new variable, with column indexes as county names, and row indexes as 'Quarters', each cell is the mean of 3 cells that share the same County and same 'Quarters' in the previous DataFrame. So I do: ANSWER = City_Zhvi_AllHomes.T.groupby('Quarters').mean().T But I got: DataError: No numeric types to aggregate It will work if I do .fillna(0) before .groupby(), here is the picture for that (except I transpose the row and column again) But I can't do that since it will affect the result for the mean. So what should I do to tell .mean() to ignore NaN?
score: 1
tagged with: dataframe

tcp
type: Tag
tags question: http://stackoverflow.com/q/51243796
tags question: http://stackoverflow.com/q/51250637
tags question: http://stackoverflow.com/q/51185293
tags question: http://stackoverflow.com/q/51190998
tag name: tcp

http://stackoverflow.com/q/51292523
has title: why does asyncio_ensure_future = asyncio.async raise a SyntaxError: invalid syntax
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
score: 1
duplicate of: http://stackoverflow.com/q/51196568
type: Question
upvote count: 2
tagged with: discord.py
linked to: http://stackoverflow.com/q/51196568
has answer: http://stackoverflow.com/a/51292628
has body: I've been looking all over the the Internet and back for an answer, but nothing comes up. I assume this may or may not be very rare. It seems I'm the only one with this probably to be honest. Here's the error that comes up: import discord File "C:\Users\hmm46\AppData\Local\Programs\Python\Python37-32\lib\site-packages\discord\__init__.py", line 20, in <module> from .client import Client, AppInfo, ChannelPermissions File "C:\Users\hmm46\AppData\Local\Programs\Python\Python37-32\lib\site-packages\discord\client.py", line 42, in <module> from .voice_client import VoiceClient File "C:\Users\hmm46\AppData\Local\Programs\Python\Python37-32\lib\site-packages\discord\voice_client.py", line 43, in <module> import websockets File "C:\Users\hmm46\AppData\Local\Programs\Python\Python37-32\lib\site-packages\websockets\__init__.py", line 3, in <module> from .client import * File "C:\Users\hmm46\AppData\Local\Programs\Python\Python37-32\lib\site-packages\websockets\client.py", line 12, in <module> from .protocol import CONNECTING, OPEN, WebSocketCommonProtocol File "C:\Users\hmm46\AppData\Local\Programs\Python\Python37-32\lib\site-packages\websockets\protocol.py", line 17, in <module> from .compatibility import asyncio_ensure_future File "C:\Users\hmm46\AppData\Local\Programs\Python\Python37-32\lib\site-packages\websockets\compatibility.py", line 9 from asyncio import async as asyncio_ensure_future ^ SyntaxError: invalid syntax I'm using python 3.7.0, the latest version.
answer count: 1
downvote count: 1

http://stackoverflow.com/q/51176759
type: Question
has title: pass array with urls into template
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/51176828
tagged with: python
has body: Here I got the right URLs from django.http import HttpResponse from django.shortcuts import render import requests def main(request): return render(request,'main.html') req = requests.get('https://d3.ru/api/posts').json() arr = [] for data in req['posts']: urls = data['main_image_url'] if urls != None: arr.append(urls) print('urls',arr) How can i pass array arr into my template main.html into &lt;img class&gt; {% extends "wrapper.html" %} {% block title %} &lt;div class="container"&gt; &lt;img class = "col-12 ml-auto col-12 mr-auto" src=///arr???&gt; &lt;/div&gt; {% endblock %}
favorite count: 0
tagged with: django
upvote count: 1
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/51176828

http://stackoverflow.com/comment/89399728
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51204422
score: 0
has text: the code looks like you just "rewrite" the partner_id for that specific TransientModel. You don't "create" at any moment.

http://stackoverflow.com/comment/89369722
has text: So encodings are not available, no problem. However, I notice that you have a PyDECREF later in the function, and you skip that. It's probably needed. Consider RIAA
comment on: http://stackoverflow.com/q/51192285
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/a/51193289
downvote count: 0
upvote count: 2
answers question: http://stackoverflow.com/q/51192552
has body: Using csv.DictReader makes the work simpler compared to reader, And i changed it to commas from semi-colon, incase youre gonna use semicolon , specify the delimitter in the reader object with open('arztliste.csv', 'r') as f: file = csv.Dicteader(f) csv_data = [] for element in file : csv_data.append(element) csv_data now contains list of dictionaries where keys are the headers of your csv file and values are the "real" data . Once you get the data correct its simple to dump it into the sqldb , query = 'INSERT INTO table_name(Anrede,Titel,Titel2,Vorname,Name,Praxis,Straße,PLZ,Ort) VALUES(%s,%s,%s,%s,%s,%s,%s,%s)' Looping through the values , for data in csv_data: cur.execute(query,data['Anrede'],data['Titel'],data['Titel2']...data['Ort'])
type: Answer
score: 2

http://stackoverflow.com/comment/89440753
comment on: http://stackoverflow.com/q/51192287
score: 0
type: Comment
type: QuestionComment
has text: edit your question and provide a [mcve], so I'll tell you where the problem is, read [ask]

http://stackoverflow.com/a/51302340
has comment: http://stackoverflow.com/comment/89819845
answers question: http://stackoverflow.com/q/51302102
score: 0
has body: If I understood correctly, you want your users to be able to download a file (.csv) you generated after the user filled your form. Nonetheless, you don't want to store the data on a database, or locally. Is that it? In other words, what I'm imagining is you having a page with the generated table and a button saying "Download CSV", or something like that. What you could do is to create an URL to download that .csv, generate it and in your response use the "Content-Disposition" header. Just like this answer: https://stackoverflow.com/a/37299531/9989707
type: Answer

http://stackoverflow.com/a/51413802
answers question: http://stackoverflow.com/q/51197063
has comment: http://stackoverflow.com/comment/91280426
score: 5
upvote count: 5
has body: I have a bog-standard synchronous python program that needs to be able to read data from websockets and update the GUI with the data. However, asyncio creep is constantly tripping me up. As you mentioned GUI, then it is probably not a "bog-standard synchronous python program". Usually a GUI program has a non-blocking event-driven main thread, which allows concurrent user behaviors and callbacks. That is very much similar to asyncio, and it is usually a common way for asyncio to work together with GUIs to use GUI-specific event loop to replace default event loop in asyncio, so that your asyncio coroutines just run in GUI event loop and you can avoid calling run_forever() blocking everything. An alternative way is to run asyncio event loop in a separate thread, so that your program could at the same time wait for websocket data and wait for user clicks. I've rewritten your code as follows: import asyncio import threading import websockets import json class WSClient(threading.Thread): def __init__(self): super().__init__() self._loop = None self._tasks = {} self._stop_event = None def run(self): self._loop = asyncio.new_event_loop() self._stop_event = asyncio.Event(loop=self._loop) try: self._loop.run_until_complete(self._stop_event.wait()) self._loop.run_until_complete(self._clean()) finally: self._loop.close() def stop(self): self._loop.call_soon_threadsafe(self._stop_event.set) def subscribe(self, url, sub_msg, callback): def _subscribe(): if url not in self._tasks: task = self._loop.create_task( self._listen(url, sub_msg, callback)) self._tasks[url] = task self._loop.call_soon_threadsafe(_subscribe) def unsubscribe(self, url): def _unsubscribe(): task = self._tasks.pop(url, None) if task is not None: task.cancel() self._loop.call_soon_threadsafe(_unsubscribe) async def _listen(self, url, sub_msg, callback): try: while not self._stop_event.is_set(): try: ws = await websockets.connect(url, loop=self._loop) await ws.send(json.dumps(sub_msg)) async for data in ws: data…
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/91281712
has comment: http://stackoverflow.com/comment/89925491

http://stackoverflow.com/a/51174061
has body: Looks like a job for DataFrame.groupby. You can also use numpy's outer product for eliminating the inner double for loop. def process_data(df): pos = np.argwhere(np.less.outer(df['start'], df['end'])) indices = df.index[pos] unique = indices.ravel().unique() date_diff = np.subtract.outer(df['end'], df['start']).max(axis=0) return pd.DataFrame( data=np.asarray([ [True]*len(indices), np.where( np.isin(unique, indices[:, 1]), date_diff, np.NaN ) ]).T, columns=['Double booked', 'Time_removed'], index=unique ) df_cal.groupby('date').apply(process_data) In any case, this is based on the snippet of the OP only, and without any example data frame and example output (i.e. some kind of unit test), it is hard to say whether it really solves the issue. Also you have to make sure to not confuse index and position. In your question you seem to mix .loc and .iloc as well as usage of range. I'm not sure this is giving the result you want. Edit From the data added to OP it looks like the 'Date' variable is actually dependent on the 'Start' variable (namely being just the date of the 'Start' datetime value). Given that this holds we can spare the application of groupby and directly apply the outer product in order to get the overlapping items: overlapping = np.less_equal.outer(df['Start'], df['Start']) &amp; np.greater.outer(df['End'], df['Start']) overlapping &amp;= ~np.identity(len(df), dtype=bool) # Meetings are overlapping with themselves; need to remove. overlapping_indices = df.index[np.argwhere(overlapping)].values df.loc[ np.unique(overlapping_indices.ravel()), 'double_booked' ] = True df.loc[ overlapping_indices[:, 1], 'Time_removed' ] = ( np.minimum(df.loc[overlapping_indices[:, 0], 'End'], df.loc[overlapping_indices[:, 1], 'End']) - np.maximum(df.loc[overlapping_indices[:, 0], 'Start'], df.loc[overlapping_indices[:, 1], 'Start']) ).values However from the example data it is not clear how you want to deal with marking overlapping meetings as double booked. For the 12:30:00 …
type: Answer
has comment: http://stackoverflow.com/comment/89404684
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/89462920
has comment: http://stackoverflow.com/comment/89469691
answers question: http://stackoverflow.com/q/51172585
has comment: http://stackoverflow.com/comment/89463967
downvote count: 0
has comment: http://stackoverflow.com/comment/89475773

http://stackoverflow.com/comment/89401240
comment on: http://stackoverflow.com/a/51210353
score: 0
type: Comment
has text: I am still not very confident with dictionaries, which is something I think I need to sort out
type: AnswerComment

http://stackoverflow.com/comment/89533240
comment on: http://stackoverflow.com/q/51277108
score: 0
has text: @DevashishPrasad ok i will try these and let's see if it improves the result. i will let you know. thanks
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/89616747
has text: Paste your code as text in the question, no images unless images are relevant to the question. Also post what you got and what you expected to see.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51320544

http://stackoverflow.com/a/51237177
type: AcceptedAnswer
downvote count: 0
has body: Your profile model is related to your User model via the user_profile related name, so the correct way to query it would be: ... if product in request.user.user_profile.merchandise.all(): ... if for any reason you want to rename this relationship, then: class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, related_name='profile') Then, your merchandise relationship is One to One, so it would return an object, not a collection, no need for all: ... if product in request.user.user_profile.merchandise: ... One improvement you can make here, is because merchandise is another object, this lookup will hit the database again just to see if merchandise exist. To save you a database hit, you can use the Profile auto-field merchandise_id, to read the information saved on the Profile table instead: ... if product in request.user.user_profile.merchandise_id: ... Every relationship (ForeignKey, ManyToMany and OneToOne) will create those auto-fields in the forwarding model, so it's easy to ask if the related object exist without having to invoke it. I know you're having trouble getting all the concepts of the Django ORM in your head, so I recommend you read this documentation page throughly, it covers all the different relationships and concepts that are basic to a successful Django project.
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/89743850
accepted answer of: http://stackoverflow.com/q/51237055
has comment: http://stackoverflow.com/comment/89475913
score: 1
answers question: http://stackoverflow.com/q/51237055
has comment: http://stackoverflow.com/comment/89456364
has comment: http://stackoverflow.com/comment/89455025

http://stackoverflow.com/comment/89409370
has text: list append is nearly as good as a list comprension. `np.append` is a `concatenate`, and slow if done in a loop.
type: Comment
score: 3
type: AnswerComment
comment on: http://stackoverflow.com/a/51211968

http://stackoverflow.com/q/51202842
favorite count: 0
type: UnansweredQuestion
tagged with: python
has title: (pymysql.err.OperationalError) (2013, 'Lost connection to MySQL server during query') [SQL: u'SELECT 1']
answer count: 0
score: 1
tagged with: mysql
upvote count: 1
type: Question
has body: The question is 'Lost connection to MySQL server during query'. Some say it was just query the too large table, but except this situation. This error just do the SQL like "select 1" and then we discovers the error: (pymysql.err.OperationalError) (2013, 'Lost connection to MySQL server during query') [SQL: u'SELECT 1']. I found the pymysql code and the error log. The code that raised the exception is in file /usr/lib/python2.7/site-packages/pymysql/connections.py. def _read_bytes(self, num_bytes): self._sock.settimeout(self._read_timeout) while True: try: data = self._rfile.read(num_bytes) break except (IOError, OSError) as e: if e.errno == errno.EINTR: continue self._force_close() raise err.OperationalError( CR.CR_SERVER_LOST, "Lost connection to MySQL server during query (%s)" % (e,)) if len(data) &lt; num_bytes: #wops here self._force_close() raise err.OperationalError( CR.CR_SERVER_LOST, "Lost connection to MySQL server during query") return data The error log is as below: 2018-07-06 04:43:19.171 4674 ERROR aodh.evaluator.event File "/usr/lib/python2.7/site-packages/oslo_db/sqlalchemy/engines.py", line 80, in _connect_ping_listener 2018-07-06 04:43:19.171 4674 ERROR aodh.evaluator.event connection.scalar(select([1])) 2018-07-06 04:43:19.171 4674 ERROR aodh.evaluator.event File "/usr/lib64/python2.7/site-packages/sqlalchemy/engine/base.py", line 877, in scalar 2018-07-06 04:43:19.171 4674 ERROR aodh.evaluator.event return self.execute(object, *multiparams, **params).scalar() 2018-07-06 04:43:19.171 4674 ERROR aodh.evaluator.event File "/usr/lib64/python2.7/site-packages/sqlalchemy/engine/base.py", line 945, in execute 2018-07-06 04:43:19.171 4674 ERROR aodh.evaluator.event return meth(self, multiparams, params) 2018-07-06 04:43:19.171 4674 ERROR aodh.evaluator.event File "/usr/lib64/python2.7/site-packages/sqlalchemy/sql/elements.py", line 263, in _execute_on_connection 2018-07-06 04:43:19.171 4674 ERROR aodh.evaluator.event return connection._execute_clauseelemen…
tagged with: sqlalchemy
downvote count: 0
tagged with: pymysql

http://stackoverflow.com/comment/89454560
score: 0
type: AnswerComment
type: Comment
has text: Running the above gives me this: `The data points: Empty DataFrame Columns: [] Index: [0, 1, 2, 3, 4] []` Did I miss a step?
comment on: http://stackoverflow.com/a/51237719

http://stackoverflow.com/comment/89347549
type: QuestionComment
comment on: http://stackoverflow.com/q/51182689
has text: @RushabhMehta, i have the first dictionary is the current form of dictionary that I have right now, the second dictionary is what I need as an output ..
score: 0
type: Comment

http://stackoverflow.com/comment/89556092
has text: sure @izuzvo, thanks
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51275544
score: 0

http://stackoverflow.com/comment/89447875
score: 0
type: Comment
type: QuestionComment
has text: This should help: https://stackoverflow.com/questions/49219341/is-it-possible-to-import-my-own-modules-into-a-google-colaboratory-notebook/49221494#49221494
comment on: http://stackoverflow.com/q/51194303

http://stackoverflow.com/comment/89411914
score: 0
type: Comment
type: QuestionComment
has text: I posted a sample of my dataframe. The desired output is essentially a new column in which each element is "word|tag"
comment on: http://stackoverflow.com/q/51215246

http://stackoverflow.com/comment/89489909
comment on: http://stackoverflow.com/q/51249959
has text: From the names of the ODBC drivers it sounds like you're doing this on Windows, and Windows ODBC enables connection pooling by default for SQL Server drivers, so opening a separate connection for each thread may not necessarily be as expensive as you fear.
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/q/51217867
tagged with: python
has comment: http://stackoverflow.com/comment/89417312
tagged with: qthread
tagged with: qt
tagged with: anaconda
score: 0
has comment: http://stackoverflow.com/comment/89417636
has comment: http://stackoverflow.com/comment/89417176
has title: Embedding Python in C++ freezes when importing sklearn and running in QThread
answer count: 0
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/10625584
has comment: http://stackoverflow.com/comment/89417202
tagged with: scikit-learn
has comment: http://stackoverflow.com/comment/89417095
has body: I am working on the code below and when I am running in the main thread returns the correct printing. However, when I am running this function in a different thread (a QThread class) the code freeze in the PyRun_SimpleString function- printing and can not reach a break point below. Also no error is returned. I have noticed that this is happening when the sklearn function is imported. Could tou please help to run it correctly in a QThread class? Any help is highly appreciated! PyObject *moduleMain = PyImport_ImportModule("__main__"); PyRun_SimpleString( "def wrapper(arg1, arg2) : \n"\ " import sklearn \n"\ " print(arg1, arg2) \n"\ ); PyObject *func = PyObject_GetAttrString(moduleMain, "wrapper"); PyObject *args = PyTuple_Pack(2, PyUnicode_FromString("hello1"), PyUnicode_FromString("hello2")); Py_DECREF(moduleMain); Py_DECREF(func); Py_DECREF(args); PS: Python 3.6.1 |Anaconda (64-bit) 4.4.0 EDIT: PyEval_InitThreads(); PyEval_SaveThread(); PyGILState_STATE state = PyGILState_Ensure(); \\ code above Py_DECREF(moduleMain); Py_DECREF(func); Py_DECREF(args); PyGILState_Release(state);
type: Question

http://stackoverflow.com/comment/89346762
comment on: http://stackoverflow.com/q/51182059
score: 0
type: Comment
type: QuestionComment
has text: @abarnert I'm quite new to OOP so like you said I may not be using the correct words. I am trying to eliminate boildplate code. What I wanted was to instantiate a parent class. Then from that parent class, I can spawn multiple child classes that will inherit what the parent has. Currently I am in the process of adding and removing parameters. And having to go through all classes to add and delete parameters is not the most efficient use of my time. I will look into `@dataclass` and `namedtuple`.

http://stackoverflow.com/a/51207420
has comment: http://stackoverflow.com/comment/89400034
has comment: http://stackoverflow.com/comment/89400239
has comment: http://stackoverflow.com/comment/89400146
has comment: http://stackoverflow.com/comment/89400104
has comment: http://stackoverflow.com/comment/89399470
answers question: http://stackoverflow.com/q/51206289
has body: First some tips when you work with strings as input. Python will make the difference between caps and non-caps letter, thus a good way to deal with strings is to lower() them first (or upper(), ...): Example: ques = input("Enter Yes or No: ") ques = ques.lower() if ques == "yes": # do something elif ques == "no": # do something else else: # raise error Now I feel like your code is build in a funny way. A good habit is to separate the import from the functions, from the main program. The 2 first will be imported if the module (file) is imported, while the last one will be played when the file is executed. To do so, you can use this: # -*- coding: utf-8 -*- """ docstring of the module """ # Imports import random import os # Functions def f(): return "Hello world" # Main program if __name__ == '__main__': # Calling the function, taking the inputs and so on In the main program, it's rather useful to deal with the possibility that an exception is raised. Moreover, if you use the cmd to display your program, the cmd will close immediately when an error is raised. This syntax is quite useful: if __name__ == '__main__': try: # Do stuff except: import sys print (sys.exc_info()[0]) import traceback print (traceback.format_exc()) os.system("pause") # for windows, else easy way is to have an empty input to freeze the cmd Now your code. I would rework it this way: # -*- coding: utf-8 -*- """ Docstring """ # Imports import random import os # Functions def build_a_phrase(language) : if language == "french": verb = ["vendre", "atterir", "attaquer", "jeter"] #list of verbs I have manually entered noun = ["arbre", "poisson", "chien"] #list of nouns I have manually entered pronoun = ["un", "les"] #list of pronouns I have manually entered morenouns = ["chat", "oiseau"] #list of nouns I have manually entered choices = [random.choice(verb), random.choice(noun), random.choice(pronoun), random.choice(morenouns)] phrase = " ".join(choices) # Add a space between the words return phrase elif …
score: 0
type: Answer

http://stackoverflow.com/comment/89635459
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51293427
has text: Do you know if there's a way to keep each indicator's title/detection/fileds/etc... separate instead of putting them together?

http://stackoverflow.com/q/51175012
score: 0
tagged with: pandas
has answer: http://stackoverflow.com/a/51175031
answer count: 1
tagged with: python
has body: This code : df = pd.DataFrame({ 'id_val' : [1.0 , 2.0, 3.0] , 'c1': [1.0 , 2.0, 3.0], 'c2': [1.0 , 2.0, 3.0], 'c3': [1.0 , 2.0, 3.0] }) df generates the dataframe : Attempting to one-hot encode this dataframe using get_dummies : pd.get_dummies(df) renders the same dataframe : How do I one hot encode the dataframe using get_dummies ?
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51175031
has title: Pandas not one hot encoding data
has comment: http://stackoverflow.com/comment/89332776
type: Question

http://stackoverflow.com/comment/138684257
type: Comment
comment on: http://stackoverflow.com/a/51249740
type: AnswerComment
has text: why cant spark do this on its own, rather than relying on external library to do so?
score: 0

http://stackoverflow.com/comment/89584702
type: QuestionComment
has text: you can break lines by adding a `\\` at the end of the line
score: 1
comment on: http://stackoverflow.com/q/51304016
type: Comment

http://stackoverflow.com/q/51297334
tagged with: python
has title: group by count and sum based on particular column in pandas dataframe in separate column along with other columns
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/51297368
type: Question
tagged with: dataframe
answer count: 2
tagged with: pandas
has answer: http://stackoverflow.com/a/51297379
downvote count: 0
favorite count: 0
has body: I have a dataframe(df): A B C D E F A1 B1 c 10 E1 F1 A2 B2 c 50 E2 F2 A3 B3 c 20 E2 F3 A4 B4 c 30 E1 F4 A5 B5 c 40 E3 F5 Output should be like; df: A B C D E F count sum A1 B1 c 10 E1 F1 2 40 A2 B2 c 50 E2 F2 2 70 A3 B3 c 20 E2 F3 2 70 A4 B4 c 30 E1 F4 2 40 A5 B5 c 40 E3 F5 1 40 taking count and sum based on E column. I tried : df.groupby('E').agg(['count','sum']) I am getting only count and sum column not other columns of df. Please suggest the solution.
has comment: http://stackoverflow.com/comment/89571845
type: UnansweredQuestion

http://stackoverflow.com/a/51285153
has body: I am not quite sure as I'm a newbie as well, but I have a feel like you are missing the name in your HTML. HTML &lt;input type="file" style="visibility:hidden;" multiple id="new-homework" value="Choose files" name="file"&gt; Python if request.method == 'POST': file = request.files['file'] print(file) Thanks.
score: 0
answers question: http://stackoverflow.com/q/51282011
type: Answer

http://stackoverflow.com/q/51183719
has comment: http://stackoverflow.com/comment/89365746
score: 0
has comment: http://stackoverflow.com/comment/89350280
answer count: 1
has answer: http://stackoverflow.com/a/51184243
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89349507
tagged with: scrapy
type: Question
has title: My first Python Scrapy cannot work
has body: I am new to Python and Scrapy. and now i am working on crawling and needs to use both of them. below is my code and no output can be retrieved. May i know how can i solve this issue? Thanks in advance. import scrapy from loginform import fill_login_form class FirstSpider(scrapy.Spider): name = 'test' login_url = 'URL' login_user = 'account' login_password = 'password' def start_requests(self): print('Step 1') return scrapy.Request(self.login_url, callback=self.parse_login) def parse_login(self, response): print('Step 2') data, url, method = fill_login_form(response.url, response.body, self.login_user, self.login_password) return scrapy.FormRequest(url, formdata=dict(data), method=method, callback=self.start_crawl) def start_crawl(self, response): list = response.xpath("//a[@class='menu_section active']/text()").extract() print(list) if 'back overview' in list: print('Good to go') else: print("Failed") output : Process finished with exit code 0
has comment: http://stackoverflow.com/comment/89351897

http://stackoverflow.com/q/51193920
has answer: http://stackoverflow.com/a/51194185
has answer: http://stackoverflow.com/a/51194194
downvote count: 0
has answer: http://stackoverflow.com/a/51194119
tagged with: string
favorite count: 0
tagged with: python
answer count: 4
score: 2
type: AnsweredQuestion
tagged with: list
tagged with: chunks
possible better answer: http://stackoverflow.com/a/51194194
upvote count: 2
type: Question
tagged with: split
accepted answer: http://stackoverflow.com/a/51194185
has body: So I am working with files in python, feel like there is a name for them but I'm not sure what it is. They are like csv files but with no separator. Anyway in my file I have lots of lines of data where the first 7 characters are an ID number then the next 5 are something else and so on. So I want to go through the file reading each line and splitting it up and storing it into a list. Here is an example: From the file: "0030108102017033119080001010048000000" These are the chunks I would like to split the string into: [7, 2, 8, 6, 2, 2, 5, 5] Each number represents the length of each chunk. First I tried this: n = [7, 2, 8, 6, 2, 2, 5, 5] for i in range(0, 37, n): print(i) Naturally this didn't work, so now I've started thinking about possible methods and they all seem quite complex. I looked around online and couldn't seem to find anything, only even sized chunks. So any input? EDIT: The answer I'm looking for should in this case look like this: ['0030108', '10', '20170331', '190800', '01', '01', '00480', '00000'] Where each value in the list n represents the length of each chunk.
has title: Iterate through a string in chunks of different sizes python
has answer: http://stackoverflow.com/a/51194360

http://stackoverflow.com/q/51263832
tagged with: django-views
has body: Right now, I'm working on the registration form in Django. In my registration form, there is the total of six fields like Username, First Name, Last Name, Email, Password, Password Confirmation. During my testing of the registration form, I figured out such a weird thing. Every time fields change their positions. I mean sometime Password comes at first place and Last Name at last place. And whenever I shut down the server and run it again then again fields positions changed again. See below some screenshot. So you can understand what I mean to say. And If I shut down the server and run it again then It happens every time. According to the logic which I write in the code it must in one proper manner like Username, First Name, Last Name, Email, Password, Password Confirmation. Here below my views.py: from django.shortcuts import render, redirect from accounts.forms import RegistrationForm # Create your views here. def register(request): if request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid(): form.save() return redirect('/account') else: form = RegistrationForm() args = {'form': form} return render(request, 'accounts/reg_form.html', args) And below one is forms.py: from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm class RegistrationForm(UserCreationForm): email = forms.EmailField(required=True) class Meta: model = User fields = { 'username', 'first_name', 'last_name', 'email', 'password1', 'password2' } def save(self, commit=True): user = super(RegistrationForm, self).save(commit=False) user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.email = self.cleaned_data['email'] if commit: user.save() return user
has comment: http://stackoverflow.com/comment/89505502
score: 0
accepted answer: http://stackoverflow.com/a/51264678
answer count: 1
has title: Improper format of Registration Form in Django
tagged with: python-3.x
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51264678
tagged with: django
tagged with: django-forms
has comment: http://stackoverflow.com/comment/89505811
type: Question

http://stackoverflow.com/q/51289991
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51290150
tagged with: methods
has comment: http://stackoverflow.com/comment/89557993
has comment: http://stackoverflow.com/comment/89558416
type: Question
tagged with: object
has answer: http://stackoverflow.com/a/51290150
has body: I am writing a program (python Python 3.5.2) that uses a HTTPSConnection to get a JSON object as a response. I have it working using some example code, but am not sure where a method comes from. My question is this: In the code below, the decode('utf-9') method doesn't exist in the documentation at https://docs.python.org/3.4/library/http.client.html#http.client.HTTPResponse under "21.12.2. HTTPResponse Objects". How would I know that the return value from the method "response.read()" has the method "decode('utf-8')" available? Do Python objects inherit from a base class like C# objects do or am I missing something? http = HTTPSConnection(get_hostname(token)) http.request('GET', uri_path, headers=get_authorization_header(token)) response = http.getresponse() print(response.status, response.reason) feed = json.loads(response.read().decode('utf-8')) Thank you for your help.
score: 0
has title: Python documentation on possibly inherited method
answer count: 1

http://stackoverflow.com/a/51275719
has comment: http://stackoverflow.com/comment/89536540
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51273024
answers question: http://stackoverflow.com/q/51273024
upvote count: 3
type: Answer
score: 3
downvote count: 0
has body: The usual idiom for lists is: parameter_list : parameter | parameter_list COMMA parameter parameter : ID COL WHITESPACE TYPE For optional parameter lists, you would then add optional_parameters : parameter_list | empty It's not necessary to define parameter as a separate non-terminal, particularly if there's only one associate production. But often there is more than one, and the grammar is easier to read with the extra non-terminal. By the way, it's usually a lot less trouble to ignore whitespace in the scanner than to try to include it everywhere it could go in a grammar. (For even slightly complicated grammar, trying to deal with whitespace explicitly often leads to the need for additional lookahead.)

http://stackoverflow.com/comment/89547980
comment on: http://stackoverflow.com/q/51285205
score: 0
has text: you initialize the flask app (`app = Flask(__name__)`). now my question is where you added `app.run()` command to start flask app
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51324321
has body: For your example data you could use: (?s)\(\s*array\['nosql'\].*?\)\) (?s) Mode for dot matches newline \( Match ( array\['nosql'\] Match zero or more times a whitespace character followed by array [nosql] .*? Match any character zero or more times non greedy \)\) Match )) Demo
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/51323703
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51323703
type: Answer

http://stackoverflow.com/comment/89398968
score: 0
has text: its a keras module, I edited my question to add it
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51209000

http://stackoverflow.com/comment/89456054
type: QuestionComment
has text: What is `data2`? I see a `numpy` tag, but `contains` isn't a numpy method, nor a Python string one.
score: 0
comment on: http://stackoverflow.com/q/51235906
type: Comment

http://stackoverflow.com/comment/89596968
type: AnswerComment
score: 0
type: Comment
has text: What is `.dt`? What libraries you are importing?
comment on: http://stackoverflow.com/a/51310112

http://stackoverflow.com/q/51195017
has answer: http://stackoverflow.com/a/51195367
tagged with: tensor
type: UnansweredQuestion
tagged with: machine-learning
upvote count: 1
tagged with: tensorflow
type: Question
score: 1
has title: tf.keras.backend way of replacing a tensors value if it's less than 1
answer count: 2
has answer: http://stackoverflow.com/a/51196077
downvote count: 0
tagged with: keras
favorite count: 0
has body: I am using Keras with the Tensorflow backend. In my loss function I have a tensor where I need to replace the elements that are less than 1 with a 1. I can see loads of functions available to me in the docs https://www.tensorflow.org/api_docs/python/tf/keras/backend but I'm not sure how to go about this. If I do: a_ = tf.Print( message='a_shape', input_=a_, data=[tf.shape(a_)] ) I get the shape as: y_shape[128] I need to essentially iterate through this tensor replacing elements that are less than 1 with a 1. How would I do this using the keras tensorflow API? Thanks -
tagged with: python

http://stackoverflow.com/a/57653719
downvote count: 0
type: Answer
has body: I solved this by setting up proxies on the about:config page on Firefox. Here is the code that you need in order to do it: devices = { "mobile" : "Mozilla/5.0 (Android 4.4; Tablet; rv:41.0) Gecko/41.0 Firefox/41.0", "desktop" : "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36 Edge/12.246" } scripts = 'var prefs = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch); prefs.setIntPref("network.proxy.type", 1); prefs.setCharPref("network.proxy.socks", "' + proxy + '"); prefs.setIntPref("network.proxy.socks_port", port); prefs.setBoolPref("dom.webnotifications.enabled", false); prefs.setCharPref("general.useragent.override", "' + devices[device] + '");' browser.execute_script(scripts) If you dont want to override the UA then you dont need to use devices list and just remove the last js rule set in the script.
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/51276893
has comment: http://stackoverflow.com/comment/101911395

css-selectors
tags question: http://stackoverflow.com/q/51252089
tags question: http://stackoverflow.com/q/51188330
tags question: http://stackoverflow.com/q/51263444
tags question: http://stackoverflow.com/q/51207243
tag name: css-selectors
type: Tag

http://stackoverflow.com/comment/89382182
score: 0
type: QuestionComment
has text: @roganjosh i just want to compare the user input to database values and show that the value exists and value does not exist .
comment on: http://stackoverflow.com/q/51199767
type: Comment

http://stackoverflow.com/q/51241130
downvote count: 0
has title: python Django ORM group and order a queryset
tagged with: orm
type: Question
upvote count: 2
has body: In my django project i have to implement a groupped query with ORM and order results for a specific field. I do this: a = tt.objects.filter(thread_status = 'DEAD').select_related().distinct('thread_stag').order_by('-id')[0:20] but the response is an error: ProgrammingError: SELECT DISTINCT ON expressions must match initial ORDER BY expressions How can i do distinct and order_by in same query on different columns? thanks in advance
tagged with: django-queryset
answer count: 1
favorite count: 0
linked to: http://stackoverflow.com/q/20582966
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51241290
tagged with: django
tagged with: python
score: 2

http://stackoverflow.com/comment/89452351
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51236631
has text: @AlexReinking yea it's a counter-intuitive thing when working with numpy. In answers like [this](https://stackoverflow.com/questions/50959180/python-sort-list-of-lists-numerically/50960136#50960136), I actually sort something twice when dropping duplicates and it still easily beats any vanilla python approach.
type: Comment

http://stackoverflow.com/q/51204250
possible better answer: http://stackoverflow.com/a/51219580
favorite count: 0
has answer: http://stackoverflow.com/a/51219580
has answer: http://stackoverflow.com/a/61354451
type: Question
has comment: http://stackoverflow.com/comment/89389836
tagged with: python
tagged with: jupyter
accepted answer: http://stackoverflow.com/a/61354451
tagged with: jupyter-notebook
upvote count: 3
answer count: 2
has title: Jupyter notebook run in chrome gets stuck on server restart
has body: I start with a working jupyter setup, and everything works just fine. I can interrupt or restart the kernel from the notebook without any problems. If, however, I change some jupyter configuration, or install some modules, and restart jupyter server - I have to wait for about 5 minutes for the open notebooks to recover access to the python kernel. To reproduce the problem: Start jupyter (local shell) jupyter notebook In chrome create a new notebook (python 3), which will result in a url like: http://localhost:8888/notebooks/Untitled1.ipynb?kernel_name=python3 Create and run a single cell in that new notebook: print(1) Restart jupyter (Ctrl-C followed by [yes] to the prompt to exit), followed by: jupyter notebook Go to the same chrome tab with the same single cell notebook and click OK for the pop-up "Connection failed" Observe the notebook showing: [Connecting to Kernel] without success. Try to Restart the kernel via the menu, usually it gets stuck in [Kernel Starting...], and after several manually forced kernel restarts it supposedly succeeds [Kernel Created], but it's a false success, as trying to run the cells gives a [*] busy sign and nothing happens. After some 5 min of waiting it recovers by itself. Workarounds: Reloading the notebook in the browser (i.e. hitting Reload at the browser level) Restarting chrome Software: ubuntu 16.04 notebook 5.5.0 python 3.6.6 chrome 67 no adblock software enabled empty ~/.jupyter (removed everything for the sake of the testing, so no extensions or custom configuration) Same setup works fine in firefox on the same machine. There are several tickets on github about the same from 2015 (e.g. this, but somehow they blame it on chrome and clearly the issue is still there 3 years later. Any idea how to solve this? Thank you. And here is the log during the open notebook reconnect/restart process: [I 22:54:09.032 NotebookApp] Kernel restarted: 9aa08efb-74b1-471c-ad0f-bb9dc3577c28 [W 22:54:09.343 NotebookApp] Replacing stale connection…
downvote count: 1
has comment: http://stackoverflow.com/comment/89389956
score: 2
type: AnsweredQuestion

http://stackoverflow.com/comment/89541899
comment on: http://stackoverflow.com/q/51239715
has text: I was searching for the code to plot histogram from the LBP pattern, but I couldn't get that. All I see is plotting histogram from the image. Can you help me out to find that @CrisLuengo? Is there any reference sites that I can look ahead?
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/51288294
downvote count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51290385
type: Question
score: 1
tagged with: base64
has comment: http://stackoverflow.com/comment/89554416
has comment: http://stackoverflow.com/comment/89562316
has title: UTF-8 encoding in str type Python 2
upvote count: 1
answer count: 1
favorite count: 0
has body: I have a Python 2.7 code which retrieves a base64 encoded response from a server. This response is decoded using base64 module (b64decode / decodestring functions, returning str). Its decoded content has the Unicode code points of the original strings. I need to convert these Unicode code points to UTF-8. The original string has a substring content "Não". When I decode the responded string, it shows: &gt;&gt;&gt; encoded_str = ... # server response &gt;&gt;&gt; decoded_str = base64.b64decode(encoded_str) &gt;&gt;&gt; type(decoded_str) &lt;type 'str'&gt; &gt;&gt;&gt; decoded_str[x:y] 'N\xe3o' When I try to encode to UTF-8, it leads to errors as &gt;&gt;&gt; (decode_str[x:y]).encode('utf-8') UnicodeDecodeError: 'ascii' codec can't decode byte 0xe3 in position 2: ordinal not in range(128) However, when this string is manually written in Unicode type, I can correctly convert it to my desired UTF-8 string. &gt;&gt;&gt; test_str = u'N\xe3o' &gt;&gt;&gt; test.encode('utf-8') 'N\xc3\xa3o' I have to retrieve this response from the server and correctly generate an UTF-8 string which can be printed as "Não", how can I do this in Python 2?
tagged with: python
tagged with: utf-8

http://stackoverflow.com/comment/89651012
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/51292055
has text: Actually, after further investigations, I found out that the reason they didn't make it a foreign key was that the field was supposed to be a generic id field. That is, it can refer to the foreign key of another model (aside from Bar). But thanks for this answer.

http://stackoverflow.com/comment/89342438
score: 1
comment on: http://stackoverflow.com/q/51179906
type: Comment
type: QuestionComment
has text: you could save result of the query directly to a csv using the -e command with mysql on the command line. Also if the data is too big, try using chunking and store it in multiple csv s or append on the same csv.... also where are you running out of memory ? are you sure it is because the query is too big ?

http://stackoverflow.com/comment/89523108
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51271726
has text: Hmm, sorry that's all I've got. I don't actually know/use this software, I'm just being Captain obvious

http://stackoverflow.com/a/51322948
score: 5
downvote count: 0
type: Answer
has body: Getting the URL of your response is very simple: r = requests.get("www.example.com") print(r.url)
upvote count: 5
answers question: http://stackoverflow.com/q/51322889

http://stackoverflow.com/comment/89634597
comment on: http://stackoverflow.com/a/51319161
type: AnswerComment
score: 0
type: Comment
has text: Just confirmed: it works well with Python 2.x as well as Python 3. Numpy versions are 1.11.2 and 1.14.0.

http://stackoverflow.com/q/51263934
has answer: http://stackoverflow.com/a/51362691
has title: Spyder won't load
has comment: http://stackoverflow.com/comment/89511974
type: Question
tagged with: anaconda
has comment: http://stackoverflow.com/comment/89506274
score: 0
has comment: http://stackoverflow.com/comment/89514067
accepted answer: http://stackoverflow.com/a/51362691
answer count: 1
has body: I've installed in Windows 10 Anaconda 1.8.7 with Python 3.6.5 and Spyder 3.2.8 The issue is the following : when I launch Spyder from Anaconda navigator Spyder freeze when loading the editor. I've uninstall Anaconda an reinstall it whithout succes I've launched Spyder from commmand line and I've no specific output in the terminal I've deleted the .spyder-py3 .anaconda .ipython and .conda whithout change Does someone has an idea?
tagged with: windows-10
has comment: http://stackoverflow.com/comment/89524961
tagged with: spyder
tagged with: python
has comment: http://stackoverflow.com/comment/89507319
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89521137

http://stackoverflow.com/a/51223670
type: Answer
has body: Problem Indeed it is a dimensionality problem. It has to do with your general network architecture, which does not match your new input size. You adopted the architecture from cnn_mnist.py. Here line 72 is causing the issue: pool2_flat = tf.reshape(pool2, [-1, 7 * 7 * 64]) // 7*7*64=3136 The architecture assumes a [-1, 7, 7, 64] shape, but you are passing [-1,24,24,64]. How to fix it change pool2_flat to match your acutal output shape: pool2_flat = tf.reshape(pool2, [-1, 24 * 24 * 64])
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/51221958
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51221958

http://stackoverflow.com/comment/89403995
comment on: http://stackoverflow.com/q/51211539
type: QuestionComment
score: 1
has text: So are you ignoring any group with less than 3 elements?
type: Comment

http://stackoverflow.com/q/51194106
upvote count: 0
score: -2
has body: I have a txt file that presents nodes and edges between nodes. The node-part contains some additional information. The file looks like this: @nodes label characteristic A characteristic B 1 vfn 5 2 ksdv 625 3 asn 0 @edges 1 3 2 3 I can extract the information if I have one file for the nodes and one for the edges without headers without a problem, but how can I extract the information if the file looks like the example? Since the skript has to work for all node-edge-files in this format I cannot just cut out certain lines, I need to somehow spot the @-symbol and cut along that line. In addition to that I need to cut out the node header with the characteristics while the edge section does not have a header. Any help is appreciated!
answer count: 3
has comment: http://stackoverflow.com/comment/89369841
has title: Python extract data from txt file and ignore the headers
favorite count: 0
has answer: http://stackoverflow.com/a/51194416
has comment: http://stackoverflow.com/comment/89375366
tagged with: extract
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/51194323
downvote count: 2
has answer: http://stackoverflow.com/a/51196520
type: Question

http://stackoverflow.com/q/51279535
upvote count: 1
has answer: http://stackoverflow.com/a/51279584
type: Question
has comment: http://stackoverflow.com/comment/89537085
has comment: http://stackoverflow.com/comment/89536553
has comment: http://stackoverflow.com/comment/89537324
score: 1
possible better answer: http://stackoverflow.com/a/51279584
has comment: http://stackoverflow.com/comment/89537681
accepted answer: http://stackoverflow.com/a/51280408
has body: import speech_recognition as sr r = sr.Recognizer() with sr.Microphone() as source: audio = r.listen(source) print(r.recognize_sphinx(audio)) When I run this code in Python in raspberry pi 3 (model B), it gives the following error. OSError: No Default Input Device Available what is the reason for this? do I need to have a USB microphone to get the audio signals in rather than using the microphone in earphones?
has comment: http://stackoverflow.com/comment/89536644
answer count: 2
tagged with: raspberry-pi
has comment: http://stackoverflow.com/comment/89536514
downvote count: 0
has comment: http://stackoverflow.com/comment/89536915
has comment: http://stackoverflow.com/comment/89536755
tagged with: speech-recognition
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89537394
tagged with: python
has comment: http://stackoverflow.com/comment/89536470
has answer: http://stackoverflow.com/a/51280408
type: AnsweredQuestion
has title: Can I use AUX port in Raspberry Pi 3 (Model B) to plug a microphone to get audio signals in?
has comment: http://stackoverflow.com/comment/89536451
has comment: http://stackoverflow.com/comment/89537634

http://stackoverflow.com/a/51235278
answers question: http://stackoverflow.com/q/51234114
type: Answer
has comment: http://stackoverflow.com/comment/89495813
has comment: http://stackoverflow.com/comment/89449628
score: 0
has comment: http://stackoverflow.com/comment/89449683
has body: I am not exactly sure if this is what you want, but if you want to rotate the image based on the rotation angle of the object then: image = cv2.imread('image.jpg',cv2.IMREAD_UNCHANGED) gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY) ret, corners=cv2.findCirclesGrid(gray,(5,5),None) criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 100, 0.001) corners2 = cv2.cornerSubPix(gray,corners,(11,11),(-1,-1),criteria) ((x,y),(w,h),angle) = cv2.minAreaRect(corners2) rows,cols = image.shape[:2] angle += 90 M = cv2.getRotationMatrix2D((int(cols/2),int(rows/2)), angle, 1.0) nimg = cv2.warpAffine(image,M,(cols,rows))

http://stackoverflow.com/comment/89402593
has text: You are not counting the extracted mentions, collect them first, then find the most common, see https://ideone.com/PyxjGt
type: QuestionComment
comment on: http://stackoverflow.com/q/51210853
type: Comment
score: 1

http://stackoverflow.com/comment/89383490
has text: Wow! I like the use of [this technique](https://www.dostips.com/forum/viewtopic.php?f=3&t=6429&p=41035#p41035) to create the array elements! **`;)`**
type: AnswerComment
score: 2
type: Comment
comment on: http://stackoverflow.com/a/51194867

http://stackoverflow.com/comment/89485839
score: 0
type: QuestionComment
type: Comment
has text: Can you add an [mcve]? I'm unable to reproduce your issue. Please read more on [how to create good reproducible apache spark dataframe examples](https://stackoverflow.com/questions/48427185/how-to-make-good-reproducible-apache-spark-dataframe-examples).
comment on: http://stackoverflow.com/q/51253271

http://stackoverflow.com/a/51173978
has body: Another way of doing it is by using dictionaries to build relationships between device serial numbers and printer ports: inString = """/usr/local/bin/lp_server -n 5964 -d /dev/usb/lp1 /usr/local/bin/lp_server -n 5965 -d /dev/usb/lp0 {lp_supervisor} /bin/sh /usr/local/lp/lp_supervisor /dev/usb/lp0 SERIAL#1 /var/run/lp/lp_pid/usb_lp0 {lp_supervisor} /bin/sh /usr/local/lp/lp_supervisor /dev/usb/lp1 SERIAL#2 /var/run/lp/lp_pid/usb_lp1""" inString = inString.split("\n") matches = dict() serials = dict() for i in range(len(inString[:2])): lp = inString[i][-3:] printerPort = int(inString[i].split("-n ")[1][:4]) matches.update({lp:printerPort}) for i in range(2,len(inString)): t = inString[i].split(" ") lp = t[3][-3:] serial = t[4] serials.update({serial:lp}) finalLookup = dict((k,matches[v]) for k,v in serials.items()) print(finalLookup) Output: {'SERIAL#1': 5965, 'SERIAL#2': 5964} Then you can do: if not finalLookup['SERIAL#1'] == 5964: run some command else: do something else if not finalLookup['SERIAL#2'] == 5965: run some command else: do something else
score: 0
answers question: http://stackoverflow.com/q/51173298
type: Answer

http://stackoverflow.com/a/51195341
upvote count: 2
type: Answer
answers question: http://stackoverflow.com/q/51195038
score: 2
has comment: http://stackoverflow.com/comment/89399544
has comment: http://stackoverflow.com/comment/89399981
has body: Your dijkstra function only carries out these four lines of code, as they are the only lines of code before you define a second function. So when you call this function at the end, the program creates some empty dictionaries and then closes: shortest_distance = {} #empty dictionary predeccesor = {} #empty dictionary unseenNodes = graph #makes it run through til all are seen path = [] The second function you define, init() is a class method, you can't define it outside of a class. Have a look at some more basic algorithms in python first, and familiarise yourself to the syntax (I don't know how different it is to C#).
downvote count: 0

http://stackoverflow.com/a/51185245
downvote count: 0
answers question: http://stackoverflow.com/q/51185079
score: 4
type: Answer
upvote count: 4
has body: For a binary classification model you should use sigmoid activation function in your last dense layer model.add(Dense(1, activation='sigmoid')) also, your classes must be (0,1) not (-1,1)
accepted answer of: http://stackoverflow.com/q/51185079
type: AcceptedAnswer

http://stackoverflow.com/a/51245085
type: Answer
accepted answer of: http://stackoverflow.com/q/51241012
answers question: http://stackoverflow.com/q/51241012
downvote count: 0
has comment: http://stackoverflow.com/comment/89487922
score: 14
has comment: http://stackoverflow.com/comment/89470766
upvote count: 14
has body: Classic Load Balancer Use: client = boto3.client('elb') Then describe_load_balancers() results include a list of instances: 'Instances': [ { 'InstanceId': 'string' }, ], Application Load Balancer Use: client = boto3.client('elbv2') Call describe_target_groups() passing in the Load Balancer ARN to obtain a list of Target Groups associated with the Load Balancer Then call describe_target_health() to obtain a list of targets (instances). Here is a sample response: { 'TargetHealthDescriptions': [ { 'Target': { 'Id': 'i-0f76fade', 'Port': 80, }, ...
type: AcceptedAnswer

http://stackoverflow.com/q/51256032
accepted answer: http://stackoverflow.com/a/51256161
score: 0
tagged with: sqlite
answer count: 1
tagged with: string
has body: I have built a function to build sqlite commands in python 3.6 from text I scrape from websites. The length of the sql command varies depending on the text that was retrieved. def build_sql_stmnt(row, table, col_val): """builds an sql_stmnt to query fencers_db1.sqlite input: row -- string, row data wanted table -- string, table to query col_val -- tuple with column/value pairs Ex1: (('column', value),) Ex2: (('column1', value1), ('column2', value2)) returns: sql_stmnt -- string to be used as c.execute SELECT argument """ string = '' countdown = len(col_val) for pair in col_val: if countdown &gt; 1: string = string + ("""{} = '{}' AND """.format(pair[0], pair[1])) else: string = string + ("""{} = '{}'""".format(pair[0], pair[1])) countdown -= 1 sql_stmnt = """SELECT {rw} FROM {tbl} WHERE {s};""".format( rw = row, tbl = table, s = string) return sql_stmnt I have resorted to triple quotes to define the strings above when I discovered that the text I scrape may include double quotes ("). Now, I have found that the text I scrape can also include apostrophes ('). When I run the function when col_val includes an apostrophe ("Fencers' Club") I get the following error: OperationalError: near "Club": syntax error The following returns the same error: if countdown &gt; 1: string = string + ("""{} = \'{}\' AND """.format(p0, p1)) else: string = string + ("""{} = \'{}\'""".format(p0, p1)) countdown -= 1 Is there a better way to build an sql statement, or is there a way to generate strings with variables that may contain double quotes and/or apostrophes?
tagged with: python-3.x
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89491684
has title: how to generate python strings with formatter variables that my contain apostrophes and/or quotes?
tagged with: web-scraping
type: Question
has answer: http://stackoverflow.com/a/51256161

http://stackoverflow.com/comment/89481402
type: QuestionComment
comment on: http://stackoverflow.com/q/51251217
has text: What exactly are you having difficulty with? If you have a SQL query that works, then it should also work as `cursor.execute(<SQL query>)`. There's some stuff to learn about parameter substitution, but unless you describe exactly what you don't understand, we can't really help you any more than the [documentation](https://docs.python.org/3/library/sqlite3.html) or any tutorial could.
score: 0
type: Comment

http://stackoverflow.com/a/51198891
type: Answer
has body: You can use the concept of hierarchy of contours to solve this problem. But there is a caveat, all your images must be the same as the one in the question. I just added some additional stuff to your code. Code: img2 = img.copy() im2, cont, hierarchy = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) l = [] for e, h in enumerate(hierarchy[0]): #print (e, h[3]) if h[3] == -1: l.append(e) for i in l: if cv2.contourArea(cont[i]) &lt; 1000: cv2.drawContours(img2, [cont[i]], -1, (0, 255, 255), 2) cv2.imshow('img2', img2) Result: hierarchy returns an array expressing the parent-child relationship of contours. As per the documentation link, it as an array of four values : [Next, Previous, First_Child, Parent]. In the hierarchy array I scanned the Parent column (4th column) to see whether it has no parent contours (-1) and drew them
downvote count: 0
has comment: http://stackoverflow.com/comment/89670270
score: 1
has comment: http://stackoverflow.com/comment/89670241
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89667803
has comment: http://stackoverflow.com/comment/89668032
answers question: http://stackoverflow.com/q/51190561
accepted answer of: http://stackoverflow.com/q/51190561

http://stackoverflow.com/comment/89559688
comment on: http://stackoverflow.com/a/51289809
type: Comment
has text: Awesome, got it! Thanks!
score: 0
type: AnswerComment

http://stackoverflow.com/a/51248226
type: Answer
has body: Per the documentation for files_upload, for large files like this (>150 MB) you should use upload sessions instead: Do not use this to upload a file larger than 150 MB. Instead, create an upload session with files_upload_session_start().
answers question: http://stackoverflow.com/q/51244790
score: 0

http://stackoverflow.com/a/55752009
score: 7
has comment: http://stackoverflow.com/comment/111706875
has comment: http://stackoverflow.com/comment/111707274
downvote count: 0
has body: I had to figure this issue out passing an uploaded file from a Django front end website to a Django backend API in Python 3. The InMemoryUploadedFile's actual file data can be accessed via the object's .file property's .getvalue() method. path="path/to/api" in_memory_uploaded_file = request.FILES['my_file'] io_file = in_memory_uploaded_file.file file_value = io_file.getvalue() files = {'my_file': file_value} make_http_request(path, files=files) and can be shortened file = request.FILES['my_file'].file.getvalue() files = {'my_file': file} Before this, trying to send InMemoryUploadFile objects, the file property, or the result of the read() method all proved to send a blank/empty file by the time it got to the API.
type: Answer
answers question: http://stackoverflow.com/q/51189487
upvote count: 7

http://stackoverflow.com/q/51175884
favorite count: 0
tagged with: python
has title: Error of Shape Using Conv1D in Keras
score: 2
tagged with: conv-neural-network
has answer: http://stackoverflow.com/a/51187827
downvote count: 0
type: UnansweredQuestion
type: Question
has answer: http://stackoverflow.com/a/51176161
upvote count: 2
tagged with: keras-layer
answer count: 2
has body: I have troubles using Conv1D as an input layer in Sequential NN with Keras. Here is my code : import numpy as np from keras.layers.convolutional import Conv1D from keras.models import Sequential from keras.optimizers import Adam conv1d = Conv1D(input_shape=(None, 16), kernel_size=2, filters=2) model = Sequential() model.add(conv1d) model.compile(loss="logcosh", optimizer=Adam(lr=0.001)) x_train = np.zeros((32, 16, 1)) y_train = np.zeros((32, 16, 1)) print(x_train.shape) model.fit(x_train, y_train, batch_size=4, epochs=20) Here is the error. I have tried multiple things but none of them helped me to resolve the issue. ValueError: Error when checking input: expected conv1d_47_input to have shape (None, 16) but got array with shape (16, 1)
tagged with: keras

http://stackoverflow.com/comment/89491543
type: Comment
comment on: http://stackoverflow.com/q/51256218
score: 0
type: QuestionComment
has text: no, you cannot run a program without running a program, sorry.

http://stackoverflow.com/q/51176949
has body: I am quite new to tensorflow estimator and trying to "Process each frame of video by ConvNet, summing up the reconstruction losses and then optimize parameters". So I am wondering if I can write for loop in model_fn for estimator, so that I can process each frame of video and then optimize together. Thanks P.S. I attach two snippets of own implementation and they both work. It seems like define model_fn for estimator allows for loop even if I embedded cnn_model into model_fn, which is not allowed previously. Vanilla Tensorflow Implementation: import os, sys import tensorflow as tf # Read in video dataset in [batch, frames, height, width] raw_data = np.load(Data_root) dataset = tf.data.Dataset.from_tensor_slices((raw_data)) dataset = dataset.batch(BATCH_SIZE) iterator = dataset.make_initializable_iterator() one_element = iterator.get_next() # Set up placeholder for each frame frame = tf.placeholder('float32', [BATCH_SIZE, IMAGE_HEIGHT, IAMGE_WIDTH]) label = tf.placeholder('float32', [BATCH_SIZE, IMAGE_HEIGHT, IAMGE_WIDTH]) # Define network with tf.name_scope("network"): with tf.name_scope("Encoder"): conv1 = tf.layers.conv2d(frames, 32, [3,3], strides=2, padding='same', activation=tf.nn.relu) conv2 = tf.layers.conv2d(conv1, 64, [3,3], strides=2, padding='same', activation=tf.nn.relu) with tf.name_scope("Repeat_Layer"): latent = tf.layers.conv2d(conv2, 64, [3,3], strides=2, padding='same', activation=tf.nn.relu) with tf.name_scope("Decoder"): conv3 = tf.layers.conv2d_transpose(latent, 32, [3, 3], strides=2, padding='same', activation=tf.nn.relu) conv4 = tf.layers.conv2d_transpose(conv3, 1, [3, 3], strides=2, padding='same', activation=tf.nn.relu) prediction = tf.identity(conv4, name='prediciton') # Define loss loss_mse = tf.losses.mean_squared_error(frame, prediction) # Define optim optimizer = tf.train.RMSPropOptimizer(0.001).minimize(loss_total) # Init init_op = tf.group(tf.global_variables_initializer(), tf.local_variables_initializer()) with tf.Session as sess: se…
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89347315
has answer: http://stackoverflow.com/a/51219451
has comment: http://stackoverflow.com/comment/89366433
has title: Can I use python for loop in model_fn, Estimator, Tensorflow?
tagged with: tensorflow
type: Question
score: 0
tagged with: deep-learning
answer count: 1

http://stackoverflow.com/a/51312129
type: Answer
score: 2
upvote count: 2
has body: If I understand you correctly, that is what the axis parameter is for: &gt;&gt;&gt;np.argmax(array_2D &gt; array_3D,axis=0) array([[1, 0, 0], [0, 2, 1], [0, 2, 0]]) otherwise it runs across the flat array.
accepted answer of: http://stackoverflow.com/q/51311547
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51311547

http://stackoverflow.com/comment/89318652
comment on: http://stackoverflow.com/a/51167774
score: 0
type: AnswerComment
type: Comment
has text: I use SimpleRNN implementation from Keras

http://stackoverflow.com/comment/89327216
type: Comment
has text: @Chuck: no, it's not a coincidence and yes, it will work for any string. The contents of the first match `[^:]+` does not matter *at all*. The only exception is the colon itself.
comment on: http://stackoverflow.com/a/51170839
score: 0
type: AnswerComment

http://stackoverflow.com/comment/89456143
comment on: http://stackoverflow.com/q/51203902
type: QuestionComment
has text: @JeruLuke I used Felzenszwalb's segmentation method in scikit-image. I have add the sample code
score: 0
type: Comment

http://stackoverflow.com/comment/89334342
score: 1
type: AnswerComment
type: Comment
has text: @jackotonye I already explained why I recommend returning a redirect response - if you call `super().form_valid()` then the form is saved again. There are alternative approaches (e.g. response = super(ProductCreateView, self).form_valid(form); form.save_m2m; return response` but I prefer the explicit return.
comment on: http://stackoverflow.com/a/51174259

http://stackoverflow.com/comment/89447558
comment on: http://stackoverflow.com/q/51234071
type: Comment
has text: A heartbeat is environment-specific (Docker, Vagrant, VM) and is **a process** that may not be running consistently in your current environment - you need to verify if this process is running for this specific environment and adjust the configuration accordingly.
score: 0
type: QuestionComment

http://stackoverflow.com/a/51246205
accepted answer of: http://stackoverflow.com/q/51231943
type: AcceptedAnswer
type: Answer
upvote count: 4
downvote count: 0
has body: A pandas bar graph is a categorical plot. This means that the values are essentially plotted against their integer index, independent on what the x values would show numerically. Judging from the comments above this is what you would like to have. A line plot is not categorical. It will plot against the numeric index values. Putting both kinds of plots in the same graph would fail. Also, there is no "categorical line plot" available. But of course you can plot the line by plotting the values against their integer index as well. Suppose you have the following dataframe import pandas as pd import matplotlib.pyplot as plt df = pd.DataFrame({"x" : [1, 2.75, 100], "y1" : [1,2,3], "y2" : [300,100,275]}) df.set_index("x", inplace=True) print(df) # y1 y2 # x # 1.00 1 300 # 2.75 2 100 # 100.00 3 275 You may plot the bar graph of y1 as in the question, but for the line plot make x a propper column first and instead of plotting y2 against the x values, plot it against a newly established integer index. ax = df["y1"].plot(kind="bar") df.reset_index()["y2"].plot(kind="line", ax=ax, secondary_y=True)
answers question: http://stackoverflow.com/q/51231943
score: 4

http://stackoverflow.com/q/51284790
has title: Python combine 2 nested dictionary with multiple values for one key
has body: I have 2 default dict.. I wanna combine these 2 . Please help me . { Fun :{ 1:hi , 2: hello} , fun2 : {3: bye, 4: good bye}} {Fun :{ 1:abc , 2: xyZ} , fun2 : {3: qpr, 4: jkl}} I want to combine these and get 'hi' and 'abc' under key 1 along with 'fun'
answer count: 1
has comment: http://stackoverflow.com/comment/89546808
favorite count: 0
type: UnansweredQuestion
score: -3
linked to: http://stackoverflow.com/q/36769396
has comment: http://stackoverflow.com/comment/89546976
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/51284928
upvote count: 1
has comment: http://stackoverflow.com/comment/89547023
type: Question
downvote count: 4
has comment: http://stackoverflow.com/comment/89546821

http://stackoverflow.com/a/60550691
score: 0
has body: Thanks for all the answers, but it was not sufficient to solve my problem. However it put me on the right path :). To solve the error of the missing sys/types.h I had to copy this types.h file from "c:\Program Files (x86)\Windows Kits\10\Include\10.0.17763.0\ucrt\sys\" to "c:\Program Files (x86)\MySQL\MySQL Connector C 6.1\include\mariadb\sys\". Then I could finally install mysqlclient.
type: Answer
answers question: http://stackoverflow.com/q/51294268

http://stackoverflow.com/q/51306172
tagged with: pyqt
type: AnsweredQuestion
downvote count: 0
has body: I am trying to create a worker thread whose job is to monitor the status bit of a positioning platform. To do this I connect a QTimer timeout signal to a function that queries the platform. class expSignals(QtCore.QObject): pause=QtCore.pyqtSignal() class motorpositioner(QtCore.QObject): def __init__(self): QtCore.QThread.__init__(self) self.timer = QtCore.QTimer() self.timer.start(100) self.timer.timeout.connect(self.do_it) self.lock=QtCore.QMutex() self.running=True self.stat=0 def do_it(self): with QtCore.QMutexLocker(self.lock): #self.stat = self.motors.get_status() print(self.stat) time.sleep(5) @QtCore.pyqtSlot() def stop1(self): self.timer.stop() print('stop heard') The GUI stuff looks like this: class MyApp(QtWidgets.QMainWindow): def __init__(self): QtWidgets.QMainWindow.__init__(self) self.thread=QtCore.QThread(self) #worker self.mot=motorpositioner() # ============================================================================= # Putting buttons and GUI stuff in place # ============================================================================= self.button=QtWidgets.QPushButton('Derp',self) layout = QtWidgets.QHBoxLayout() layout.addWidget(self.button) self.setLayout(layout) self.setGeometry( 300, 300, 350, 300 ) # ============================================================================= # Connecting signals # ============================================================================= self.sig=expSignals() self.sig2=expSignals() self.button.clicked.connect(self.stop) self.sig.pause.connect(self.mot.stop1) self.sig2.pause.connect(self.thread.quit) self.mot.moveToThread(self.thread) self.thread.start() def stop(self): self.sig.pause.emit() def closeEvent(self,event): self.sig2.pause.emit() event.accept() However the way it is written now the GUI is unresponsive. However if I comment out self.timer.timeout.connect(self.do_it) and put do_it in a while(True) loop, the GUI isn't being blocked. Why is the main thread being blocked when using QTimer?
score: 1
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/51308415
tagged with: python
tagged with: qthread
tagged with: qtimer
has title: QTimer in worker thread blocking GUI
tagged with: pyqt5
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/89594058
has comment: http://stackoverflow.com/comment/89592649
linked to: http://stackoverflow.com/q/1595649
has comment: http://stackoverflow.com/comment/89596277
has answer: http://stackoverflow.com/a/51308415

http://stackoverflow.com/q/51211261
answer count: 3
upvote count: 1
has comment: http://stackoverflow.com/comment/89403373
downvote count: 1
has comment: http://stackoverflow.com/comment/89403383
has body: Total beginner question, from what I can gather I've managed to assign a string incorrectly, but I can't see where I've gone wrong. Any help would be appreciated, code below: students = [] def add_student(name, student_id): student = {"name": name, "student_id": student_id} students.append(student) while 1 == 1: try: add_student = input("Do you wish to enter the name of a Student (Yes/No)?") if add_student == "Yes": student_name = input("Enter student name: ") print(student_name) student_id = input("Enter student ID: ") print(student_id) print(student_name + ' ' + student_id) add_student(student_name, student_id) print(student_name+' '+student_id) print(*students) elif add_student == "No": break else: print("Invalid answer 1") except KeyError: print("Invalid answer 2") print(*students)
has answer: http://stackoverflow.com/a/51211402
has comment: http://stackoverflow.com/comment/89403615
linked to: http://stackoverflow.com/q/16140986
has comment: http://stackoverflow.com/comment/89403361
has answer: http://stackoverflow.com/a/51211567
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89403517
has comment: http://stackoverflow.com/comment/89403431
has comment: http://stackoverflow.com/comment/89403652
favorite count: 0
possible better answer: http://stackoverflow.com/a/51211427
accepted answer: http://stackoverflow.com/a/51211402
type: Question
has answer: http://stackoverflow.com/a/51211427
has title: Python Beginner - TypeError: 'str' object is not callable
has comment: http://stackoverflow.com/comment/89403514
tagged with: python
has comment: http://stackoverflow.com/comment/89404062
score: 0

http://stackoverflow.com/a/51317739
has body: Try this: df['MyCol'].replace('[\,\s]+\d+.+', '')
score: 0
answers question: http://stackoverflow.com/q/51317680
type: Answer
has comment: http://stackoverflow.com/comment/89615517

http://stackoverflow.com/comment/89492154
has text: It will not work with `Date`. Can you please check once?
comment on: http://stackoverflow.com/a/51244725
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/51257384
has comment: http://stackoverflow.com/comment/89493732
type: Answer
has comment: http://stackoverflow.com/comment/90941930
accepted answer of: http://stackoverflow.com/q/51256738
has comment: http://stackoverflow.com/comment/89493665
score: 24
answers question: http://stackoverflow.com/q/51256738
upvote count: 24
has comment: http://stackoverflow.com/comment/89493543
type: AcceptedAnswer
downvote count: 0
has body: Decomposing the Error Message Your error message includes the following hint: OpenBLAS blas_thread_init: pthread_create: Resource temporarily unavailable OpenBLAS blas_thread_init: RLIMIT_NPROC 1024 current, 2067021 max The RLIMIT_NPROC variable controls the total number of processes that user can have. More specifically, as it is a per process setting, when fork(), clone(), vfork(), &amp;c are called by a process, the RLIMIT_NPROC value for that process is compared to the total process count for that process's parent user. If that value is exceeded, things shut down, as you've experienced. The error message indicates that OpenBLAS was unable to create additional threads because your user had used all the threads RLIMIT_NPROC had given it. Since you're running on a cluster, it's unlikely that your user is running many threads (unlike, say, if you were on your personal machine and browsing the web, playing music, &amp;c), so it's reasonable to conclude that OpenBLAS is trying to start multiple threads. How OpenBLAS Uses Threads OpenBLAS can use multiple threads to accelerate linear algebra. You may want many threads for solving a single, larger problem quickly. You may want fewer threads for solving many smaller problems simultaneously. OpenBLAS has several ways to limit the number of threads it uses. These are controlled via: export OPENBLAS_NUM_THREADS=4 export GOTO_NUM_THREADS=4 export OMP_NUM_THREADS=4 The priorities are OPENBLAS_NUM_THREADS > GOTO_NUM_THREADS > OMP_NUM_THREADS. (I think this means that OPENBLAS_NUM_THREADS overrides OMP_NUM_THREADS; however, OpenBLAS ignores OPENBLAS_NUM_THREADS and GOTO_NUM_THREADS when compiled with USE_OPENMP=1.) If none of the foregoing variables are set, OpenBLAS will run using a number of threads equal to the number of cores on your machine (32 on your machine) Your Situation Your cluster has 32-core CPUs. You're trying to run 36 instances of Python. Each instance requires 1 thread for Python + 32 threads for OpenBLAS. You…

http://stackoverflow.com/a/51197973
score: 29
type: Answer
upvote count: 29
answers question: http://stackoverflow.com/q/51197783
has body: In your case, the exception in worker returns None. Once that happens, there's no getting the exception back. If your master function knows what the return values should be for each function (for example, ZeroDivisionError in worker returns None, you can manually reraise an exception. If you're not able to edit the worker functions themselves, I don't think there's too much you can do. You might be able to use some of the solutions from this answer, if they work in code as well as on the console. krflol's code above is kind of like how C handled exceptions - there was a global variable that, whenever an exception happened, was assigned a number which could later be cross-referenced to figure out what the exception was. That is also a possible solution. If you're willing to edit the worker functions, though, then escalating an exception to the code that called the function is actually really simple: try: # some code except: # some response raise If you use a blank raise at the end of a catch block, it'll reraise the same exception it just caught. Alternatively, you can name the exception if you need to debug print, and do the same thing, or even raise a different exception. except Exception as e: # some code raise e
downvote count: 0

http://stackoverflow.com/q/51244960
score: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/89468434
type: UnansweredQuestion
tagged with: python
has body: I am doing address string match using python fuzzywuzzy library and also parallelising it using multiprocessing module. Here is my current code, import pandas as pd from multiprocessing import Pool test = pd.DataFrame({'Address1':['123 Cheese Way','234 Cookie Place','345 Pizza Drive','456 Pretzel Junction'],'city':['X','U','X','U']}) test2 = pd.DataFrame({'Address1':['123 chese wy','234 kookie Pl','345 Pizzza DR','456 Pretzel Junktion'],'city':['X','U','Z','Y'] , 'ID' : ['1','3','4','8']}) test=test.assign(dataset = 'test') test2=test2.assign(dataset = 'test2') newdf=pd.concat([test2,test],keys = ['test2','test']) gpd=newdf.groupby('city') def my_func(mygrp): test_data=mygrp.loc['test'] test2_data=mygrp.loc['test2'] test2_data = test2_data.loc[:,['ID','Address1']].set_index('ID') del test2_data.index.name other = {x.Index : x.Address1 for x in test2_data.itertuples()} test_data['applied']=test_data['Address1'].apply(lambda x: process.extract(x, other , limit = 1)) return test_data mypool=Pool(processes=2) ret_list=mypool.imap(my_func,(group for name, group in gpd)) result = pd.concat(ret_list, axis=0) This is working fine. Its working on a big dataset (test and test2 each has more than 3 million records). So utilising an ec2 instance with more processing power - 64GB, however we are now moving to a smaller instance with 32GB, so trying to may be rewrite this in multithreading if possible. From what i read so far, it seems multithreading CPU bound tasks in python is not feasible due to GIL. Any suggestions on this? Is there any other possible solution to speed up this task? Or is it possible to do this string match using word2vec ?
has comment: http://stackoverflow.com/comment/89470217
answer count: 0
has comment: http://stackoverflow.com/comment/89636569
tagged with: multithreading
tagged with: multiprocessing
type: Question
has title: Using multithreading in python
has comment: http://stackoverflow.com/comment/89468502
tagged with: python-multiprocessing

http://stackoverflow.com/comment/89529073
type: QuestionComment
has text: `it can't be a set as it's a translation of an audio file`. I dont understand the logic behind this statement.
score: 1
comment on: http://stackoverflow.com/q/51275578
type: Comment

http://stackoverflow.com/q/51294486
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/18517722
has comment: http://stackoverflow.com/comment/121444190
has comment: http://stackoverflow.com/comment/89566795
tagged with: average
type: Question
upvote count: 4
tagged with: numpy
downvote count: 0
answer count: 1
score: 4
favorite count: 0
tagged with: python
linked to: http://stackoverflow.com/q/26447191
has answer: http://stackoverflow.com/a/51294863
has body: I have a 2D array of temperature over time data. There are about 7500 x-values and as much corresponding y-values (so one y for every x). It looks like this: The blue line in the middle is the result of my unsuccessful attempt to draw a plot line, which would represent the average of my data. Code: import numpy as np import matplotlib.pyplot as plt data=np.genfromtxt("data.csv") temp_av=[np.mean(data[1])]*len(data[0]) plt.figure() plt.subplot(111) plt.scatter(data[0],data[1]) plt.plot(data[0],temp_av) plt.show() However what I need is a curve, which will follow the rise in the temperature. Basically a line which will be somewhere in the middle of data points. I googled for some solutions, but all I found were suggestions how to compute an average in cases where you have multiple y-values for one x. I understand how to do that, but it doesn't help in this case. My next idea would be to use a loop to compute an average for every 2 neighbor points. But I am not sure how to do that best and if there aren't better solutions. Also, I understand that what I need is to compute an other array. Plotting is only for representation.
has comment: http://stackoverflow.com/comment/89566763
has title: Plot average of an array in python

http://stackoverflow.com/comment/89565442
comment on: http://stackoverflow.com/q/51293937
type: Comment
score: 2
has text: @hootnot: It's technically valid syntax in Python 3, but it's a bizarre thing to do.
type: QuestionComment

http://stackoverflow.com/comment/89509315
comment on: http://stackoverflow.com/a/51221498
type: AnswerComment
has text: When I use this I just get empty dict return for each order - I've updated my code with your loop and changed the variables to have the correct names. Any what I am doing wrong? Thanks
score: 0
type: Comment

http://stackoverflow.com/q/51191198
has answer: http://stackoverflow.com/a/51204465
tagged with: database
score: 0
has title: sqlalchemy cx_oracle cannot get results
tagged with: cx-oracle
answer count: 1
accepted answer: http://stackoverflow.com/a/51204465
tagged with: python
type: AnsweredQuestion
has body: sqlalchemy+cx_Oracle may not be in your domain. However, if you can help me giving few web links/helps will be nice. from sqlalchemy import create_engine from sqlalchemy import MetaData from sqlalchemy import Table import cx_Oracle engine = create_engine('oracle+cx_oracle://user:passwd@FTSDBLAB') meta = MetaData() meta.reflect(bind=engine) tbl_mgr_theater = Table('mgr_table', meta, autoload=True, autoload_with=engine) connection = engine.connect() result = connection.execute(tbl_mgr_theater.select()) print(result.rowcount()) gives the following ERROR: Traceback (most recent call last): File "", line 1, in TypeError: 'int' object is not callable Error closing cursor Traceback (most recent call last): AttributeError: 'cx_Oracle.Cursor' object has no attribute 'lastrowid'
tagged with: sqlalchemy
type: Question

http://stackoverflow.com/a/51203257
type: Answer
score: 1
upvote count: 1
downvote count: 0
answers question: http://stackoverflow.com/q/51202596
has body: This is actually pretty close, but I recommend testing def partition3(a, l, r) by itself. You'll see that the values it is returning don't really make sense. However, with a small change, we can get it to work: m1 = len(less) should be: m1 = len(less) + l # l for left, not 1 for one You don't want m1 to just be the length of the items in less because if you had been comparing the 9th to the 11th item you'd return 1 when you mean to return 10. Also, in general, try to avoid single letter variable names (especially l which is easy to confuse for 1). It makes it hard to read and hard for people unfamiliar with your code to see what is happening.

http://stackoverflow.com/q/51216168
has answer: http://stackoverflow.com/a/51216273
tagged with: python
answer count: 4
linked to: http://stackoverflow.com/q/24896613
type: AnsweredQuestion
score: 2
downvote count: 0
type: Question
has comment: http://stackoverflow.com/comment/89413491
has title: Function missing 1 required positional argument
tagged with: positional-argument
has body: I'm getting this error : Traceback (most recent call last): File "C:/Users/mali03/Desktop/Python/Practice/p2.py", line 18, in &lt;module&gt; first.subtraction(1, 2) TypeError: subtraction() missing 1 required positional argument: 'y' Here is my calculator class class calculator: def __init__(self, x, y): self.x = x self.y = y def addition(self, x, y): return self.x + self.y def subtraction(self, x, y): if self.x &gt; self.y: return self.y - self.x else: return self.x - self.y I then call subtraction with the following: first = calculator first.subtraction(1, 2)
has answer: http://stackoverflow.com/a/51216208
has comment: http://stackoverflow.com/comment/89413525
has answer: http://stackoverflow.com/a/51216362
accepted answer: http://stackoverflow.com/a/51216386
upvote count: 2
tagged with: typeerror
duplicate of: http://stackoverflow.com/q/24896613
possible better answer: http://stackoverflow.com/a/51216273
has answer: http://stackoverflow.com/a/51216386
favorite count: 0

http://stackoverflow.com/q/51254859
has answer: http://stackoverflow.com/a/51254931
has title: Use an object even though `__init__()` raises an exception?
accepted answer: http://stackoverflow.com/a/51255140
has body: I'm in a situation where some meager important parts of a classes __init__ method could raise an exception. In that case I want to display an error message but carry on using the instance. A very basic example: class something(object): def __init__(self): do_something_important() raise IrrelevantException() def do_something_useful(self): pass try: that_thing = something() except IrrelevantException: print("Something less important failed.") that_thing.do_something_useful() However, the last line does not work, because that_thing is not defined. Strange thing is, I could swear I've done things like this before and it worked fine. I even thougt about ways to keep people from using such an unfinished instance, because I found out it gets created even in case of errors. Now I wanted to use that and it does not work. Hmmm...?!? PS: something was written by myself, so I'm in control of everything.
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89489153
tagged with: python
answer count: 4
has comment: http://stackoverflow.com/comment/89488856
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/94396898
has comment: http://stackoverflow.com/comment/89490525
has comment: http://stackoverflow.com/comment/89488684
possible better answer: http://stackoverflow.com/a/51255059
has answer: http://stackoverflow.com/a/51255140
downvote count: 1
has answer: http://stackoverflow.com/a/51255059
type: Question
upvote count: 5
score: 4
has answer: http://stackoverflow.com/a/51255026
tagged with: python-3.6

http://stackoverflow.com/q/51267202
has answer: http://stackoverflow.com/a/53050194
type: Question
tagged with: ticker
tagged with: history
tagged with: poloniex
score: 0
answer count: 1
type: UnansweredQuestion
has title: How do I get all the tickers from poloniex
has body: I am using the function: polo.returnTicker()['BTC_ETH'] that I got from this python package https://github.com/s4w3d0ff/python-poloniex to get the current ticker from Poloniex. The function returns a json object that looks like this: {u'last': u'0.07120000', u'quoteVolume': u'3523.11980704', u'high24hr': u'0.07170000', u'isFrozen': u'0', u'highestBid': u'0.07120026', u'percentChange': u'-0.00154256', u'low24hr': u'0.07078026', u'lowestAsk': u'0.07120370', u'id': 148, u'baseVolume': u'251.02174618'} However, I need a array with all tickers from the past in one-minute intervals , which I don't know how to get. My function can only return the current ticker, and not past tickers, which I need. Does anyone know how to do that?
tagged with: python

http://stackoverflow.com/q/51249628
has comment: http://stackoverflow.com/comment/89480720
type: Question
duplicate of: http://stackoverflow.com/q/35819538
score: 0
has comment: http://stackoverflow.com/comment/89480627
has body: I'm having this weird problem, I'm creating file menu action items from a list that I have. It displays properly but behaves the wrong way. Here's an example snippet of my code: self.dMenu = self.menuBar().addMenu('&amp;Fruit') for entry in ['apple', 'banana', 'orange', 'strawberry']: item = QAction(QIcon(), entry, self) item.triggered.connect(lambda: print(item.text())) #Prints the menu action's text when clicked self.dMenu.addAction(item) In the file menu it shows up as: apple banana orange strawberry When I click on the item it should display the action item's text but it always prints strawberry regardless of which I press. (Even though it shows the text as apple for example.) I also tried creating an array of QAction menu items to see if that would solve the problem. self.dMenu = self.menuBar().addMenu('&amp;Fruit') actionItems = {} for entry in ['apple', 'banana', 'orange', 'strawberry']: actionItems[entry] = QAction(QIcon(), entry, self) actionItems[entry].triggered.connect(lambda: print(actionItems[entry].text())) #Prints the menu action's text when clicked self.dMenu.addAction(actionItems[entry]) Same results though. I'm not really sure what's causing all the action items to behave the same even though each is being created as it's own instance. I initially set the action to just print entry but that didn't do anything, I was hoping printing the instance's text would fix the problem but it seems like that didn't work either. Edit: Just want to mention the array I'm using is much larger and is changing frequently so I can't just hard code each entry in the menu.
type: UnansweredQuestion
has title: QT: Creating menu items in a loop behave differently
tagged with: python
tagged with: qt
has comment: http://stackoverflow.com/comment/89478459
answer count: 0
linked to: http://stackoverflow.com/q/35819538

http://stackoverflow.com/comment/89343676
type: Comment
score: 0
comment on: http://stackoverflow.com/q/51178485
type: QuestionComment
has text: Possible duplicate of [TypeError: can't use a string pattern on a bytes-like object in re.findall()](https://stackoverflow.com/questions/31019854/typeerror-cant-use-a-string-pattern-on-a-bytes-like-object-in-re-findall)

http://stackoverflow.com/q/51248667
has body: Scenario Previous Question I've converted the image to HSV and I want to change the values of that in Image. Code import numpy as np import cv2 image = cv2.imread('4.png') #cv2.imshow("images",image) hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV) hsv[:,:,0] = 0 # Changes the V value out = cv2.cvtColor(hsv, cv2.COLOR_HSV2BGR) cv2.imshow("images", np.hstack([hsv, out])) cv2.waitKey(0) Output It indeed change the color based on the V value but what If I want to specify exact color I still can't figure out the co-relation between the HSV values and my RGB or Hex color values. Any help will be appreciated.
score: 1
tagged with: image-processing
upvote count: 1
type: Question
tagged with: opencv
has answer: http://stackoverflow.com/a/52224846
has title: Python replace or change the HSV value for given RGB or Hexadecimal value
answer count: 1
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/51242608

http://stackoverflow.com/q/51281482
tagged with: python
has comment: http://stackoverflow.com/comment/89540815
has title: Pyinstaller: Exe files do not run; encoding error
linked to: http://stackoverflow.com/q/48872724
has comment: http://stackoverflow.com/comment/89541519
has comment: http://stackoverflow.com/comment/89558403
score: 0
has comment: http://stackoverflow.com/comment/89540878
has comment: http://stackoverflow.com/comment/89543251
type: Question
has comment: http://stackoverflow.com/comment/89540553
tagged with: encoding
has comment: http://stackoverflow.com/comment/89540851
has comment: http://stackoverflow.com/comment/89540332
has comment: http://stackoverflow.com/comment/89540870
has body: Edit: Due tu being marked as duplicate= My problem is not related to pyinstaller not being supported, same problem persist in cx_Freeze 3.7 for some reason my .exe files don't run. C:\Users\Fif\Desktop\Python\To compile&gt;pyinstaller -F Test.py 72 INFO: PyInstaller: 3.3.1 72 INFO: Python: 3.7.0 72 INFO: Platform: Windows-10-10.0.16299-SP0 72 INFO: wrote C:\Users\Fif\Desktop\Python\To compile\Test.spec 72 INFO: UPX is not available. 72 INFO: Extending PYTHONPATH with paths ['C:\\Users\\Fif\\Desktop\\Python\\To compile', 'C:\\Users\\Fif\\Desktop\\Python\\To compile'] 72 INFO: checking Analysis 87 INFO: Building because pathex changed 87 INFO: Initializing module dependency graph... 87 INFO: Initializing module graph hooks... 87 INFO: Analyzing base_library.zip ... 3634 INFO: running Analysis out00-Analysis.toc 3649 INFO: Adding Microsoft.Windows.Common-Controls to dependent assemblies of final executable required by c:\python37\python.exe 3681 WARNING: lib not found: api-ms-win-crt-math-l1-1-0.dll dependency of c:\python37\python.exe 3712 WARNING: lib not found: api-ms-win-crt-heap-l1-1-0.dll dependency of c:\python37\python.exe 3728 WARNING: lib not found: api-ms-win-crt-stdio-l1-1-0.dll dependency of c:\python37\python.exe 3759 WARNING: lib not found: api-ms-win-crt-locale-l1-1-0.dll dependency of c:\python37\python.exe 3774 WARNING: lib not found: api-ms-win-crt-runtime-l1-1-0.dll dependency of c:\python37\python.exe 3978 WARNING: lib not found: api-ms-win-crt-environment-l1-1-0.dll dependency of c:\python37\python37.dll 3993 WARNING: lib not found: api-ms-win-crt-locale-l1-1-0.dll dependency of c:\python37\python37.dll 4023 WARNING: lib not found: api-ms-win-crt-filesystem-l1-1-0.dll dependency of c:\python37\python37.dll 4039 WARNING: lib not found: api-ms-win-crt-time-l1-1-0.dll dependency of c:\python37\python37.dll 4055 WARNING: lib not found: api-ms-win-crt-math-l1-1-0.dll dependency of c:\python37\python37.dll 4086 WARNING: lib not found: api-ms-win-crt-std…
tagged with: exe
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89541396
answer count: 0
has comment: http://stackoverflow.com/comment/89542446
tagged with: pyinstaller
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89541864
has comment: http://stackoverflow.com/comment/89540985

http://stackoverflow.com/comment/89510541
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51265891
has text: is class `B` a subclass of `PMixin`. If it is a sub class just put it before `PMixin` in `class (PMixin, B)`.
score: 0

http://stackoverflow.com/q/51183014
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89348621
tagged with: python
tagged with: gspread
has comment: http://stackoverflow.com/comment/89348346
answer count: 0
has comment: http://stackoverflow.com/comment/89348221
has title: for loop wont move on to next iteration gspread
has body: This will print the first sheets results, but it wont loop past the first page. The output is fine and accurate for the first page, it just wont loop past that and I don't know why. I'm new, so forgive me if this is obvious, but I've read up on documents and can't find the answer. Thank you. import gspread from oauth2client.service_account import ServiceAccountCredentials sheets_of_months= ['May 2018 Chem Readings', 'April 2018 Chem Readings', 'June 2018 Chem Readings'] scope= ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive'] creds= ServiceAccountCredentials.from_json_keyfile_name('client_secret.json', scope) client= gspread.authorize(creds) def get_customers(): for name_of_sheet in sheets_of_months: spread_sheet= client.open(name_of_sheet) work_sheet= spread_sheet.sheet1 result= work_sheet.row_count print result, name_of_sheet get_customers() I realized the issue is in this line work_sheet= spread_sheet.sheet1 for whatever reason this stops it. Edit: def get_customers(): for name_of_sheet in sheets_of_months: spread_sheet= client.open(name_of_sheet) print name_of_sheet work_sheet= spread_sheet.sheet1 print name_of_sheet The output for this is crazy. May 2018 Chem Readings April 2018 Chem Readings June 2018 Chem Readings June 2018 Chem Readings It loops through once up to the first print, then hits the work_sheet= spread_sheet.sheet1 line, after that it starts over again and prints only once. Odd....
type: Question
has comment: http://stackoverflow.com/comment/89348496
has comment: http://stackoverflow.com/comment/89348679
has comment: http://stackoverflow.com/comment/89348309
has comment: http://stackoverflow.com/comment/89348616
has comment: http://stackoverflow.com/comment/89348366
tagged with: python-2.7
score: 0

http://stackoverflow.com/q/51250796
has answer: http://stackoverflow.com/a/51251008
accepted answer: http://stackoverflow.com/a/51251008
has answer: http://stackoverflow.com/a/57834015
linked to: http://stackoverflow.com/q/51261584
type: Question
tagged with: debugging
has answer: http://stackoverflow.com/a/73526109
has title: Pythons Console Module has made it impossible to type the tab key
score: 9
downvote count: 1
has answer: http://stackoverflow.com/a/68729100
answer count: 6
possible better answer: http://stackoverflow.com/a/57834015
favorite count: 0
has answer: http://stackoverflow.com/a/51250981
upvote count: 10
tagged with: python
has answer: http://stackoverflow.com/a/58435160
has body: I started using it on one of my programs a while back. Ever since, whenever I type the tab key on a console (cmd.exe instance) with python running, I get a readline internal error. Full traceback is as follows (note I haven't imported the cmd module in this context or even imported a script using it. I've simply started python, pressed tab and voila an exception): &lt;pre&gt; Traceback (most recent call last): File "C:\SP_CI_PROGRAMS\Languages\Python\3.6.1\lib\site-packages\pyreadline\console\console.py", line 768, in hook_wrapper_23 res = ensure_str(readline_hook(prompt)) File "C:\SP_CI_PROGRAMS\Languages\Python\3.6.1\lib\site-packages\pyreadline\rlmain.py", line 571, in readline self._readline_from_keyboard() File "C:\SP_CI_PROGRAMS\Languages\Python\3.6.1\lib\site-packages\pyreadline\rlmain.py", line 536, in _readline_from_keyboard if self._readline_from_keyboard_poll(): File "C:\SP_CI_PROGRAMS\Languages\Python\3.6.1\lib\site-packages\pyreadline\rlmain.py", line 556, in _readline_from_keyboard_poll result = self.mode.process_keyevent(event.keyinfo) File "C:\SP_CI_PROGRAMS\Languages\Python\3.6.1\lib\site-packages\pyreadline\modes\emacs.py", line 243, in process_keyevent r = self.process_keyevent_queue[-1](keyinfo) File "C:\SP_CI_PROGRAMS\Languages\Python\3.6.1\lib\site-packages\pyreadline\modes\emacs.py", line 286, in _process_keyevent r = dispatch_func(keyinfo) File "C:\SP_CI_PROGRAMS\Languages\Python\3.6.1\lib\site-packages\pyreadline\modes\basemode.py", line 257, in complete completions = self._get_completions() File "C:\SP_CI_PROGRAMS\Languages\Python\3.6.1\lib\site-packages\pyreadline\modes\basemode.py", line 200, in _get_completions r = self.completer(ensure_unicode(text), i) File "C:\SP_CI_PROGRAMS\Languages\Python\3.6.1\Lib\rlcompleter.py", line 80, in complete readline.redisplay() AttributeError: module 'readline' has no attribute 'redisplay' &lt;/pre&gt; Before u ask, I installed python to the directory "C:\SP_CI_PROGRAMS\Languages\Python\3.6.1". It's acc…
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/56838545

http://stackoverflow.com/comment/97176346
comment on: http://stackoverflow.com/a/55200461
has text: Oh, interesting... Can you give me an example for a slice that works with yours, but not with mine? I'd like to see where the problem is.
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/89351550
type: QuestionComment
has text: I call different instances of a class through large_function(). Yes, I have one instance of the class which does processing per time-series. When looking at one of these instances, the calls must arrive sequentially. I need to either map an instance to a single core, or somehow remember and pass the right values if the calls will be across cores.
comment on: http://stackoverflow.com/q/51171989
score: 0
type: Comment

http://stackoverflow.com/a/77263396
answers question: http://stackoverflow.com/q/51294268
score: 0
has body: Just want to share how I resolve it. I downgraded it to Python version 3.10 rather than using the new version 3.12. I tried all the solutions above but it did not fix the issue. So I tried to copy all my settings on my laptop and replicate it on my desktop and that solved my issue. Maybe in the future, they will fix it on the 3.12. But for now, it works fine. By the way, the first error I got was Microsoft Visual 14 or higher after I fixed that issue it was a quick fix. That error came out fatal error C1083: Cannot open include file: 'mysql.h' When I install all the requirments. I tried downloading the .whl file but still does not work. Maybe this would also help other people who still have this issue. By the way, almost all servers where you host your Python/Django app have lower Python Versions.
type: Answer

http://stackoverflow.com/q/51305682
type: Question
has comment: http://stackoverflow.com/comment/89588645
possible better answer: http://stackoverflow.com/a/64984765
has title: how to use to_categorical when using ImageDataGenerator
has answer: http://stackoverflow.com/a/64984765
downvote count: 0
tagged with: keras
linked to: http://stackoverflow.com/q/54232549
favorite count: 0
score: 11
answer count: 3
accepted answer: http://stackoverflow.com/a/51306128
upvote count: 11
has answer: http://stackoverflow.com/a/73893364
tagged with: machine-learning
tagged with: python
type: AnsweredQuestion
has body: I am using Keras for classifying images (multiple classes) and I'm using ImageDataGenerator. It automatically finds all of classes, and it doesn't seem to write labels in any variable. I figured I need to use to_categorical to store my labels in matrix form, but I just don't know where to use it. Here is a snippet of my code: ... datagen = ImageDataGenerator( rotation_range=40, width_shift_range=0.2, height_shift_range=0.2, rescale=1./255, shear_range=0.2, zoom_range=0.2, horizontal_flip=True, fill_mode='nearest') # generator for training train_generator = datagen.flow_from_directory( train_dir, target_size=(img_width, img_height), batch_size=batch_size, class_mode='categorical') # generator for validation val_generator = datagen.flow_from_directory( val_dir, target_size=(img_width, img_height), batch_size=batch_size, class_mode='categorical') # generator for testing test_generator = datagen.flow_from_directory( test_dir, target_size=(img_width, img_height), batch_size=batch_size, class_mode='categorical') # train model.fit_generator( train_generator, steps_per_epoch=nb_train_samples // batch_size, epochs=epochs, validation_data=val_generator, validation_steps=nb_validation_samples // batch_size) Generators just say "Found 442 images belonging to 5 classes." or smth like that. How can I use to_categorical on my labels?
tagged with: tensorflow
has answer: http://stackoverflow.com/a/51306128

http://stackoverflow.com/comment/89610041
has text: @TimPeters: Wow that was easy! I completely missed that! Thanks!!!!!
score: 1
comment on: http://stackoverflow.com/q/51316881
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51255403
score: 1
has body: use np.array instead of list sun_x = np.logspace(0, np.log10(46050), 100) You can't divide elements in a list by an int directly, but you can using a numpy array.
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/51255395
has comment: http://stackoverflow.com/comment/89489774
downvote count: 0
has comment: http://stackoverflow.com/comment/89489775
has comment: http://stackoverflow.com/comment/89489763

http://stackoverflow.com/a/51306855
has comment: http://stackoverflow.com/comment/89590391
type: AcceptedAnswer
downvote count: 0
has body: If you are going to connect to the same database it is not necessary that you create several connections, only one since qt manages those connections globally as indicated by the docs: QSqlDatabase QSqlDatabase::addDatabase(const QString &type, const QString &connectionName = QLatin1String(defaultConnection)) Adds a database to the list of database connections using the driver type and the connection name connectionName. If there already exists a database connection called connectionName, that connection is removed. The database connection is referred to by connectionName. The newly added database connection is returned. If type is not available or could not be loaded, isValid() returns false. If connectionName is not specified, the new connection becomes the default connection for the application, and subsequent calls to database() without the connection name argument will return the default connection. If a connectionName is provided here, use database(connectionName) to retrieve the connection. Warning: If you add a connection with the same name as an existing connection, the new connection replaces the old one. If you call this function more than once without specifying connectionName, the default connection will be the one replaced. Example: . ├── connection.py ├── main.py └── views.p connection.py from PyQt5 import QtWidgets, QtSql def createConnection(): db = QtSql.QSqlDatabase.addDatabase("QSQLITE") db.setDatabaseName(":memory:") if not db.open(): QtWidgets.QMessageBox.critical(None, "Cannot open database", "Unable to establish a database connection.\n" "This example needs SQLite support. Please read " "the Qt SQL driver documentation for information how " "to build it.\n\n" "Click Cancel to exit.", QtWidgets.QMessageBox.Cancel) return False query = QtSql.QSqlQuery() query.exec_("""CREATE TABLE IF NOT EXISTS person (id int primary key, firstname VARCHAR(20), lastname VARCHAR(20))""") query.exec_("insert into person values(101, 'Danny', 'Young')") query.exec_…
has comment: http://stackoverflow.com/comment/89591398
type: Answer
upvote count: 6
has comment: http://stackoverflow.com/comment/89590360
score: 6
accepted answer of: http://stackoverflow.com/q/51306683
answers question: http://stackoverflow.com/q/51306683

http://stackoverflow.com/comment/89490039
comment on: http://stackoverflow.com/q/51255497
type: Comment
type: QuestionComment
has text: Is this Python 3+?
score: 0

http://stackoverflow.com/comment/89618477
comment on: http://stackoverflow.com/q/51320544
has text: what is the value of `k` at the end of the run?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89362253
type: Comment
has text: The missing values were 0, I replaced them with NaN as you said. Works perfect. But the second step won't do. I expected a number for the rows with gps_height is NaN, but I still get NaN at those rows.
comment on: http://stackoverflow.com/a/51190119
score: 0
type: AnswerComment

http://stackoverflow.com/a/51230145
upvote count: 2
answers question: http://stackoverflow.com/q/51230090
has body: You can do it using Q object from django.db.models import Q NetworkRelatedInformation.objects.filter(Q(month__isnull=True) | Q(month=month), Q(year__isnull=True) | Q(year=year)).aggregate(Sum('tt_count'))
type: Answer
score: 2
downvote count: 0

http://stackoverflow.com/q/51199137
tagged with: pyqt5
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/89380319
has comment: http://stackoverflow.com/comment/89380128
has answer: http://stackoverflow.com/a/51199492
type: AnsweredQuestion
has body: I'm trying to translate a Qt plugin from C++ to python, however my knowledge on C++ is minimal, can you please help me to confirm if my translation is Ok? (the plugin is not working as expected). C++ code: /*************************************************************************** * Copyright (C) 2006-2008 by Tomasz Ziobrowski * * http://www.3electrons.com * * e-mail: t.ziobrowski@3electrons.com * * * * * * 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., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ #include <QPainter> #include <QPen> #include <QSvgRenderer> #include "counter.h" Counter::Counter (QWidget * parent):QWidget(parent) { init(); } int Counter::digits() const { return m_digits; } int Counter::value() const { return m_value; } const QString Counter::digitsFile() const { return m_digitsFile; } /*-------------------------------------------------------------------------------------------- P U B L I C S L O T S --------------------------------------------------------------------------------------------*/ void Counter::setValue(int i) { m_value = i; update(); } void Counter::setDigits(int i) { m_digits = i; update(); } void Counter::setDigitsFile(const QString & i ) { m_digitsFile = i; if (m_svg) delete m_svg; m_svg = new QSvgRenderer(this); if (!m_svg->load(m_dig…
score: 1
has title: Translating a C++ line to Python 3
favorite count: 0
tagged with: python-3.x
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/89380085
tagged with: python
accepted answer: http://stackoverflow.com/a/51199492
tagged with: qt
tagged with: c++
has comment: http://stackoverflow.com/comment/89380238
has comment: http://stackoverflow.com/comment/89380754

http://stackoverflow.com/a/51208178
accepted answer of: http://stackoverflow.com/q/51207964
answers question: http://stackoverflow.com/q/51207964
type: AcceptedAnswer
has body: You can use pivot_table(): For the data: import pandas as pd df = pd.DataFrame({'Color': ['red', 'red', 'blue', 'blue'], 'Shape': ['triangle', 'circle', 'triangle', 'circle'], 'Value': [10, 11, 12, 13]}) df.pivot_table(index = 'Color', columns = 'Shape', values = 'Value') The result is: Shape circle triangle Color blue 13 12 red 11 10
type: Answer
score: 2
downvote count: 0
upvote count: 2

scrapy-splash
tags question: http://stackoverflow.com/q/51259488
tag name: scrapy-splash
type: Tag

http://stackoverflow.com/comment/97583018
has text: What solution was the one that worked???
score: 1
comment on: http://stackoverflow.com/q/51209933
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51178176
upvote count: 4
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51178132
type: Answer
accepted answer of: http://stackoverflow.com/q/51178132
has body: The shape is the size of the dimensions. [[1., 2., 3.], [4., 5., 6.]] # a rank 2 tensor; a matrix with shape [2, 3] Because it has 2 rows and 3 columns. So it is not about the elements but the size of each dimension. So rank is the number of dimensions, and shape is size of the dimension. If you look at the next example [[[1., 2., 3.]], [[7., 8., 9.]]] # a rank 3 tensor with shape [2, 1, 3] It has 2 rows, 1 set of elements in this dimension, and 3 columns. This resource might help https://www.tensorflow.org/versions/r1.1/programmers_guide/dims_types https://www.gsrikar.com/2017/06/what-is-tensor-rank-and-tensor-shape.html
score: 4

http://stackoverflow.com/comment/89381048
has text: That would make sense to me - see my comment above about IBM i specificity.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51184578
type: Comment

http://stackoverflow.com/a/51269062
has body: You could try to find contour in your image patch with cv2.findContour() (red spot). Then remove the background of the contour and save the image. You can finally combine the one you saved (red spot without background) with the gray background image with cv2.add(). I have combined some code I once played with and the code in OpenCV docs (for cv2.add()). Hope it helps a bit (Note the example ads the image in upper left corner - if you want elswhere you should change the code). Cheers! Example: import cv2 import numpy as np from PIL import Image img = cv2.imread('background2.png', cv2.IMREAD_UNCHANGED) gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) ret, threshold = cv2.threshold(gray, 100, 255, cv2.THRESH_BINARY_INV) height,width = gray.shape mask = np.zeros((height,width), np.uint8) _, contours, hierarchy = cv2.findContours(threshold,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE) cnt = max(contours, key=cv2.contourArea) cv2.drawContours(mask,[cnt], -1, (255,255,255),thickness=-1) masked = cv2.bitwise_and(img, img, mask=mask) _,thresh = cv2.threshold(mask,1,255,cv2.THRESH_BINARY) contours = cv2.findContours(thresh,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE) x,y,w,h = cv2.boundingRect(contours[0]) circle = masked[y:y+h,x:x+w] cv2.imwrite('temp.png', circle) cv2.waitKey(0) cv2.destroyAllWindows() img = Image.open('temp.png') img = img.convert("RGBA") datas = img.getdata() newData = [] for item in datas: if item[0] == 0 and item[1] == 0 and item[2] == 0: newData.append((255, 255, 255, 0)) else: newData.append(item) img.putdata(newData) img.save('background3.png', "PNG") img1 = cv2.imread('background1.png') img2 = cv2.imread('background3.png') rows,cols,channels = img2.shape roi = img1[0:rows, 0:cols ] img2gray = cv2.cvtColor(img2,cv2.COLOR_BGR2GRAY) ret, mask = cv2.threshold(img2gray, 110, 255, cv2.THRESH_BINARY_INV) mask_inv = cv2.bitwise_not(mask) img1_bg = cv2.bitwise_and(roi,roi,mask = mask_inv) img2_fg = cv2.bitwise_and(img2,img2,mask = mask) dst = cv2.add(img1_bg,img2_fg) img1[…
type: Answer
has comment: http://stackoverflow.com/comment/89517505
answers question: http://stackoverflow.com/q/51266831
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/89517683
downvote count: 0

http://stackoverflow.com/a/70238013
type: Answer
score: 1
has body: You can use a ttk custom style to configure the size: import tkinter, tkinter.ttk #Setup a custom style notebookStyle = ttk.Style() notebookStyle.configure('Custom.TNotebook.Tab', padding=[30,4]) tabControl = ttk.Notebook(parent, style = "Custom.TNotebook") As explained in this answer.
answers question: http://stackoverflow.com/q/51181368
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/89420859
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51218189
has text: And since you are using this as some kind of dropout, the flow of gradient will be negligible, which should be good enough. However, there is no substitute for experimentation ;)
score: 0

http://stackoverflow.com/comment/89495433
type: Comment
comment on: http://stackoverflow.com/a/51257974
score: 0
has text: Basically, i change the 'active_id' to 'id', sorry for first time comment in StackOverflow.
type: AnswerComment

http://stackoverflow.com/q/51299887
favorite count: 0
has comment: http://stackoverflow.com/comment/90325873
has title: Update field of another model from cutomized View in Odoo
has answer: http://stackoverflow.com/a/51300560
accepted answer: http://stackoverflow.com/a/51300560
tagged with: python
has body: I want to update inventory quantity from my customized view in odoo 11 and want to do it by using automated action in odoo studio but have no clue how to write python code in automated actions. Thanks.
type: AnsweredQuestion
upvote count: 0
tagged with: odoo
type: Question
score: -1
answer count: 1
downvote count: 1

http://stackoverflow.com/a/51291703
answers question: http://stackoverflow.com/q/51285835
score: -1
downvote count: 1
has comment: http://stackoverflow.com/comment/89614877
type: Answer
upvote count: 0
has body: There is no direct way to disable these logs. However, a simple workaround is to remove the CloudWatch Logs permission from the Lambda execution role. Lambda function uses this role to access other AWS services, if you remove CloudWatch permission it will not be able to push logs to CloudWatch. Note: if you do this you will not able to push any logs from lambda to CloudWatch

http://stackoverflow.com/comment/89338977
comment on: http://stackoverflow.com/q/51177849
score: 0
has text: you're doing `LinearSegmentedColormap.from_list(..., N=7)` but 7 doesn't "nicely" go into 0.3. Try `N=6`?
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/89401009
score: 1
has text: This totally solved the problem
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51209909

http://stackoverflow.com/q/51194745
has body: I need a function which returns the first and last day respectively the Monday and Sunday of a given week number (and a year). There is a difficulty for weeks where Jan 1st is not a Monday so I cannot use the standard datetime.datetime.strptime().
downvote count: 1
type: AnsweredQuestion
upvote count: 10
has answer: http://stackoverflow.com/a/59531847
score: 9
type: Question
accepted answer: http://stackoverflow.com/a/51194746
linked to: http://stackoverflow.com/q/17087314
answer count: 2
possible better answer: http://stackoverflow.com/a/59531847
has title: Get first and last day of given week number in python
favorite count: 0
tagged with: datetime
tagged with: python
has answer: http://stackoverflow.com/a/51194746

http://stackoverflow.com/comment/89378886
type: QuestionComment
has text: Isn't it then `{"'{}':'{}'".format(k,v):ObjectIdentifier(k,v) for k,v in dictA.items()}`?
comment on: http://stackoverflow.com/q/51198179
score: 0
type: Comment

http://stackoverflow.com/q/51201747
score: 0
has comment: http://stackoverflow.com/comment/89433083
tagged with: multidimensional-array
has body: I need to do iteratively (about 3 millions times) X=[X B] which B=[b1,b2,b3,b4,b5] and save this in a file to access in future. I encounter two problems: 1- The first problem is that the size of X is size=(2,) and I do not know how to access different element (i.e. b1..b5 of each time) because all of them are supposed to be element number zero of each time! For solving this problem I have tried to use X.append(B) but I saw an error. I have tried to use X.append(B[0])...X.append(B[4]) but the problem was not solved! How I can do this? 2- The second one is that I use np.save('Xsaved.npy',X) but when I see `np.save('Xsaved.npy',X) File "C:\Users\L\Anaconda3\envs\tensorflow\lib\site-packages\numpy\lib\npyio.py", line 509, in save pickle_kwargs=pickle_kwargs) File "C:\Users\L\Anaconda3\envs\tensorflow\lib\site-packages\numpy\lib\format.py", line 576, in write_array pickle.dump(array, fp, protocol=2, **pickle_kwargs) RecursionError: maximum recursion depth exceeded while pickling an object when Time is more than 450! however I need to iterate it for about 2.5 millions time. I would like to know how I could solve these two problems! p.s. I write a pseudo code to see what I have done! episodes=40000 T=3000000 for e in range(episodes): REWARDALLkol.append(REWARDALL) REWARDALL=[] X=[] for time_t in range(1,T+1): B= functioncalculatedB() #B=[b0,b1,b2,b3,b4] X=[X, B] np.save('./save/X.npy',X)
tagged with: python
answer count: 0
type: UnansweredQuestion
has title: get ride of Recursion Error in large number of iteration and access to element of joint of 2 lists iteratively python
tagged with: list
type: Question
tagged with: numpy
tagged with: numpy-ndarray
has comment: http://stackoverflow.com/comment/89385380
has comment: http://stackoverflow.com/comment/89385693

http://stackoverflow.com/q/51217433
answer count: 1
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
upvote count: 4
tagged with: animated-gif
tagged with: wand
downvote count: 0
has answer: http://stackoverflow.com/a/51246938
has title: Make a GIF play exactly once with Python Wand
has body: I can create an animated GIF like this: from wand.image import Image with Image() as im: while i_need_to_add_more_frames(): im.sequence.append(Image(blob=get_frame_data(), format='png')) with im.sequence[-1] as frame: frame.delay = calculate_how_long_this_frame_should_be_visible() im.type = 'optimize' im.format = 'gif' do_something_with(im.make_blob()) However, an image created like this loops indefinitely. This time, I want it to loop once, and then stop. I know that I could use convert's -loop parameter if I were using the commandline interface. However, I was unable to find how to do this using the Wand API. What method should I call, or what field should I set, to make the generated GIF loop exactly once?
type: Question
tagged with: http://stackoverflow.com/tag/gif
score: 4

http://stackoverflow.com/comment/89559780
comment on: http://stackoverflow.com/q/51291018
score: 0
type: Comment
type: QuestionComment
has text: What do you mean by `distance between all other points`? Can you give us an example of expected output?

http://stackoverflow.com/comment/89392660
type: Comment
comment on: http://stackoverflow.com/q/51205540
type: QuestionComment
has text: It seems like the version of django-ajax you are using is not compatible with that version of Django itself.
score: 0

pyside
tags question: http://stackoverflow.com/q/51288062
tags question: http://stackoverflow.com/q/51212916
tags question: http://stackoverflow.com/q/51283283
tags question: http://stackoverflow.com/q/51272418
tags question: http://stackoverflow.com/q/51309100
type: Tag
tags question: http://stackoverflow.com/q/51306366
tags question: http://stackoverflow.com/q/51256737
tag name: pyside
tags question: http://stackoverflow.com/q/51200589
tags question: http://stackoverflow.com/q/51240875

http://stackoverflow.com/comment/89412532
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51214599
type: Comment
has text: ok it should be good to go so you can copy and past hard-coded dataframes now Prune

http://stackoverflow.com/q/51191731
has answer: http://stackoverflow.com/a/51192306
tagged with: python
score: 2
has title: how to get the max of each column from an 2d array + index of the max value
upvote count: 3
has body: I have for example A = [[1 2 3 4 5] [2 4 5 8 7] [9 8 4 5 2] [1 2 4 7 2] [5 9 8 7 6] [1 2 5 4 3]] So the shape of A = (5,6) What I want is now the max of each column and return the result as eg: A = [[9 9 8 8 7]] with as shape (5,1) And at the same time I would like to receive the index of the max value from each column. Is this possible? I don't find immediatly the sollution within the np.array basic doc.
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/51192188
tagged with: arrays
linked to: http://stackoverflow.com/q/17079279
answer count: 2
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89368405

http://stackoverflow.com/comment/89507520
has text: No, Extra Val column cannot change Val1 column at all. It should only return its values if Val1 columns are True ( which you have answered already and it works perfectly). May be this helps in explaining Lets Say there are two main columns Val1 and Val2 now Val1 should check with ExtraVal1 and Val2 should check ExtraVal2 and final output is something like similar of what you have answered. Sorry if this was unclear, may be I can invite you in discussion chat ? .
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51264305

http://stackoverflow.com/q/51221840
score: 0
tagged with: pip
tagged with: pypi
answer count: 1
has body: I'm trying to install some add-ons to Plone but buildout can't find the links for the dependencies. I have the following in my buildout.cnfg find-links += http://dist.plone.org/release/5.0.4 http://getpaid.googlecode.com/files/yoma.batching-0.2.2-getpaid.zip And index = https://pypi.python.org/simple/ eggs = Plone Pillow collective.addthis collective.cart.shopping Products.PloneGetPaid When I run bin/buildout I get Getting distribution for 'plone.recipe.zope2instance==4.4.0'. warning: no previously-included files matching '*pyc' found anywhere in distribution Got plone.recipe.zope2instance 4.4.0. Installing instance. Couldn't find index page for 'getpaid.yoma.batching' (maybe misspelled?) Getting distribution for 'getpaid.yoma.batching'. Couldn't find index page for 'getpaid.yoma.batching' (maybe misspelled?) While: Installing instance. Getting distribution for 'getpaid.yoma.batching'. Error: Couldn't find a distribution for 'getpaid.yoma.batching'. I followed the Setup Guide The only differences I made were to add index = https://pypi.python.org/simple/to the buildout.cnfg and to add plone.recipe.zope2instance = 4.4.0 which didn't do anything and I added the link to find-links which didn't do anything either Plone Pillow collective.addthis collective.cart.shopping The first 3 install but before I added index = https://pypi.python.org/simple/ only Plone and Pillow would install. The original error is Here
has answer: http://stackoverflow.com/a/51240002
type: UnansweredQuestion
has title: Buildout can't find the links for the dependecies of Pypi Plone add-ons
type: Question
linked to: http://stackoverflow.com/q/51210505
tagged with: python
tagged with: plone
tagged with: buildout

http://stackoverflow.com/q/51267876
type: Question
has body: I have a DataFrame with two years of monthly data Y. I need the second column Y_avg with the climatology to be able to subtract both. Y Y_avg T X 2000-01-31 1 51 63 2 52 64 2000-02-29 1 53 65 2 54 66 2000-03-31 1 55 67 2 56 68 2000-04-30 1 57 69 2 58 70 2000-05-31 1 59 71 2 60 72 2000-06-30 1 61 73 2 62 74 2000-07-31 1 63 75 2 64 76 2000-08-31 1 65 77 2 66 78 2000-09-30 1 67 79 2 68 80 2000-10-31 1 69 81 2 70 82 2000-11-30 1 71 83 2 72 84 2000-12-31 1 73 85 2 74 86 2001-01-31 1 75 63 2 76 64 2001-02-28 1 77 65 2 78 66 2001-03-31 1 79 67 2 80 68 2001-04-30 1 81 69 2 82 70 2001-05-31 1 83 71 2 84 72 2001-06-30 1 85 73 2 86 74 2001-07-31 1 87 75 2 88 76 2001-08-31 1 89 77 2 90 78 2001-09-30 1 91 79 2 92 80 2001-10-31 1 93 81 2 94 82 2001-11-30 1 95 83 2 96 84 2001-12-31 1 97 85 2 98 86 This is my temporal solution: f = np.tile(np.arange(1,25),2) df['Y_avg'] = np.tile(df.groupby(f).mean().values.ravel(),2) But how can I do that more efficiently? Thanks for the help!
tagged with: pandas
tagged with: python
has answer: http://stackoverflow.com/a/51270236
score: 0
answer count: 2
accepted answer: http://stackoverflow.com/a/51270236
possible better answer: http://stackoverflow.com/a/51271884
tagged with: multi-index
has answer: http://stackoverflow.com/a/51271884
tagged with: mean
type: AnsweredQuestion
has title: Monthly Climatology for Pandas DataFrame with MultiIndex

http://stackoverflow.com/a/51310759
upvote count: 9
type: Answer
downvote count: 0
has body: You cannot do that in original one. LabelEncoder.fit() uses numpy.unique which will always return the data as sorted, as given in source: def fit(...): y = column_or_1d(y, warn=True) self.classes_ = np.unique(y) return self So if you want to do that, you need to override the fit() function. Something like this: import pandas as pd from sklearn.preprocessing import LabelEncoder from sklearn.utils import column_or_1d class MyLabelEncoder(LabelEncoder): def fit(self, y): y = column_or_1d(y, warn=True) self.classes_ = pd.Series(y).unique() return self Then you can do this: le = MyLabelEncoder() le.fit(['b', 'a', 'c', 'd' ]) le.classes_ #Output: array(['b', 'a', 'c', 'd'], dtype=object) Here, I am using pandas.Series.unique(), to get unique classes. If you cannot use pandas for any reason, refer to this question which does this question using numpy: numpy unique without sort
has comment: http://stackoverflow.com/comment/104820119
accepted answer of: http://stackoverflow.com/q/51308994
answers question: http://stackoverflow.com/q/51308994
score: 9
type: AcceptedAnswer

http://stackoverflow.com/a/51262282
has comment: http://stackoverflow.com/comment/89531132
score: 1
accepted answer of: http://stackoverflow.com/q/51261553
has comment: http://stackoverflow.com/comment/89651811
upvote count: 1
answers question: http://stackoverflow.com/q/51261553
has body: Since you have already deleted element dic[r] and ls[r] earlier in the loop, when you run x1.timeit() and x2.timeit(), it would give an error as dic[r] and ls[r] has already been deleted. Consider the following working code import timeit import random for n in range(10, 20): ls = list(range(n)) dic = {j: None for j in ls} x1 = timeit.Timer("del ls[random.randrange(len(ls))]", "from __main__ import random,ls") # delete random x2 = timeit.Timer("del dic[random.choice(dic.keys())]", "from __main__ import random,dic") print(x1.timeit(n) - x2.timeit(n)) # Will work for numbers upto n
has comment: http://stackoverflow.com/comment/89522810
has comment: http://stackoverflow.com/comment/89530179
type: AcceptedAnswer
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/89504272

http://stackoverflow.com/q/51220597
has comment: http://stackoverflow.com/comment/89432667
has body: The question is to implement barycentric weights in numerical analysis: and here is my code: def barycentric_weights(j,n): weight=1 for k in range(0,n+1): if k != j: weight=weight*(1/(xj-xk)) else: weight=weight*1 what I'm stuck is that I don't know how to correctly call xj and xk. Should I call them as tuples?
type: Question
score: 0
upvote count: 1
tagged with: numerical-methods
has comment: http://stackoverflow.com/comment/89423755
favorite count: 0
tagged with: python-3.x
tagged with: python
answer count: 0
tagged with: numerical-analysis
type: UnansweredQuestion
downvote count: 1
has title: How to write Barycentric weights in python

http://stackoverflow.com/comment/89340148
type: Comment
type: QuestionComment
has text: the problem is that if i put the code for the video in a if it will not show the box of the video but if put it without the if it will show
score: 0
comment on: http://stackoverflow.com/q/51178699

http://stackoverflow.com/comment/89582071
comment on: http://stackoverflow.com/q/51300268
type: QuestionComment
type: Comment
score: 0
has text: @Omegastick Thanks! :) I can send you a full code of my pre-processing and architecture in second e-mail.

http://stackoverflow.com/q/51179822
type: UnansweredQuestion
has title: Working with strings in lists (Python Sentiment Analysis)
tagged with: python
score: 2
type: Question
has body: I like to do a small sentiment analysis about hotel reviews. Example (stop_word_filter: ['Even', 'though', 'pictures', 'show', 'clean', 'rooms', 'actual', 'room', 'quit', 'dirty', 'outlived', 'Also', 'check', '15', 'clock', 'room', 'not', 'ready', 'time'] I figured out that this is about a "hotelroom" and about "clean". I want to connect now the closes "negative" word to "clean"which should be "dirty". I integrated a list of negative words. I am hanging on the implementation... Code: bullets = [] #output distances = [] bad_word_locations = [] rubrik_word_location = [] #category_word #if there is a category word in the review if len(rubrik_uR_list) == 1: #get the index of that one rubrik_word_location = stop_words_filter.index(rubrik_uR_list[0]) #go throu all negative words and if one of them in my sentence get the index of that word for w in negativ_words_list: if w in stop_words_filter: bad_word_locations.append(stop_words_filter.index(w)) #NOW ITS GETTING CRUCIAL #if we found one if len(bad_word_locations) &gt; 0: #I need to some how catch now the closest word, my code is not doing this distances.append(abs(rubrik_word_location-bad_word_locations[0])) bullets.append(stop_words_filter[min(distances)]) #if I got more categories in one review I need to remind that somehow... blacklist.append(stop_words_filter[min(distances)]) I am poor in programming, I see. I would appreciate your help faithfully. Thanks in advance, Niklas
tagged with: sentiment-analysis
downvote count: 0
answer count: 1
tagged with: string
has answer: http://stackoverflow.com/a/51195825
favorite count: 0
upvote count: 2

http://stackoverflow.com/a/51236147
has comment: http://stackoverflow.com/comment/89451475
has comment: http://stackoverflow.com/comment/89451613
has comment: http://stackoverflow.com/comment/89451496
upvote count: 0
answers question: http://stackoverflow.com/q/51236069
score: -3
type: Answer
has comment: http://stackoverflow.com/comment/89451311
has body: I would fix the positions of the '|' characters in a string of blanks before entering the rest of the data. So, say you want a '|' every set number of index gaps along a string of characters, you could use insert() to place '|' at every set number of indexes apart. It might look something like this: string = "" for i in SizeofString: string.append(' ') for i in NumberofPipesYouWant: string.insert('|', indexGap*i) This is just how I would personally do it, I'm not sure if more direct solutions exist.
downvote count: 3

http://stackoverflow.com/q/51291082
type: AnsweredQuestion
tagged with: pca
accepted answer: http://stackoverflow.com/a/51292077
score: 1
has body: Say I want to find the optimal number of components when doing PCA in Python3 with sklearn. I'd do that by iterating over some n_components and computing total absolute prediction error for each value when validating the model. My question would be, what's the difference between passing a n_components parameter to PCA and going from there, as opposed to not passing it and only using the first (i) components from the implicit max value it gets. My linear algebra is a bit shaky, but if I recall correctly the single vectors should be the same in both situations, and ordered in ascending order, and provide the same amount of explained variance. Sorry for not providing any code nor writing up both scenarios to test them myself, but I'm on a long train ride and my laptop battery ran out mid-process. Now I'm stuck with the curiosity.
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/51292077
tagged with: data-science
answer count: 1
downvote count: 0
tagged with: scikit-learn
favorite count: 0
has title: sklearn.pca() and n_components, linear algebra dilemma
tagged with: data-analysis
tagged with: python

http://stackoverflow.com/a/51318404
answers question: http://stackoverflow.com/q/51318249
has body: Variable salary is just a copy of the value from data. You should modify the original list instead of the copy. The function enumerate can generate the index (from 0) you need for changing the value inside the list. data = [['Ben', 'Manager', 3000], ['James', 'Cleaner', 1000], ['Ken', 'Supervisor', 2000]] for i, (name, appt, salary) in enumerate(data): if name == 'James': data[i][2] = 1500 print(data[i]) The output: ['James', 'Cleaner', 1500]
score: 0
type: Answer

http://stackoverflow.com/q/51190277
has title: the for loop is not iterating completely in python
has answer: http://stackoverflow.com/a/51190375
accepted answer: http://stackoverflow.com/a/51190327
possible better answer: http://stackoverflow.com/a/51190375
has comment: http://stackoverflow.com/comment/89362655
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51190774
type: Question
has answer: http://stackoverflow.com/a/51190327
tagged with: for-loop
has body: I want to traverse the for loop to find all the occurrences of "%" followed by an integer and replace them with another word. for x in format: if x is "%": finder = format.find("%") val = format[finder + 1] index = int(format[finder + 1]) print("Index value is %d" % index) replace = args[index] print(replace) str = format.replace(val, replace) return str If there is more than one "%" in format(i.e string) then only integer, is getting replaced. Eg: format : "%1 greets %0" and args = "Bob", "Alex" The output should be : "Alex greets Bob" But what I'm getting is "Alex greets %0"
score: 0
answer count: 3

http://stackoverflow.com/comment/89611195
score: 0
has text: yes, I've tried uninstalling numpy, verified that it is no longer in site-packages in the virtualenv, and then reinstalled it. And, since I had upgraded from 1.14.0 to 1.14.2, I have also tried uninstalling and then reinstalling the 1.14.0 version without success. That's why I'm left wondering if I should uninstall all modules (and the gcc-c++ yum package) and start over
comment on: http://stackoverflow.com/q/51316688
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51235076
has comment: http://stackoverflow.com/comment/89449074
accepted answer: http://stackoverflow.com/a/51236156
tagged with: numpy
score: 0
tagged with: pandas-groupby
tagged with: pandas
has title: How to perform below task using pandas which is faster and does not give warning 'SettingWithCopyWarning'
answer count: 1
has comment: http://stackoverflow.com/comment/89449153
tagged with: python
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/20625582
has answer: http://stackoverflow.com/a/51236156
tagged with: pandas-datareader
type: Question
has body: I am accessing the timestamp from the data. If several timestamps have same value, then changing them. In that case add 2 to the second timestamp if two are same. If three are same then add 2 to second and add 4 to third and so on. I get a warning /anaconda/lib/python3.6/site-packages/ipykernel/main.py:8: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy My problem is: it takes too long to perform the task. I want to know if there is some specific way to perform the task in a more precise way in pandas. Please consider I am new to panda. dftime =df.time for i in range (len(dftime)): if i!=0: if dftime[i]==dftime[i-1]: dftime[i]=dftime[i]+2 if dftime[i]&lt;dftime[i-1]: dftime[i]=dftime[i-1]+2
has comment: http://stackoverflow.com/comment/89449039

http://stackoverflow.com/a/51202360
answers question: http://stackoverflow.com/q/51202238
upvote count: 1
type: Answer
downvote count: 0
has body: Using melt df.melt('Pageviews').drop('variable',1) Out[644]: Pageviews value 0 1210 ConsumerProducts 1 1528 Collaboration 2 1716 FinancialServices 3 1403 Collaboration 4 1090 ConsumerProducts 5 1210 ConsumerProducts 6 1528 FutureofSupplyChains 7 1716 ConsumerProducts 8 1403 FinancialServices 9 1090 FutureofSupplyChains 10 1210 FinancialServices 11 1528 FinancialServices 12 1716 Collaboration 13 1403 FutureofSupplyChains 14 1090 FinancialServices
score: 1
accepted answer of: http://stackoverflow.com/q/51202238
type: AcceptedAnswer

http://stackoverflow.com/q/51267610
has comment: http://stackoverflow.com/comment/89513769
score: 0
has comment: http://stackoverflow.com/comment/89523593
has body: Im trying to install presto on an iMac with High Sierra. I followed every step in this guide but at the last step &gt; pip3 install presto I get following error: "Command "python setup.py egg_info" failed with error code 1 in /private/var/folders/m2/1tsgrfm16rv0d42lsdmzw9b40000gr/T/pip-install-a6tq2cq4/presto/ Ladmins-iMac:~ patrick$ " I installed python with homebrew and everything is up to date. I already tried everything mentioned here but nothing seems to work for me.There were no problems installing other packages like pandas, numpy and scipy. Would gladly appreciate your help!
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89513949
tagged with: pip
tagged with: python
has title: pip install presto : Command "python setup.py egg_info" failed with error code 1
answer count: 0
tagged with: installation
linked to: http://stackoverflow.com/q/35991403
tagged with: macos-high-sierra
type: Question
has comment: http://stackoverflow.com/comment/89579258

http://stackoverflow.com/q/51306118
has comment: http://stackoverflow.com/comment/89593528
tagged with: qt
tagged with: c++
has comment: http://stackoverflow.com/comment/89594793
has comment: http://stackoverflow.com/comment/89594703
answer count: 0
score: 0
linked to: http://stackoverflow.com/q/145270
type: Question
has comment: http://stackoverflow.com/comment/89594897
has comment: http://stackoverflow.com/comment/89588892
has comment: http://stackoverflow.com/comment/89588921
has comment: http://stackoverflow.com/comment/89588881
has comment: http://stackoverflow.com/comment/89593590
has body: Hy guys. I need your help. So, I'm creating an a qt desktop app, and i need to call function methods from python file, inside te project. So, my python file: import logging import os from time import gmtime, strftime class Logger(): LOG_TO_FILE=True @staticmethod def currentTime(): return strftime("%Y-%m-%d %H:%M:%S", gmtime()) @staticmethod def log(msg): print msg Logger.saveToFile(msg) @staticmethod def info(label, msg): msg = "%s Info : [%s] -&gt; %s" % (Logger.currentTime(), label, msg) Logger.saveToFile(msg) print msg @staticmethod def debug(label, msg): msg = "%s Debug : [%s] -&gt; %s" % (Logger.currentTime(), label, msg) Logger.saveToFile(msg) print msg @staticmethod def warning(label, msg): msg = "%s Warn : [%s] -&gt; %s" % (Logger.currentTime(), label, msg) Logger.saveToFile(msg) print msg @staticmethod def critical(label, msg): msg = "%s Critic : [%s] -&gt; %s" % (Logger.currentTime(), label, msg) Logger.saveToFile(msg) print msg @staticmethod def error(label, msg): msg = "%s Error : [%s] -&gt; %s" % (Logger.currentTime(), label, msg) Logger.saveToFile(msg) print msg #log.critical(msg) @staticmethod def data(label, msg): msg = "%s Data : [%s] -&gt; \t%s" % (Logger.currentTime(), label, msg) Logger.saveToFile(msg) print msg @staticmethod def saveToFile(message): if Logger.LOG_TO_FILE is True: if os.path.exists('/var/log/iot-pi') is not True: os.makedirs('/var/log/iot-pi') try: filePath='/var/log/iot-pi/main.log' f = open(filePath,'a') f.write(message + '\n') f.close() bytes = os.path.getsize(filePath) if bytes &gt;= 10000000: os.remove(filePath) Logger.info("SYSTEM", "Log file removed") except Exception as inst: print "save to file error (%s)" % inst if __name__ == "__main__": Logger.info("Test", "Message test") my main cpp #include &lt;QGuiApplication&gt; #include &lt;QQmlApplicationEngine&gt; int main(int argc, char *argv[]) { QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling); QGuiApplication app(argc, argv); //call Logger.py here ?? it's possib…
has comment: http://stackoverflow.com/comment/89589225
has title: Call Python file methods inside from QT creator C++
type: UnansweredQuestion
tagged with: qt-creator
tagged with: python

http://stackoverflow.com/comment/89629726
score: 0
type: AnswerComment
has text: Nihal - w+ shall wipe all previous entries. r+ works to some extent - but it doesn't delete the previous entries, but keeps the lines dividable by the user input (I given 2, and every 2nd lines were kept)
type: Comment
comment on: http://stackoverflow.com/a/51323336

http://stackoverflow.com/comment/89466811
comment on: http://stackoverflow.com/q/51244034
has text: Thanks @pkpkpk for the quick reply. That seems to stumble if the address is also 4 digits i.e. 1920 Sample Street. There is also the possibility of other numbers appearing in the address if looking from top down whereas at least the Dear route is known.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51213717
possible better answer: http://stackoverflow.com/a/51214394
has answer: http://stackoverflow.com/a/51214138
has answer: http://stackoverflow.com/a/51214394
answer count: 3
downvote count: 0
accepted answer: http://stackoverflow.com/a/51214089
favorite count: 0
tagged with: beautifulsoup
tagged with: python
has comment: http://stackoverflow.com/comment/89408902
score: 2
type: AnsweredQuestion
has body: I have a web crawling script import requests from lxml import html import bs4 res = requests.get('https://in.linkedin.com/in/ASAMPLEUSERNAME', headers={'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36'}) print(res.text) please replace 'ASAMPLEUSERNAME' in the url in the code with some dummy linkedin user But the code only gives me partial incomplete (almost nothing) webpage source
has title: Beautiful Soup not loading the entire page
upvote count: 2
linked to: http://stackoverflow.com/q/41495589
has answer: http://stackoverflow.com/a/51214089
type: Question
has comment: http://stackoverflow.com/comment/89408905
tagged with: web-crawler

http://stackoverflow.com/comment/89605617
comment on: http://stackoverflow.com/q/51313850
type: QuestionComment
has text: That worked for me thank you.
score: 0
type: Comment

http://stackoverflow.com/comment/89479118
score: 0
type: Comment
has text: Thank you, your explanation really cleared this up for me. For some reason, though, I keep getting the alert: `'set' object has no attribute 'replace'` even though you never use the word "replace". Do you know what's happening?
comment on: http://stackoverflow.com/a/51219188
type: AnswerComment

http://stackoverflow.com/q/51291460
possible better answer: http://stackoverflow.com/a/75219179
tagged with: multiprocessing
type: AnsweredQuestion
has body: Hi I'm currently trying to run a function parallely on multiple cores due to the long run time of the program. I could not find the syntax for multiprocessing syntax for functions with multiple arguments. I have attached my code below and have no idea how to fix the syntax. import pandas as pd import numpy as np import numpy.random as rdm import matplotlib.pyplot as plt import math as m import random as r import time from joblib import Parallel, delayed def firstLoop(r1, r2, d): count = 0 for i in range(r1): for j in range(r2): if(findDistance(dat1[i, 0], dat2[j, 0], dat1[i, 1], dat2[j, 1]) &lt;= d): count = count + 1 return count food1 = range(r1) atm1 = range(r2) d = 100 num_cores = multiprocessing.cpu_count() results = Parallel(n_jobs=num_cores)(delayed(firstLoop)(for i in food1, for j in atm1, d)) I'm trying to run firstLoop on multiple cores with all the elements in food1 and atm1, but am unsure on the syntax for the program. EDIT : startTime = time.time() with mp.Pool(processes = mp.cpu_count()) as p: p.starmap(f, [(x, y, d) for x in range(r1) for y in range(r2) for d in range(100, 200, 100)]) print(time.time()- startTime)
has answer: http://stackoverflow.com/a/51291533
accepted answer: http://stackoverflow.com/a/51291533
has answer: http://stackoverflow.com/a/75219179
type: Question
tagged with: python-multiprocessing
answer count: 2
score: 0
tagged with: python
has title: Python Parallel Processing Syntax for Functions with Multiple Arguments

http://stackoverflow.com/a/51296783
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51237770
score: 0
type: Answer
has body: Try this one: (.*"state":"CA".*"active":true.*) Demo: https://regex101.com/r/hP6gS1/238 It works. You can change tag name and values as per your requirements. It extracts your required JSON content.
answers question: http://stackoverflow.com/q/51237770

http://stackoverflow.com/q/51301690
type: Question
tagged with: dataframe
has title: remove dataframe from another without removing duplicates
score: 0
tagged with: pandas
linked to: http://stackoverflow.com/q/44546086
type: UnansweredQuestion
tagged with: python
has body: i have a dataframe df1 of size [21,4], and a dataframe df2 of size [10200,4]. I wish to remove the values of df1 from df2 so that its size is [10179,4] I have seen many posts using the drop duplicates function, however i do not want to drop any duplicates in the df2 dataframe, i only want to remove the df1 values. i have tried result=df1[~df1'decel','accel','corner','vert'.apply(lambda x: np.in1d(x,df2).all(),axis=1)]\.reset_index(drop=True) but with no success! many thanks for all your help UPDATE: Using the code: Xfinal = pd.merge(X, dropthese, on=['decel','accel','corner','vert'], how='outer', indicator=True).query("_merge != 'both'").drop('_merge', axis=1) allows me to remove df1 from df2, however reorders df2, grouping similar values. Is there a way to keep the order the same? thanks
has comment: http://stackoverflow.com/comment/89598662
answer count: 0
has comment: http://stackoverflow.com/comment/89580357

http://stackoverflow.com/q/51226731
accepted answer: http://stackoverflow.com/a/51226764
answer count: 2
possible better answer: http://stackoverflow.com/a/51226756
has answer: http://stackoverflow.com/a/51226764
score: 0
tagged with: python
has answer: http://stackoverflow.com/a/51226756
type: Question
type: AnsweredQuestion
has title: Generate a repeating index for length of list
has comment: http://stackoverflow.com/comment/89433565
has body: I know I can do the follow : files = ['a', 'b', 'c', 'd', 'e', 'f'] for ind, file in enumerate(files): print(ind, file) (0, 'a') (1, 'b') (2, 'c') (3, 'd') (4, 'e') (5, 'f') I'd like to generate a second index that repeats between 0 and n-1 over the length of the list. For example, if n=2 print(ind, file, ind2) yields (0, 'a', 0) (1, 'b', 1) (2, 'c', 0) (3, 'd', 1) (4, 'e', 0) (5, 'f', 1) and if n=3 (0, 'a', 0) (1, 'b', 1) (2, 'c', 2) (3, 'd', 0) (4, 'e', 1) (5, 'f', 2)
has comment: http://stackoverflow.com/comment/89433548

http://stackoverflow.com/comment/89435374
has text: @EugenePrimako Traceback (most recent call last): File "<pyshell#8>", line 1, in <module> sum_all([1, [2, [3, [4]]]]) File "C:/Users/#/Documents/python/recursion.py", line 36, in sum_all numbers[0] = numbers[0] + rec_sum(numbers[-1]) File "C:/Users/#/Documents/python/recursion.py", line 17, in rec_sum numbers[0] = numbers[-1] + numbers[0] TypeError: can only concatenate list (not "int") to list
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51227600
score: 0

http://stackoverflow.com/comment/89433476
type: AnswerComment
type: Comment
has text: Actually, you _can't_ call it on the key view, or on the dict itself. `choice` requires a _sequence_, not just an iterable.
comment on: http://stackoverflow.com/a/51226639
score: 0

http://stackoverflow.com/q/51252619
has body: Original dataframe: ix x y z 0 3 4 1 1 2 0 6 2 7 1 0 3 0 0 0 Should transform into: ix x y z 0 0 1 0 1 0 0 1 2 1 0 0 3 0 0 0 As you can see, i'm taking the max value in each row and setting that equal to 1 then the other values in that row will be equal to 0. Also, you'll notice that row 3 stays the same since they are all equal to 0. So, I've been able to extract the index of the max value using: x.idxmax(axis = 1) But i'm not sure what to do with the max indices. I'm thinking to use np.where but there isn't a conditional statement I can use. Or so I think. Any help would be much appreciated.
has comment: http://stackoverflow.com/comment/89485509
has answer: http://stackoverflow.com/a/51252680
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/51253375
accepted answer: http://stackoverflow.com/a/51253375
has comment: http://stackoverflow.com/comment/89484181
has comment: http://stackoverflow.com/comment/89484161
has comment: http://stackoverflow.com/comment/89485586
score: 4
answer count: 3
tagged with: pandas
has answer: http://stackoverflow.com/a/51252712
has comment: http://stackoverflow.com/comment/89484194
possible better answer: http://stackoverflow.com/a/51252680
favorite count: 0
tagged with: python
upvote count: 4
has title: How do I set the max value if dataframe row to 1 and the rest of the values to 0
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/89484103

http://stackoverflow.com/comment/89592685
comment on: http://stackoverflow.com/q/51307587
type: Comment
has text: @schwobaseggl This is possible, but then that would imply that almost every page load checks 3-4 models, where as, if I update `completed_setup` as a field, I only look up one model (but then I have to create signals)
type: QuestionComment
score: 0

http://stackoverflow.com/comment/123864724
type: Comment
has text: Under "improving performance"? That was going to be my third guess... :) Anyway, thanks. Although it mainly has the syntax, it does mention that wildcards can be used, so presumably "fields=*" would have given me everything, similar to "fields=sheets".
comment on: http://stackoverflow.com/a/51313562
score: 0
type: AnswerComment

http://stackoverflow.com/q/51182470
tagged with: python
tagged with: macos
has comment: http://stackoverflow.com/comment/89347624
has title: Python tkinter on Mac
tagged with: tkinter
answer count: 0
type: UnansweredQuestion
type: Question
has comment: http://stackoverflow.com/comment/89349353
score: 0
has comment: http://stackoverflow.com/comment/89347627
has body: This is a very basic question. I'm reading the book 'Programming Python' and following the tutorial. But the book is based on the Windows, and I'm doing in Mac, and the result seems different. Code is this: from tkinter import * from tkinter.messagebox import showerror import shelve shelvename='class-shelve' fieldnames=('name','age','job','pay') def makeWidgets(): global entries window=Tk() window.title('People Shelve') form=Frame(window) form.pack() entries={} for (ix,label) in enumerate(('key',)+fieldnames): lab=Label(form,text=label) ent=Entry(form) lab.grid(row=ix,column=0) lab.grid(row=ix,column=1) entries[label]=ent Button(window,text="Fetch",command=fetchRecord).pack(side=LEFT) Button(window,text="Update",command=updateRecord).pack(side=LEFT) Button(window,text="Quit",command=window.quit).pack(side=RIGHT) return window def fetchRecord(): key=entries['key'].get() try: record=db[key] except: showerror(title='Error',message='No such key!') else: for field in fieldnames: entries[field].delete(0,END) entries[field].insert(0,repr(getattr(record,field))) def updateRecord(): key=entries['key'].get() if key in db: record=db[key] else: from person import Person record=Person(name='?',age='?') for field in fieldnames: setattr(record, field, eval(entries[field].get())) db[key]=record db=shelve.open(shelvename) window=makeWidgets() window.mainloop() db.close() And the book says the result should look like: But it does look like in my Mac: So there is no space for me to type something. How can I fix it?

http://stackoverflow.com/a/51213065
downvote count: 0
answers question: http://stackoverflow.com/q/51212806
type: Answer
has body: You have to add sess.run(tf.tables_initializer()) add the beginning of the with tf.Session()-block
score: 2
upvote count: 2
accepted answer of: http://stackoverflow.com/q/51212806
type: AcceptedAnswer

http://stackoverflow.com/comment/89617485
type: Comment
score: 0
comment on: http://stackoverflow.com/a/51302617
has text: If it helps I'm using stacked layout to switch in between windows. When I switch to a different window the navigation bar doesn't go away. posted the code above
type: AnswerComment

http://stackoverflow.com/a/54215305
downvote count: 0
answers question: http://stackoverflow.com/q/51209475
type: Answer
score: 6
upvote count: 6
has body: Try to shoot export OAUTHLIB_INSECURE_TRANSPORT=1in the terminal. It should work.

http://stackoverflow.com/q/51284405
has title: Display pandas dataframe containing figure objects
has comment: http://stackoverflow.com/comment/89549112
has comment: http://stackoverflow.com/comment/89546371
has comment: http://stackoverflow.com/comment/89549371
type: Question
has comment: http://stackoverflow.com/comment/89549510
tagged with: seaborn
tagged with: python
has comment: http://stackoverflow.com/comment/89549241
score: 0
tagged with: matplotlib
linked to: http://stackoverflow.com/q/47038538
duplicate of: http://stackoverflow.com/q/47038538
has body: I have several matplotlib figure objects organised in a pandas dataframe. I am looking for a way to display such a dataframe within a jupyter notebook. To give an example for such a dataframe: import pandas as pd import matplotlib.pyplot as plt pdf = pd.DataFrame({'a':{'a1': plt.Figure(), 'a2': plt.Figure()}, 'b': {'a1': plt.Figure(), 'a2': plt.Figure()}} Currently, I am thinking of creating an html template of the table, pasting in the figures in png format. But maybe there is a more elegant way? Maybe it is already implemented? Sidenote: I am aware, that the usual way of combining several plots is to use several axes within one figure object, but that is not what I am asking for.
answer count: 0
has comment: http://stackoverflow.com/comment/89549329
type: UnansweredQuestion
tagged with: pandas

http://stackoverflow.com/q/51216605
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/89414578
has comment: http://stackoverflow.com/comment/89414527
tagged with: oop
has comment: http://stackoverflow.com/comment/89414407
has comment: http://stackoverflow.com/comment/89414571
has answer: http://stackoverflow.com/a/51216682
answer count: 1
has comment: http://stackoverflow.com/comment/89414451
has title: Using a manipulated property on all of the functions in a class (python)
favorite count: 0
has comment: http://stackoverflow.com/comment/89414432
accepted answer: http://stackoverflow.com/a/51216682
tagged with: python
type: AnsweredQuestion
has body: I'm looking for the best way to solve a scenario I encountered. I have a python class that gets as one of its properties a string, that represents the absolute path of a file in the filesystem. In all of the functions where the property is used, I convert the string to a list that every item on the list is a directory in the mentioned path. Obviously I don't want to create the list every time I need to use it, because it's much more sensible to have an attribute in the class that is that list. But I don't want to put that logic in the constructor, because it's bad practice to have anything but assignments in the constructor (testing wise, although this is not that bad of a case). How would you handle this? Where would you put such a property in the class if you didn't want to recalculate it everytime you use it?
score: 0
upvote count: 1

http://stackoverflow.com/q/51247958
answer count: 3
has comment: http://stackoverflow.com/comment/89479184
has answer: http://stackoverflow.com/a/51248120
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89479067
tagged with: python
accepted answer: http://stackoverflow.com/a/51251097
type: AnsweredQuestion
has body: I'm trying to multiply two matrices of dimensions (17,2) by transposing one of the matrices Here is example p1 p1 = [[ 0.15520622 -0.92034567] [ 0.43294367 -1.05921439] [ 0.7569707 -1.15179354] [ 1.08099772 -1.15179354] [ 1.35873517 -0.96663524] [-1.51121847 -0.64260822] [-1.32606018 -0.87405609] [-1.00203315 -0.96663524] [-0.67800613 -0.96663524] [-0.3539791 -0.87405609] [ 0.89583942 1.02381648] [ 0.66439155 1.3478435 ] [ 0.3866541 1.48671223] [ 0.15520622 1.5330018 ] [-0.07624165 1.5330018 ] [-0.3539791 1.44042265] [-0.58542698 1.20897478]] here is another example matrix p2 p2 = [[ 0.20932473 -0.90029958] [ 0.53753779 -1.03849455] [ 0.88302521 -1.10759204] [ 1.24578701 -1.02122018] [ 1.47035383 -0.77937898] [-1.46628927 -0.69300713] [-1.29354556 -0.9521227 ] [-0.96533251 -1.03849455] [-0.63711946 -1.00394581] [-0.3089064 -0.90029958] [ 0.86575084 1.06897874] [ 0.55481216 1.37991742] [ 0.26114785 1.50083802] [ 0.03658102 1.51811239] [-0.1879858 1.50083802] [-0.46437574 1.37991742] [-0.74076568 1.08625311]] I'm trying to multiply them using numpy import numpy print(p1.T * p2) But I'm getting the following error operands could not be broadcast together with shapes (2,17) (17,2) This is the expected matrix multiplication output [[11.58117944 2.21072324] [-0.51754442 22.28728876]] Where exactly am I going wrong
possible better answer: http://stackoverflow.com/a/51248906
has comment: http://stackoverflow.com/comment/89474786
has answer: http://stackoverflow.com/a/51248906
has comment: http://stackoverflow.com/comment/89479270
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/89475064
has title: Issue with numpy matrix multiplication
has comment: http://stackoverflow.com/comment/89475071
has comment: http://stackoverflow.com/comment/89475178
has answer: http://stackoverflow.com/a/51251097
score: 0
has comment: http://stackoverflow.com/comment/89475551
has comment: http://stackoverflow.com/comment/89478540

http://stackoverflow.com/comment/89346698
type: Comment
comment on: http://stackoverflow.com/q/51182154
score: 0
has text: Please add a simplified example. Do you expect people to create the example?
type: QuestionComment

http://stackoverflow.com/comment/89531504
has text: Ok, so I guess I did not miss anything in my google search and this is just not an algorithm that is readily/publicly available even for the 2D case ? The article I cited mentioned that there were some simple brute force approach, and I was hoping this had been implemented before maybe for texture mapping of non simply connected shapes. Anyway, thank you!
comment on: http://stackoverflow.com/q/51253641
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51192283
accepted answer of: http://stackoverflow.com/q/51192250
answers question: http://stackoverflow.com/q/51192250
score: 0
type: AcceptedAnswer
type: Answer
has body: Do you mean fig, ax = plt.subplots(figsize=(15, 15)) SP500_Growth_quantiles.plot(kind = 'bar', ax=ax) ax.set_title('Quantiles of the Probability Distribution of S&amp;P 500 Growth in 2018') ax.set(ylabel = 'S&amp;P 500 Growth in 2018', xlabel = 'Quantile')

http://stackoverflow.com/comment/89617653
score: 0
has text: Very good solution, but sometimes it stays stuck on the last page on my side... Infinitely trying to reach the next page(which doesn't exist).
type: Comment
comment on: http://stackoverflow.com/a/51312424
type: AnswerComment

http://stackoverflow.com/q/51209432
answer count: 2
tagged with: bootstrap-4
has answer: http://stackoverflow.com/a/51211967
has title: Not able to get clicked on login button, to move to next page, using phantomjs with Python selenium
tagged with: python-3.x
type: UnansweredQuestion
score: 0
tagged with: selenium
tagged with: python
tagged with: phantomjs
has answer: http://stackoverflow.com/a/51209522
has body: I am not able to get click on button using phantomjs in python selenium test cases. here is the code that I am using in python file: btn_log = wait(driver, 10).until(EC.presence_of_element_located((By.XPATH, "//*[@id = ('login_button')]"))) driver.execute_script("arguments[0].click();", btn_log) This is the login button but this is not getting clicked and nothing does change to get inside after login. Login
type: Question

http://stackoverflow.com/comment/100264003
comment on: http://stackoverflow.com/a/51281363
has text: AFAIK you don't have to add anything there. The class is there to overwrite the original function that is used by the requests package. In order to use your extracted certificate in cert_verify.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/89413693
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51202566
type: AnswerComment
has text: No, you're redundantly testing the same pairs of players twice in your code, while my code would test each player pair exactly once. I've updated my answer to give you a better explanation.

http://stackoverflow.com/comment/89579296
score: 0
type: QuestionComment
has text: @Omegastick No, I put into neural network only sentences (such as in the example), without the position of the gene. Positions of genes I have in another CSV column. Can I somehow use it?
type: Comment
comment on: http://stackoverflow.com/q/51300268

http://stackoverflow.com/comment/89494239
score: 0
type: Comment
comment on: http://stackoverflow.com/q/51257803
type: QuestionComment
has text: `(int(b) >= 1230) and (int(b) != 1250) and (str(b)[:3] == 130)`?

http://stackoverflow.com/a/51181734
upvote count: 1
has body: Using formatted_df = numeric_df mean the variables share the same memory footprint. Referencing the same object. To manipulate one independently you need a seperate object. For this you can clone an object or Pandas offers copy() formatted_df = numeric_df.copy() why should I make a copy of a data frame in pandas
accepted answer of: http://stackoverflow.com/q/51181707
has comment: http://stackoverflow.com/comment/89345892
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51181707
score: 1
type: Answer

http://stackoverflow.com/comment/89526362
type: QuestionComment
has text: It's also worth looking into lower-level libraries like PyCxx, boost::python, Pyd, rust-python, etc. Instead of writing code to drive an interface generator like SWIG, you write code in a general-purpose language like C++ or D or Rust that can talk directly to C, and there are templates/macros/etc. that generate Python types, manage Python refcounting, etc. so you don't have to deal with all of that boilerplate (and all of the annoying bugs that you're going to face in doing this).
comment on: http://stackoverflow.com/q/51273804
score: 0
type: Comment

http://stackoverflow.com/comment/89382344
type: Comment
score: 0
has text: @hoefling Yes, it’s still _there_, but is it still guaranteed to be used by `import`? The docs in 3.4+ say that it’s “strongly discouraged” to replace or use it, and no longer give all the details about what effects replacing it actually has.
comment on: http://stackoverflow.com/q/51200093
type: QuestionComment

http://stackoverflow.com/q/51227733
tagged with: jupyter-notebook
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89435434
has answer: http://stackoverflow.com/a/51227753
type: Question
has body: This code works fine if I run it from the command line. import argparse import sys from googleapiclient import sample_tools from pprint import pprint def execute_request(service, property_uri, request): """Executes a searchAnalytics.query request. Args: service: The webmasters service to use when executing the query. property_uri: The site or app URI to request data for. request: The request to be executed. Returns: An array of response rows. """ return service.searchanalytics().query( siteUrl=property_uri, body=request).execute() # Declare command-line flags. argparser = argparse.ArgumentParser(add_help=False) argparser.add_argument('property_uri', type=str, help=('Site or app URI to query data for (including ' 'trailing slash).'), action='store_true') argparser.add_argument('start_date', type=str, help=('Start date of the requested date range in ' 'YYYY-MM-DD format.'), action='store_true') argparser.add_argument('end_date', type=str, help=('End date of the requested date range in ' 'YYYY-MM-DD format.'), action='store_true') service, flags = sample_tools.init( sys.argv, 'webmasters', 'v3', __doc__, 'client_secrets.json', parents=[argparser], scope='https://www.googleapis.com/auth/webmasters.readonly') # First run a query to learn which dates we have data for. You should always # check which days in a date range have data before running your main query. # This query shows data for the entire range, grouped and sorted by day, # descending; any days without data will be missing from the results. request = { 'startDate': flags.start_date, 'endDate': flags.end_date, 'dimensions': ['date'] } response = execute_request(service, flags.property_uri, request) pprint(response) If I run it from ipython notebook, I get this error: ArgumentParser(prog='-c', usage=None, description=None, version=None, formatter_class=, conflict_handler='error', add_help=False) usage: -c [-h] [--auth_host_name AUTH_HOST_NAME] [--noauth_local_webserver] [--auth_host_port [AUTH_HOST_PORT [AUTH_HOS…
tagged with: python-2.7
score: 0
has title: ipython notebook argparse error
answer count: 1
tagged with: python-3.x
linked to: http://stackoverflow.com/q/50763033
has comment: http://stackoverflow.com/comment/89435620
tagged with: argparse
has comment: http://stackoverflow.com/comment/89435645
tagged with: python

http://stackoverflow.com/q/51278119
upvote count: 1
answer count: 1
downvote count: 1
favorite count: 0
score: 0
tagged with: typeerror
tagged with: python
has comment: http://stackoverflow.com/comment/89533856
has body: I tried to put the float and int inside my coding, but it still said "can't multiply sequence by non-int of type float" PV = input("investment amout:") r = float(input("rate:")) n = int(input("year:")) FV_conti = PV*(1+r)**n import math FV_diceret = PV * math.exp(r*n)
has title: TypeError:can't multiply sequence by non-int of type float
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89533998
has answer: http://stackoverflow.com/a/51278621
accepted answer: http://stackoverflow.com/a/51278621
type: Question
has comment: http://stackoverflow.com/comment/89534453

http://stackoverflow.com/comment/89502672
score: 0
type: Comment
type: QuestionComment
has text: there is no DISPLAY environment variable set. what is your setup? Are you running this on a local Linux PC?
comment on: http://stackoverflow.com/q/51262103

http://stackoverflow.com/comment/89534942
score: 2
has text: Possible duplicate of [Is there a memory efficient and fast way to load big json files in python?](https://stackoverflow.com/questions/2400643/is-there-a-memory-efficient-and-fast-way-to-load-big-json-files-in-python)
comment on: http://stackoverflow.com/q/51278619
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/89616227
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51319979
has text: I have managed to get both start and end of month dates (I think) with this code.. but still l dont know how to take those two values and put in the same column

http://stackoverflow.com/comment/89369564
type: Comment
type: QuestionComment
has text: florian: pip install gspread
score: 0
comment on: http://stackoverflow.com/q/51192688

http://stackoverflow.com/q/51173695
has body: I'm trying to use pytorch in MSVS2017. I started a pytorch project, have anaconda environment set using python3.6, but when I run the debugger, I get a "module not found" error on the first import statement "import torch". I've tried various methods for installing pytorch in a way that allows MSVS2017 to use it, including command line and Anaconda command line installations (using tips from other closely related StackOverflow questions), but I cannot clear the error. This is a native MSVS2017 project type that came with their AI Tools module. What am I doing wrong?
type: Question
has title: How do I install and run pytorch in MSVS2017 (to avoid "module not found" error on "import torch" statement)?
upvote count: 1
answer count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/51173697
tagged with: python
type: AnsweredQuestion
tagged with: anaconda
tagged with: installation
downvote count: 0
tagged with: pytorch
score: 1
has answer: http://stackoverflow.com/a/51173697

http://stackoverflow.com/comment/89334732
type: Comment
type: QuestionComment
has text: Can you share HTML sample for the same?
comment on: http://stackoverflow.com/q/51175902
score: 0

http://stackoverflow.com/comment/89609982
type: Comment
has text: Expanding on @Paul's comment. by using `.date()` you'e throwing away the hours, minutes, and seconds. The resulting `datetime.date` objects are exactly 7 days apart.
score: 3
comment on: http://stackoverflow.com/q/51316881
type: QuestionComment

http://stackoverflow.com/comment/89417405
score: 0
type: QuestionComment
has text: The easy way to do this is to sort all the letters of both words, then test if they're equal.
type: Comment
comment on: http://stackoverflow.com/q/51218121

http://stackoverflow.com/comment/89595953
type: QuestionComment
has text: cheers finally got to that... now I'm trying to figure out how to get it to display correctly.
comment on: http://stackoverflow.com/q/51304566
score: 0
type: Comment

http://stackoverflow.com/q/51208115
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51208536
has comment: http://stackoverflow.com/comment/89397085
has title: Error predicting: X has n features per sample, expecting m
type: Question
answer count: 2
has body: I got the following code, where I transform a text to tf: ... x_train, x_test, y_train, y_test = model_selection.train_test_split(dataset['documents'],dataset['classes'],test_size=test_percentil) #Term document matrix count_vect = CountVectorizer(ngram_range=(1, Ngram), min_df=1, max_features=MaxVocabulary) x_train_counts = count_vect.fit_transform(x_train) x_test_counts=count_vect.transform(x_test) #Term Inverse-Frequency tf_transformer = TfidfTransformer(use_idf=True).fit(x_train_counts) lista=tf_transformer.get_params() x_train_tf = tf_transformer.transform(x_train_counts) x_test_tf=tf_transformer.transform(x_test_counts) ... Then, I train a model and save it using pickle. The problem comes when, in another program, I try to predict new data. Basically, I got: count_vect = CountVectorizer(ngram_range=(1, 1), min_df=1, max_features=None) x_counts = count_vect.fit_transform(dataset['documents']) #Term Inverse-Frequency tf_transformer = TfidfTransformer(use_idf=True).fit(x_counts) x_tf = tf_transformer.transform(x_train_counts) model.predict(x_tf) When I execute this code, the output is ValueError: X has 8933 features per sample; expecting 7488 I know this is a problem with the TfIdf representation, and I hear that I need to use the same tf_transformer and vectorizer to get the expected input shape, but I don't know how to achieve this. I can store the others transformers and vectorizers, but I have tried using different combinations and I got nothing.
accepted answer: http://stackoverflow.com/a/51208536
linked to: http://stackoverflow.com/q/29788047
downvote count: 0
score: 1
tagged with: scikit-learn
favorite count: 0
tagged with: tf-idf
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89397207
has comment: http://stackoverflow.com/comment/89397249
upvote count: 1
tagged with: python
possible better answer: http://stackoverflow.com/a/51209519
has answer: http://stackoverflow.com/a/51209519
has comment: http://stackoverflow.com/comment/89397174

http://stackoverflow.com/a/51284877
accepted answer of: http://stackoverflow.com/q/51283708
has comment: http://stackoverflow.com/comment/89555894
has comment: http://stackoverflow.com/comment/89558029
has comment: http://stackoverflow.com/comment/94309484
has comment: http://stackoverflow.com/comment/94339947
answers question: http://stackoverflow.com/q/51283708
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89598131
downvote count: 0
has comment: http://stackoverflow.com/comment/89819069
has comment: http://stackoverflow.com/comment/94304547
has body: So took a couple of things for me to get this working. First I upgraded cyptography as per Mufeeds suggestion sudo pip install --upgrade cryptography This then gave me a new error everytime I did pip &lt;any command&gt; Traceback (most recent call last): File "/usr/local/bin/pip", line 7, in &lt;module&gt; from pip._internal import main File "/usr/local/lib/python2.7/dist-packages/pip/_internal/__init__.py", line 42, in &lt;module&gt; from pip._internal import cmdoptions File "/usr/local/lib/python2.7/dist-packages/pip/_internal/cmdoptions.py", line 16, in &lt;module&gt; from pip._internal.index import ( File "/usr/local/lib/python2.7/dist-packages/pip/_internal/index.py", line 15, in &lt;module&gt; from pip._vendor import html5lib, requests, six File "/usr/local/lib/python2.7/dist-packages/pip/_vendor/requests/__init__.py", line 86, in &lt;module&gt; from pip._vendor.urllib3.contrib import pyopenssl File "/usr/local/lib/python2.7/dist-packages/pip/_vendor/urllib3/contrib/pyopenssl.py", line 46, in &lt;module&gt; import OpenSSL.SSL File "/usr/lib/python2.7/dist-packages/OpenSSL/__init__.py", line 8, in &lt;module&gt; from OpenSSL import rand, crypto, SSL File "/usr/lib/python2.7/dist-packages/OpenSSL/SSL.py", line 118, in &lt;module&gt; SSL_ST_INIT = _lib.SSL_ST_INIT AttributeError: 'module' object has no attribute 'SSL_ST_INIT' Resolved this by resintalling PyOpenSSL sudo python -m easy_install --upgrade pyOpenSSL Curator is now working as expected without the warnings curator_cli --version &gt; curator_cli, version 5.5.4
type: Answer
score: 90
upvote count: 90
has comment: http://stackoverflow.com/comment/89765629

http://stackoverflow.com/comment/89431276
type: Comment
comment on: http://stackoverflow.com/a/51225359
has text: Nice! But how to set up the $EDITOR variable?
score: 0
type: AnswerComment

http://stackoverflow.com/q/51271790
has answer: http://stackoverflow.com/a/51272378
has title: Data Privacy with Tensorboard
upvote count: 2
has body: I've recently begun using Tensorflow via Keras and Python 3.5 to analyze company data, and I am by no means an expert and only recently built my first "real-world" model. With my experimental data I used Tensorboard to visualiza how my neural network was working, and I would like to do the same with my real data. However, my company is extremely strict about company data leaving our servers - so my question is this: Does tensorboard take the raw data used in the model and upload it off-site to generate its reports/visuals or does it only use processed data/results from my model? I've done several google searches already, and I haven't found anything conclusive one way or the other. If I'm not asking this question correctly, please let me know - I'm new to all of this. Thank you.
tagged with: tensorflow
type: Question
tagged with: privacy
answer count: 1
downvote count: 0
tagged with: keras
favorite count: 0
type: UnansweredQuestion
tagged with: tensorboard
tagged with: python
score: 2

http://stackoverflow.com/q/51171256
has comment: http://stackoverflow.com/comment/89327989
has comment: http://stackoverflow.com/comment/89327770
has answer: http://stackoverflow.com/a/51172943
accepted answer: http://stackoverflow.com/a/51172943
type: AnsweredQuestion
has title: How to output "No product dimension" in csv for products that haven't got dimensions display on the page?(python,web scraping)
type: Question
has body: I made a web scraping program with python and I would like to display "No product dimension" in the column "Product dimensions". These products don't have dimensions display on Amazon. The code that should be replaced is on the try catch block with the dimension. I attached the program. I will appreciate any help. THIS IS THE OUTPUT OF THIS PROGRAM! I WOULD LIKE TO REPLACE THE ASINS FROM THE PRODUCT DIMENSIONS COLUMN WITH NO PRODUCT DIMENSION. from selenium import webdriver import csv import io proxies = { 'http': 'http://5.189.133.231:80', 'https': 'https://27.111.43.178:8080' } chrome_options = webdriver.ChromeOptions() chrome_options.add_argument('--proxy-server="%s"' % ';'.join(['%s=%s' % (k, v) for k, v in proxies.items()])) driver = webdriver.Chrome(executable_path="C:\\Users\Andrei-PC\Downloads\webdriver\chromedriver.exe", chrome_options=chrome_options) header = ['Product title', 'ASIN', 'Product Weight', 'Product dimensions', 'URL'] with open('csv/products.csv', "w") as output: writer = csv.writer(output) writer.writerow(header) links = [ 'https://www.amazon.com/Fermtech-regular-Auto-Siphon-Tubing/dp/B06XMR433X/ref=sr_1_2?s=kitchen&amp;ie=UTF8&amp;qid=1520274561&amp;sr=1-2&amp;keywords=-hhhg', 'https://www.amazon.com/Hydro-Flask-Wide-Mouth-Flip/dp/B01ACATW7E/ref=sr_1_3?s=kitchen&amp;ie=UTF8&amp;qid=1520348607&amp;sr=1-3&amp;keywords=-gfds', 'https://www.amazon.com/Cosmetics-Organizer-Compartments-Christmas-birthday/dp/B01BXDDU04/ref=sr_1_4569/138-3260504-2979110?s=bedbath&amp;ie=UTF8&amp;qid=1520585778&amp;sr=1-4569&amp;keywords=-sdfg' ] for i in range(len(links)): driver.get(links[i]) product_title = driver.find_elements_by_xpath('//*[@id="productTitle"][1]') prod_title = [x.text for x in product_title] try: asin = driver.find_element_by_xpath('(//div[@class ="pdTab"]/table/tbody/tr/td)[24]').text except: print('no ASIN template one') try: weight = driver.find_element_by_xpath('(//div[@class ="pdTab"]/table/tbody/tr/td)[2]').text except: print('no weight te…
score: 0
tagged with: web-scraping
tagged with: python
answer count: 1

http://stackoverflow.com/q/51226028
possible better answer: http://stackoverflow.com/a/51227330
tagged with: python
has comment: http://stackoverflow.com/comment/89434350
accepted answer: http://stackoverflow.com/a/51227514
has answer: http://stackoverflow.com/a/51227330
type: AnsweredQuestion
tagged with: http://stackoverflow.com/tag/json
tagged with: output
tagged with: scrapy
type: Question
has body: I'm learning about NLP, and to do this I'm scraping an Amazon book-review using Scrapy. I've extracted the fields that I want, and am outputting them to a Json file format. When this file is loaded as a df, each field is recorded as a list rather than an individual line-per-line format. How can I split this list so that the df will have a row for each item, rather than all item entries being recorded in seperate lists? Code: import scrapy class ReviewspiderSpider(scrapy.Spider): name = 'reviewspider' allowed_domains = ['amazon.co.uk'] start_urls = ['https://www.amazon.com/Gone-Girl-Gillian-Flynn/product-reviews/0307588378/ref=cm_cr_othr_d_paging_btm_1?ie=UTF8&amp;reviewerType=all_reviews&amp;pageNumber=1'] def parse(self, response): users = response.xpath('//a[contains(@data-hook, "review-author")]/text()').extract() titles = response.xpath('//a[contains(@data-hook, "review-title")]/text()').extract() dates = response.xpath('//span[contains(@data-hook, "review-date")]/text()').extract() found_helpful = response.xpath('//span[contains(@data-hook, "helpful-vote-statement")]/text()').extract() rating = response.xpath('//i[contains(@data-hook, "review-star-rating")]/span[contains(@class, "a-icon-alt")]/text()').extract() content = response.xpath('//span[contains(@data-hook, "review-body")]/text()').extract() yield { 'users' : users.extract(), 'titles' : titles.extract(), 'dates' : dates.extract(), 'found_helpful' : found_helpful.extract(), 'rating' : rating.extract(), 'content' : content.extract() } Sample Output: users = ['Lauren', 'James'...'John'] dates = ['on September 28, 2017', 'on December 26, 2017'...'on November 17, 2016'] rating = ['5.0 out of 5 stars', '2.0 out of 5 stars'...'5.0 out of 5 stars'] Desired Output: index 1: [users='Lauren', dates='on September 28, 2017', rating='5.0 out of 5 stars'] index 2: [users='James', dates='On December 26, 2017', rating='5.0 out of 5 stars'] ... I know that the Pipeline related to the spider should probably be edited to a…
has comment: http://stackoverflow.com/comment/89434321
has comment: http://stackoverflow.com/comment/89433739
linked to: http://stackoverflow.com/q/1663807
score: 0
answer count: 2
has title: Python - Scrapy to Json Output Splitting
has comment: http://stackoverflow.com/comment/89434129
linked to: http://stackoverflow.com/q/23442711
linked to: http://stackoverflow.com/q/48858167
linked to: http://stackoverflow.com/q/47377898
has answer: http://stackoverflow.com/a/51227514

http://stackoverflow.com/comment/89351897
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/51183719
has text: Hi Nordle, yes, i replaced the real url and login being posting there.

http://stackoverflow.com/q/51278332
type: AnsweredQuestion
has title: Python 3 Web Scrape & Beautiful Soup Tag Attribute
linked to: http://stackoverflow.com/q/50533363
has comment: http://stackoverflow.com/comment/89549406
tagged with: beautifulsoup
type: Question
tagged with: python
has answer: http://stackoverflow.com/a/51278370
answer count: 1
accepted answer: http://stackoverflow.com/a/51278370
score: 0
has body: I am practicing on Beautiful Soup and am after a products price, description and item number. The first 2 are text and are easy to get. The third is an attribute of the tag data-trade-price as seen below:- &lt;div class="price-group display-metro has-promo-price medium ng-scope" ng-class="{'has-trade-price': ShowTrade}" data-trade-price="221043"&gt; I am after the numbers such as 221043 which is loaded in by the page. IE - all 24 item numbers matching all 24 products My code is:- import requests r = requests.get('http://www.supercheapauto.com.au/store/car-care/wash-wax-polish/1021762?page=1&amp;pageSize=24&amp;sort=-ProductSummaryPurchasesWeighted%2C-ProductSummaryPurchases') from bs4 import BeautifulSoup soup = BeautifulSoup(r.text, 'lxml') results = soup.find_all('div', class_='details') for result in results: try: SKU = result.select_one("data-trade-price") except AttributeError: SKU = "N/A" DESC = result.find('div', class_='title').text.strip().upper() PRICE = result.find('span', class_='currency').text.strip().upper() print(SKU,'\t', DESC,'\t', PRICE) What is the syntax to get the item number from the soup? Sorry - I am after the syntax that can iterate through the page of 24 products and recover the 24 different item numbers. The example given was to show the part of the attribute value that I was after. I ran the given answer and it works. I am unsure of how to integrate into the code given as the variations I use do not. Any suggestions.
has comment: http://stackoverflow.com/comment/89535886

http://stackoverflow.com/comment/89367784
has text: missing module named numpy.core.maximum - imported by numpy.core, numpy.linalg.linalg missing module named numpy.core.add - imported by numpy.core, numpy.linalg.linalg missing module named numpy.core.complexfloating - imported by numpy.core, numpy.linalg.linalg missing module named numpy.core.inexact - imported by numpy.core, numpy.linalg.linalg
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51177430
type: Comment

http://stackoverflow.com/q/51215267
tagged with: python-3.x
has body: The question is rather academic. I came across the following behaviour in python: This Code: def dosth(): print("new") for n in range(0,10): return False dosth() actually gives me 10 prints instead of one. So does the function recursively call itself after the return statement because there is no break? If I put in a break before the return statement I still get 2 prints instead of only one. Can someone explain this behaviour
type: UnansweredQuestion
tagged with: python
tagged with: return
has title: Python function recalls itself after return statement?
has comment: http://stackoverflow.com/comment/89411805
type: Question
has answer: http://stackoverflow.com/a/51215376
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/89411747

http://stackoverflow.com/q/51167575
tagged with: file
upvote count: 1
has title: How can I read a text file from HDFS into Python, and save the content in a string?
score: 1
type: Question
downvote count: 0
tagged with: hdfs
has answer: http://stackoverflow.com/a/51167772
tagged with: string
has body: I have a .txt file saved in HDFS, and I want to read it in Python and save the content in a string variable. How can I do it?
answer count: 1
tagged with: python
tagged with: load
favorite count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/89416107
score: 0
comment on: http://stackoverflow.com/a/51217230
type: AnswerComment
has text: I honestly don't think it'd be that hard though. All you would need to is pass multiple ranges to the randint function, which is done nicely [here](https://stackoverflow.com/questions/33730396/python-how-to-generate-random-integers-with-multiple-ranges)
type: Comment

http://stackoverflow.com/q/51235911
tagged with: machine-learning
tagged with: tensorflow
type: Question
accepted answer: http://stackoverflow.com/a/51236116
has body: The original code is too bg so I will try to explain the issue with a simplified example. First, import the libraries we need: import tensorflow as tf from keras.applications.resnet50 import ResNet50 from keras.models import Model from keras.layers import Dense, Input Then load a pretrained model and print out the summary. model = ResNet50(weights='imagenet') model.summary() Here is the output of "summary": __________________________________________________________________________________________________ Layer (type) Output Shape Param # Connected to ================================================================================================== input_1 (InputLayer) (None, 224, 224, 3) 0 __________________________________________________________________________________________________ conv1_pad (ZeroPadding2D) (None, 230, 230, 3) 0 input_1[0][0] __________________________________________________________________________________________________ conv1 (Conv2D) (None, 112, 112, 64) 9472 conv1_pad[0][0] __________________________________________________________________________________________________ bn_conv1 (BatchNormalization) (None, 112, 112, 64) 256 conv1[0][0] __________________________________________________________________________________________________ activation_1 (Activation) (None, 112, 112, 64) 0 bn_conv1[0][0] __________________________________________________________________________________________________ max_pooling2d_1 (MaxPooling2D) (None, 55, 55, 64) 0 activation_1[0][0] __________________________________________________________________________________________________ res2a_branch2a (Conv2D) (None, 55, 55, 64) 4160 max_pooling2d_1[0][0] __________________________________________________________________________________________________ bn2a_branch2a (BatchNormalizati (None, 55, 55, 64) 256 res2a_branch2a[0][0] __________________________________________________________________________________________________ activation_2 (Activation) (None, 55, 55, 6…
score: 0
answer count: 1
tagged with: keras
tagged with: python
has answer: http://stackoverflow.com/a/51236116
has title: how to set trainable param in concatenated keras models
type: AnsweredQuestion
tagged with: conv-neural-network

http://stackoverflow.com/q/51317382
has comment: http://stackoverflow.com/comment/89611066
score: 7
has title: Cannot run Spyder because No module named 'PySide'
type: Question
has body: I wanted to try using Spyder IDE. I was reading this page on how to open and run Spyder: https://github.com/spyder-ide/spyder/releases I typed the following commands as specified in the page: conda update qt pyqt conda update spyder Both commands gave "# All requested packages already installed.". I then typed spyder into my terminal (Mac): Macs-MacBook:~ macuser$ spyder Traceback (most recent call last): File "/anaconda3/lib/python3.6/site-packages/qtpy/__init__.py", line 166, in &lt;module&gt; from PySide import __version__ as PYSIDE_VERSION # analysis:ignore ModuleNotFoundError: No module named 'PySide' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/anaconda3/bin/spyder", line 11, in &lt;module&gt; sys.exit(main()) File "/anaconda3/lib/python3.6/site-packages/spyder/app/start.py", line 159, in main from spyder.app import mainwindow File "/anaconda3/lib/python3.6/site-packages/spyder/app/mainwindow.py", line 49, in &lt;module&gt; So, I tried to install PySide: Macs-MacBook:~ macuser$ conda install PySide Solving environment: failed UnsatisfiableError: The following specifications were found to be in conflict: - anaconda==5.2.0=py36_3 - pyside Use "conda info &lt;package&gt;" to see the dependencies for each package. What should I do to get up and running with Spyder?
answer count: 6
has comment: http://stackoverflow.com/comment/89610885
has answer: http://stackoverflow.com/a/67070317
has answer: http://stackoverflow.com/a/77009882
has answer: http://stackoverflow.com/a/65424834
upvote count: 7
tagged with: spyder
has comment: http://stackoverflow.com/comment/89610823
favorite count: 0
has comment: http://stackoverflow.com/comment/89611046
has answer: http://stackoverflow.com/a/74184288
possible better answer: http://stackoverflow.com/a/65424834
accepted answer: http://stackoverflow.com/a/51317562
tagged with: python
has answer: http://stackoverflow.com/a/52527079
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51317562
downvote count: 0

http://stackoverflow.com/comment/89556249
has text: Your code sample is not complete, because you did not show how you actually delete the objects.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51288662
type: Comment

http://stackoverflow.com/comment/89577646
score: 1
comment on: http://stackoverflow.com/q/51299998
type: Comment
has text: You are using three attributes of `self` that don't exist.
type: QuestionComment

http://stackoverflow.com/a/51195732
type: Answer
upvote count: 1
has body: I recommend cleaner ways to store your data (like JSON or even python's pickle module). But this is out of the context of this answer. Assuming, you want to use your data format, you could read your file like this: my_object = xyz() variables_file = open("variables.txt", "r") for line in variables_file: line = line.rstrip("\n") # remove the linebreak at the end of each line line = line.split(",") # split the line at the comma -&gt; generates a list setattr(my_object, line[0], line[1]) # sets the variable as attribute of my_object print("And the name is: "+my_object.name)+"!!!") A better way is the use of dictionaries which is a more pythonic way than the java way: configs = {} And assign values like: configs["name"] = "David" or do it dynamically by iterating through the file like in the example above, just without setattr and with: configs[line[0]] = line[1]
answers question: http://stackoverflow.com/q/51195607
downvote count: 0
score: 1

http://stackoverflow.com/comment/89417817
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51218221
has text: @jaboja I found a total of four copies of python; how can I tell which one pip is pointed at?
score: 0

http://stackoverflow.com/comment/89470599
type: Comment
score: 1
has text: When you run a python file, it becomes the `__main__` module. So when you do `import main_`, you end up with 2 instances of the `main_.py` file - one named `__main__` and one named `main_`.
type: QuestionComment
comment on: http://stackoverflow.com/q/51245754

http://stackoverflow.com/comment/89423268
type: QuestionComment
has text: are the lines that start "values.append..." automatically including text from headers or somesuch?
score: 0
comment on: http://stackoverflow.com/q/51220010
type: Comment

http://stackoverflow.com/a/51281051
accepted answer of: http://stackoverflow.com/q/51192489
answers question: http://stackoverflow.com/q/51192489
type: Answer
score: 0
has body: I got it to work. you can find my code here. import tensorflow as tf def myCustomEstimator(features, labels, mode, params): """Modell funktion für Custom Estimator (DNN Regression)""" # Input Layer top = tf.feature_column.input_layer(features, params["feature_columns"]) # basierend auf hidden Units wird die Netztopologie aufgebaut for units in params.get("hidden_units", [20]): top = tf.layers.dense(inputs=top, units=units, activation=tf.nn.relu) if "dropout" in params.keys() and params["dropout"] != 0: top = tf.layers.dropout(inputs=top, rate=params["dropout"], training=mode == tf.estimator.ModeKeys.TRAIN) # lineares output layer mit 2 Neuronen für die 2 Koordinaten output_layer = tf.layers.dense(inputs=top, units=2) if mode == tf.estimator.ModeKeys.PREDICT: # In `PREDICT` mode we only need to return predictions. return tf.estimator.EstimatorSpec( mode=mode, predictions={"predictions": output_layer}) average_loss = tf.losses.mean_squared_error(tf.cast(labels, tf.float32), output_layer) tf.summary.scalar("average_loss", average_loss) MSE = tf.metrics.mean_squared_error(tf.cast(labels, tf.float32), output_layer) tf.summary.scalar('error', MSE[1]) # Pre-made estimators use the total_loss instead of the average, # so report total_loss for compatibility. batch_size = tf.shape(labels)[0] total_loss = tf.to_float(batch_size) * average_loss if mode == tf.estimator.ModeKeys.TRAIN: optimizer = params.get("optimizer", tf.train.AdamOptimizer) optimizer = optimizer(params.get("learning_rate", None)) train_op = optimizer.minimize( loss=average_loss, global_step=tf.train.get_global_step()) return tf.estimator.EstimatorSpec( mode=mode, loss=total_loss, train_op=train_op) # In evaluation mode we will calculate evaluation metrics. assert mode == tf.estimator.ModeKeys.EVAL # Calculate root mean squared error rmse = tf.metrics.root_mean_squared_error(tf.cast(labels, tf.float32), output_layer) # Add the rmse to the collection of evaluation metrics. eval_metrics = {"rmse": rmse, "average…
type: AcceptedAnswer

http://stackoverflow.com/a/51239472
type: Answer
answers question: http://stackoverflow.com/q/51239425
downvote count: 0
score: 1
has body: Using a list comprehension and all list1 = ['php', 'net'] d = {'lara': ['net', 'php', 'python'], 'john': ['php', 'c++'], 'ian': ['php','python']} print([k for k,v in d.items() if all(i in v for i in list1)]) Output: ['lara'] Expanded version. res = [] for k,v in d.items(): if all(i in v for i in list1): res.append(k)
upvote count: 1

http://stackoverflow.com/comment/116676312
type: AnswerComment
has text: Thanks for answering, but what do you do with your updatedict then ? Trying to change dtypes with `df= df.astype(updatedict)` will raise an error `dtype '<class 'sqlalchemy.sql.sqltypes.VARCHAR'>' not understood`
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51823355

import
type: Tag
tags question: http://stackoverflow.com/q/51238306
tags question: http://stackoverflow.com/q/51174135
tags question: http://stackoverflow.com/q/51179203
tag name: import
tags question: http://stackoverflow.com/q/51295385
tags question: http://stackoverflow.com/q/51298123
tags question: http://stackoverflow.com/q/51230457
tags question: http://stackoverflow.com/q/51186430
tags question: http://stackoverflow.com/q/51211384
tags question: http://stackoverflow.com/q/51250197
tags question: http://stackoverflow.com/q/51296034
tags question: http://stackoverflow.com/q/51212690
tags question: http://stackoverflow.com/q/51305898
tags question: http://stackoverflow.com/q/51203784
tags question: http://stackoverflow.com/q/51175548
tags question: http://stackoverflow.com/q/51245130

http://stackoverflow.com/comment/89567321
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51294505
has text: Indeed the `title` field is unique, but others aren't, and the `get_or_create()` applies to any `**kwargs` passed into it; in the end I worked around the problem by just using `SessionType.objects.get_or_create()` instead of the `SessionTypeFactory`.
score: 0

phantomjs
tags question: http://stackoverflow.com/q/51308826
tags question: http://stackoverflow.com/q/51209432
type: Tag
tags question: http://stackoverflow.com/q/51316968
tag name: phantomjs

http://stackoverflow.com/a/51181461
answers question: http://stackoverflow.com/q/51181411
type: Answer
has comment: http://stackoverflow.com/comment/89346501
has comment: http://stackoverflow.com/comment/89346474
has body: Is there a way for me to log these every 5 seconds to a single .txt file? Yes. Two and a half ways, in fact. First, you can modify the Python script to write to a text file instead of stdout: with open('logfile.txt', 'w') as f: while True: print("Some Data", file=f) print("More Data", file=f) print("Some More Data", file=f) time.sleep(5) Or, if you want to be able to pass it a filename instead of hardcoding logfile.txt: import sys filnename = sys.argv[1] with open(filename, 'w') as f: while True: print("Some Data", file=f) print("More Data", file=f) print("Some More Data", file=f) time.sleep(5) Now your batch file would do this: py myscript.py logfile.txt Of course in both of these cases, you don't have to use the file= argument to print; you could instead use f.write("Some Data\n") directly if you need more control over the file, or use the logging module to magically do fancier logging (e.g., with automatic timestamps). Alternatively, you can leave the Python script alone, and instead modify the batch file to use shell redirection: py myscript.py &gt;logfile.txt
score: 0

http://stackoverflow.com/comment/89665870
has text: Output file is repeating the header for every record. Also alignment problem for 2nd and third (Gyro & mag) when the output file is opened in excel. The file mode has to be changed to 'a' otherwise only last record is being written.
type: AnswerComment
comment on: http://stackoverflow.com/a/51313033
score: 0
type: Comment

http://stackoverflow.com/a/51210188
accepted answer of: http://stackoverflow.com/q/51207398
answers question: http://stackoverflow.com/q/51207398
has body: Finally I got the solution from bokeh.models import ColumnDataSource, GMapOptions,HoverTool TOOLTIPS = [ ("Place", "@Place"), ("News","@Title") ] p.add_tools( HoverTool(tooltips=TOOLTIPS)) I appended these Lines to my code to get tooltip
type: AcceptedAnswer
downvote count: 0
upvote count: 2
type: Answer
score: 2

http://stackoverflow.com/a/51249345
type: Answer
has body: You have two problems. First one is a typo, where you say if (val &gt; mid): you should say if (val &gt; arr[mid]): Since you're comparing the value and not the index. Second one is more subtle... when you check the right side of the array, in: return binary_search(arr[mid+1:], val) The subarray you're passing to the recursive call (arr[mid+1:]) already starts in the middle of the array, that means the result of that recursive call will return the index of the element in the subarray. So you need to add the index delta you used to split the array, to have a index based on the full array again: return binary_search(arr[mid+1:], val) + (mid + 1) Here's the full code for completeness: def binary_search(arr, val): left = 0 right = len(arr)-1 mid = (left + right)//2 #Go through the array if (val == arr[mid]): return mid #Check right side of arr if (val &gt; arr[mid]): return binary_search(arr[mid+1:], val) + (mid + 1) #Check left side of arr return binary_search(arr[:mid], val)
has comment: http://stackoverflow.com/comment/116490547
downvote count: 0
score: 3
accepted answer of: http://stackoverflow.com/q/51248973
answers question: http://stackoverflow.com/q/51248973
upvote count: 3
type: AcceptedAnswer

http://stackoverflow.com/a/51231976
has comment: http://stackoverflow.com/comment/89443634
answers question: http://stackoverflow.com/q/51231743
downvote count: 0
upvote count: 2
type: Answer
score: 2
has body: It's not about the xpath. It's about how the page is generated. If you check the content of page.content you will see there is no in the webpage's source. It's because the HTML content is mainly generated via Javascript. But this is not something that should stop you, if you open the raw html source (from page.content) and look for the value you want (2759.81), you will find a tag: and another 2759.81 , you can use one of them: print(tree.xpath('//*[@itemprop="price"]')[0].get('content')) Gives 2759.82

http://stackoverflow.com/q/51191313
downvote count: 1
answer count: 1
tagged with: calculator
has answer: http://stackoverflow.com/a/51191343
favorite count: 0
type: UnansweredQuestion
tagged with: python
upvote count: 0
tagged with: tkinter
has title: Calculator in Python with TKinter invalid syntax
has body: I want to make an calculator with python but when i want to run it, it says at be.bind("&lt;Button-1&gt;", calculate) at be invalid syntax. pls help, Here´s the code: from tkinter import * from math import * def calculate(event): equation = t.get() t.delete(0,END) try: t.insert(0, eval(equation)) except: t.insert(0, "incorrect input") top = Tk() t = Entry(top) t.grid(row=0,columnspan=3) b1 = Button(top,text="1") b1.grid(row=1,column=0) b2 = Button(top,text="2") b2.grid(row=1,column=1) b3 = Button(top,text="3") b3.grid(row=1,column=2) b4 = Button(top,text="4") b4.grid(row=2,column=0) b5 = Button(top,text="5") b5.grid(row=2,column=1) b6 = Button(top,text="6") b6.grid(row=2,column=2) b7 = Button(top,text="7") b7.grid(row=3,column=0) b8 = Button(top,text="8") b8.grid(row=3,column=1) b9 = Button(top,text="9") b9.grid(row=3,column=2) b0 = Button(top,text="0") b0.grid(row=4,column=1) bp = Button(top,text="+") bp.grid(row=0,column=3) bm = Button(top,text="-") bm.grid(row=1,column=3) bmu = Button(top,text="*") bmu.grid(row=2,column=3) bd = Button(top,text="/") bd.grid(row=3,column=3) be = Button(top,text="=") be.grid(row=4,column=3) bdel = Button(top,text="DEL") bdel.grid(row=4,column=2) b1.bind("&lt;Button-1&gt;", lambda x: t.insert(END,"1")) b2.bind("&lt;Button-1&gt;", lambda x: t.insert(END,"2")) b3.bind("&lt;Button-1&gt;", lambda x: t.insert(END,"3")) b4.bind("&lt;Button-1&gt;", lambda x: t.insert(END,"4")) b5.bind("&lt;Button-1&gt;", lambda x: t.insert(END,"5")) b6.bind("&lt;Button-1&gt;", lambda x: t.insert(END,"6")) b7.bind("&lt;Button-1&gt;", lambda x: t.insert(END,"7")) b8.bind("&lt;Button-1&gt;", lambda x: t.insert(END,"8")) b9.bind("&lt;Button-1&gt;", lambda x: t.insert(END,"9")) b0.bind("&lt;Button-1&gt;", lambda x: t.insert(END,"0")) bp.bind("&lt;Button-1&gt;", lambda x: t.insert(END,"+")) bm.bind("&lt;Button-1&gt;", lambda x: t.insert(END,"-")) bmu.bind("&lt;Button-1&gt;", lambda x: t.insert(END,"*")) bd.bind("&lt;Button-1&gt;", lambda x: t.insert(END,"/") be.b…
type: Question
has comment: http://stackoverflow.com/comment/89366307
score: -1

wsgi
type: Tag
tags question: http://stackoverflow.com/q/51294534
tags question: http://stackoverflow.com/q/51201901
tag name: wsgi

http://stackoverflow.com/comment/93134362
type: AnswerComment
score: 0
has text: Thanks @are for the answer. I'm pretty naive about using the pyFMI, can you please help me how exactly I can use the prebuild version that you provided?
type: Comment
comment on: http://stackoverflow.com/a/51374827

http://stackoverflow.com/q/51252040
tagged with: file-conversion
type: UnansweredQuestion
tagged with: python
has title: I want to convert .docx to .dotx
has comment: http://stackoverflow.com/comment/89539865
has body: I have populated some mail merge fields in a .docx file and now I want my script to convert the saved .docx file to a .dotx file. I am using Python 3.6. from __future__ import print_function from mailmerge import MailMerge from datetime import date from docx import Document from docx.opc.constants import CONTENT_TYPE as CT import csv import sys import os import numpy as np import pandas as pd # . . . for i in range(0, numTemplates): theTemplateName = templateNameCol[i] theTemplateFileLocation = templateFileLocationCol[i] template = theTemplateFileLocation document = MailMerge(template) print(document.get_merge_fields()) theOffice = officeCol[i] theAddress = addressCol[i] theSuite = suiteCol[i] theCity = cityCol[i] theState = stateCol[i] theZip = zipCol[i] thePhoneNum = phoneNumCol[i] theFaxNum = faxNumCol[i] document.merge( Address = theAddress ) document.write(r'\Users\me\mailmergeproject\test-output' + str(i) + r'.docx') #do conversion here Here at the bottom is where I want to do the conversion. As you can see, I've written a file and it's just sitting in a folder right now
type: Question
upvote count: 2
has answer: http://stackoverflow.com/a/78493283
score: 0
answer count: 2
downvote count: 2
has answer: http://stackoverflow.com/a/72043121
tagged with: ms-word
favorite count: 0
has comment: http://stackoverflow.com/comment/89557765
tagged with: http://stackoverflow.com/tag/docx

http://stackoverflow.com/comment/89480971
type: Comment
type: QuestionComment
score: 0
has text: i want to save it directly to s3. Convert the csv and write it directly to s3 to save processing time. The file is going to be atleast 500MB
comment on: http://stackoverflow.com/q/51250669

http://stackoverflow.com/comment/89357452
has text: @geek2000 - sorry, please give me some time.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51187292

http://stackoverflow.com/q/51312031
downvote count: 0
has body: In my bas class I have following implementation. def find_element(self, locatorMode, Locator): locator = CONFIG.LocatorMode element = None if locatorMode == locator['ID']: element = self.driver.find_element_by_id(Locator) elif locatorMode == locator['NAME']: element = self.driver.find_element_by_name(Locator) elif locatorMode == locator['XPATH']: element = self.driver.find_element_by_xpath(Locator) elif locatorMode == locator['CSS_SELECTOR']: element = self.driver.find_element_by_css_selector(Locator) elif locatorMode == locator['LINK_TEXT']: element = self.driver.find_element_by_link_text(Locator) else: raise Exception("Unsupported locator strategy") return element I am picking the LocatorMode on line 2 from config class. def fill_out_field(self, locatorMode, Locator, text): self.find_element((locatorMode, Locator)).clear() self.find_element((locatorMode, Locator)).send_keys(text) When I call fill_out_field method in my test case, it is giving me error: def agentLogin(self): self.driver.get(CONFIG.SITE_URL) self.assertEqual(CONFIG.SITE_LOGIN_URL, self.driver.current_url) self.take_snapshot(self.driver) credential = CONFIG.TEST_ACCOUNT self.fill_out_field("name", "accountId", credential['accountId']) Error: File "/Users/hassan/Documents/GitHub/poseidon/tests/base_test.py", line 155, in fill_out_field self.find_element((locatorMode, Locator)).clear() TypeError: find_element() missing 1 required positional argument: 'Locator'
has title: missing 1 required positional argument - Selenium python
favorite count: 0
has comment: http://stackoverflow.com/comment/89600985
tagged with: python-3.x
answer count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/89600795
type: UnansweredQuestion
tagged with: python
tagged with: selenium-webdriver
type: Question
tagged with: automation
score: 2

http://stackoverflow.com/a/61469174
upvote count: 2
type: Answer
downvote count: 0
score: 2
has body: If you are going to use an environment like this: \begin{equation} (a+b)^{2} = a^{2}+2ab+b^{2} \end{equation} Notice I do not use the $$ env which is better used as inline math. Another thing to notice is that there are no spaces between the lines, if you add spaces between the lines, the notebook will display the latex code instead of rendering it when you run the cell.
answers question: http://stackoverflow.com/q/51296060

http://stackoverflow.com/comment/89446045
comment on: http://stackoverflow.com/a/51233479
score: 0
type: AnswerComment
has text: Thank you! This was helpful.
type: Comment

cryptography
tag name: cryptography
type: Tag
tags question: http://stackoverflow.com/q/51180839
tags question: http://stackoverflow.com/q/51275520

http://stackoverflow.com/comment/89431711
comment on: http://stackoverflow.com/q/51225358
score: 0
has text: i need list to be like this each line as one dictionary [{1:88,11:1438,15:kkk,45:7.7....},{4:13,11:1438....},{6:84,41:18,56:TTT...}]
type: QuestionComment
type: Comment

http://stackoverflow.com/q/51205868
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89395246
tagged with: pickle
tagged with: python
has answer: http://stackoverflow.com/a/67736972
tagged with: multiprocessing
type: Question
has body: I'm reading and applying code from the python book and I can't use multiprocessing in simple example that you can see below: import multiprocessing def myProcess(): print("Currently Executing Child Process") print("This process has it's own instance of the GIL") print("Executing Main Process") print("Creating Child Process") myProcess = multiprocessing.Process(target=myProcess) myProcess.start() myProcess.join() print("Child Process has terminated, terminating main process") My platform is Windows 10 64 bit and using if __name_ == "__main_" : doesn't work in this case. What's wrong here? This code should work in python version 3.5 and above. Python version I use is 3.7. Full error message below: C:\Users\Xian\AppData\Local\Programs\Python\Python37-32\python.exe "C:/OneDrive/Utilizing sub-process.py" Traceback (most recent call last): File "C:/OneDrive/Utilizing sub-process.py", line 25, in &lt;module&gt; myProcess.start() File "C:\Users\Xian\AppData\Local\Programs\Python\Python37-32\lib\multiprocessing\process.py", line 112, in start self._popen = self._Popen(self) File "C:\Users\Xian\AppData\Local\Programs\Python\Python37-32\lib\multiprocessing\context.py", line 223, in _Popen return _default_context.get_context().Process._Popen(process_obj) File "C:\Users\Xian\AppData\Local\Programs\Python\Python37-32\lib\multiprocessing\context.py", line 322, in _Popen return Popen(process_obj) File "C:\Users\Xian\AppData\Local\Programs\Python\Python37-32\lib\multiprocessing\popen_spawn_win32.py", line 65, in __init__ reduction.dump(process_obj, to_child) File "C:\Users\Xian\AppData\Local\Programs\Python\Python37-32\lib\multiprocessing\reduction.py", line 60, in dump ForkingPickler(file, protocol).dump(obj) _pickle.PicklingError: Can't pickle &lt;function myProcess at 0x02B2D420&gt;: it's not the same object as __main__.myProcess
has comment: http://stackoverflow.com/comment/89395707
tagged with: python-multiprocessing
upvote count: 2
has title: multiprocessing pickling error: _pickle.PicklingError: Can't pickle <function myProcess at 0x02B2D420>: it's not the same object as __main__.myProcess
has comment: http://stackoverflow.com/comment/89396328
score: 0
downvote count: 2
answer count: 1
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/comment/89497663
comment on: http://stackoverflow.com/a/51253660
has text: Yes so the watcher is basically the one distributing jobs to the registered workers. Every worker consumes its own queue. The job of the supervisor is to provide regular status updates about the worker(s). This is all started from the same script. If you like to launch the supervisor in a separate script in order to observe the workers, then you'd have too look into [inter-process communication tools](https://docs.python.org/2/library/ipc.html) (e.g. via sockets, see [this question](https://stackoverflow.com/q/6920858/3767239); `ZeroMQ` is also a very nice framework).
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/89432584
type: Comment
type: QuestionComment
has text: And the only reason the first one doesn't work is that `some-attribute` isn't a valid Python identifier. The help explains the two ways to handle that, but since you already used one of those two ways in your next attempt, you should already know that.
comment on: http://stackoverflow.com/q/51226138
score: 0

http://stackoverflow.com/q/51276426
has answer: http://stackoverflow.com/a/51276642
type: UnansweredQuestion
tagged with: python
score: 1
has body: What I'm aiming to get is only the raw link which I can then use to download the image. but I keep getting some extra characters along with the link. from bs4 import BeautifulSoup import requests from bs4 import BeautifulSoup import requests def getPages(): x = 0 url = 'https://readheroacademia.net/manga/boku-no-hero-academia-chapter-137/' req = requests.get(url) webpage = req.content soup = BeautifulSoup(webpage, 'html.parser') pages = soup.findAll('div', attrs={'class': 'acp_content'}) for p in pages: y = p.findAll('img') print(y) getPages() What I end up getting looks like this: [&lt;img src="https://2.bp.blogspot.com/-p72DilhF-_s/WRSF41vu50I/AAAAAAAAlsk/6BTxzQAzPkwteMgEHch2JFH0JKKpbKrZACHM/s16000/0137-001.png"/&gt;] and I was hoping I could get something like this: https://2.bp.blogspot.com/-p72DilhF-_s/WRSF41vu50I/AAAAAAAAlsk/6BTxzQAzPkwteMgEHch2JFH0JKKpbKrZACHM/s16000/0137-001.png
tagged with: web-scraping
upvote count: 1
tagged with: python-requests
has answer: http://stackoverflow.com/a/51276504
type: Question
has title: Getting only the raw link using bs4 and requests
has answer: http://stackoverflow.com/a/51276884
answer count: 3
downvote count: 0
tagged with: string
favorite count: 0
tagged with: beautifulsoup

http://stackoverflow.com/q/51192398
has answer: http://stackoverflow.com/a/51192462
tagged with: pandas
downvote count: 0
answer count: 1
favorite count: 0
tagged with: python
has body: user cat val1 val2 val3 user1 cat1 3 NA NA cat2 NA NA NA cat3 NA NA 5 user2 cat1 NA NA NA cat2 NA 6 NA cat3 NA NA 7 user3 cat1 4 NA NA cat2 NA NA NA cat3 NA NA NA In this dataframe df, user and cat are indices. I want to iterate by user, and count how many rows per each user have ALL NA values. (cat1 corresponds to val1 and etc) In this example user1 and user2 have 1 missing row, and user3 has 2 missing rows. EDIT: answer was provided well below. what is the best way to filter df, so that only users with no missing values appear. I have: s[s == 0].index which provides the indices (below is it; above dataframe was just general df) Index([25c90900-cd25-4f51-8634-3eba9821e167, 29b63a9d-3a60-4d69-b507-145977b0dc49, 843a997d-5446-41d1-8697-4ded33bba85d, 690d0511-232c-4bd9-98ae-c9bb101bc18b, 35a2dabb-ac20-48cb-8d1e-adf53c68d546, 859591fd-67fc-41b3-823b-33053dbccc47, 7b8a4cfb-3010-4bc3-9963-14f2b4f6ffdb, 266f5f1f-0a58-49ca-9e66-7e8d2058a836, 77b99c57-f37b-48d5-b8b9-68929f31d3fc, 47afb3d3-98bb-4486-8935-a0b57a2de0c6, ... e14e69f6-3e33-4d1f-beff-76a35c2e11e9, e81c9737-e632-460a-9a12-c6bc7b48341b, c63ddb6e-2d89-4188-97c0-794aab70a816, 4c4a259c-7121-41c7-8e15-f8b87071489a, a612b6ee-4143-44a6-9214-81e607d4c9c3, 9d95839e-94c6-4659-ab88-95159e3a1238, 04826220-c5eb-4042-a355-217526aed323, 6054dd2d-9298-49b9-8617-3e156459ab2d, 3d8aeb80-7473-4d4c-90e6-8603133a7c65, 0aa7ac36-0274-48ba-86e6-f807645e0559], dtype='object', name='uuid', length=2217)
accepted answer: http://stackoverflow.com/a/51192462
type: AnsweredQuestion
score: 1
upvote count: 1
type: Question
has title: Count how many missing rows in pandas dataframe by user index

http://stackoverflow.com/a/51187054
type: Answer
score: 1
answers question: http://stackoverflow.com/q/51172571
upvote count: 1
has body: Ok, I assume that you were able to correctly load the json into a Python dictionnary, let call it item_dict, but the key may vary. What you need now it to walk inside that Python object, and decode the complete_time field. Unfortunately, Python strptime does not know about the Z time zone, so we will have to skip that last character. Additionaly, you should never modify a collection object while iterating it, so the bullet proof way is to store indices to remove and later remove them. Code could be: datelimit = datetime.datetime(2018, 4, 1) # limit date for completed_time to_remove = [] dateformat = '%Y-%m-%dT%H:%M:%S.%f' for k, v in item_dict.items(): # enumerate top_level objects for i, block in enumerate(v['completed']): # enumerate inner blocks complete_time = datetime.datetime.strptime( # skip last char from complete_time block["complete_time"][:-1], dateformat) # print(k, i, complete_time) # uncomment for tests if complete_time &lt; datelimit: # too old to_remove.append((k, i)) # store the index for later processing for k, i in reversed(to_remove): # start from the end to keep consistent indices del item_dict[k]["completed"][i] # actual deletion
has comment: http://stackoverflow.com/comment/89358307
has comment: http://stackoverflow.com/comment/90003584
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51172571

http://stackoverflow.com/comment/89446483
comment on: http://stackoverflow.com/q/51232282
score: 0
type: Comment
type: QuestionComment
has text: Another question while I am at it, can you runserver (python3 manage.py runserver) after you deployed your project on Heroku?

http://stackoverflow.com/a/51300552
answers question: http://stackoverflow.com/q/51300431
score: 1
downvote count: 0
type: Answer
has body: You've got the right idea, but just haven't quite got the syntax right. You should use: newnumbers = [(numbers[i] - numbers[i-1]) for i in range(1, len(numbers))] In your version you're trying to index a number, but you need to index your list instead.
upvote count: 1

http://stackoverflow.com/a/60142786
answers question: http://stackoverflow.com/q/51276461
score: 0
type: Answer
has body: Assuming you don't want to turn off buffering completely (this could cause inefficiencies in other parts of the code), just call sys.stdout.flush() after each print statement in server.py.

http://stackoverflow.com/a/51201049
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51201023
score: 1
has body: else state==glo.STATE_BUY_CYCLE: I guess you meant elif state==glo.STATE_BUY_CYCLE:
answers question: http://stackoverflow.com/q/51201023
type: Answer
upvote count: 1
type: AcceptedAnswer

http://stackoverflow.com/comment/89357800
type: Comment
score: 1
comment on: http://stackoverflow.com/q/51188058
type: QuestionComment
has text: [`df.dropna()`](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.dropna.html)

http://stackoverflow.com/comment/89470723
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/51245983
type: Comment
has text: MBCS is not an encoding, it's a category of encodings, namely those that use a variable number of bytes per character (or a fixed number, usually two). So you need to find out which one your file is using (UTF-8 is the most common one) and use that.

http://stackoverflow.com/q/51314457
has title: SQLAlchemy Inner Join and last record
favorite count: 0
tagged with: sqlite
tagged with: python
downvote count: 0
answer count: 0
has body: I am really struggling on trying to find a correct query with flask_sqlalchemy for a simple task. I have two tables: Players and Stats. In the Player there is naturally a list of players with some basic data like name, position, age, team etc. In the Stats table there are the stats for each player. Every player gets a new stats record in the stats table every day. I need to make a query that return all players from the Players table the players most recent stats record from Stats table. This is the closest I have gotten: db.session.query(Player, Stats).join(Stats)\ .order_by(Stats.id.desc())\ .limit(db.session.query(Player).count()) This way I am actually able to get the out the values I need, but there must be a better way. I would like to get the results out ordered by Stats.points, but with the current query the result is ordered by id. I hope I was clear enough. Database model definitions: class Player(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(80)) link = db.Column(db.String(80), unique=True) pos = db.Column(db.String) born = db.Column(db.Integer) team = db.Column(db.String(3)) date_added = db.Column(db.DateTime, nullable=False, default=datetime.utcnow) stats = db.relationship('Stats', backref='player', lazy=True) class Stats(db.Model): id = db.Column(db.Integer, primary_key=True) games_played = db.Column(db.Integer) goals = db.Column(db.Integer) assists = db.Column(db.Integer) points = db.Column(db.Integer) plus_minus = db.Column(db.Integer) pen_min = db.Column(db.Integer) date_added = db.Column(db.DateTime, nullable=False, default=datetime.utcnow) player_id = db.Column(db.Integer, db.ForeignKey('player.id'), nullable=False)
type: UnansweredQuestion
type: Question
score: 1
tagged with: sqlalchemy
upvote count: 1
has comment: http://stackoverflow.com/comment/89605902
tagged with: flask-sqlalchemy

http://stackoverflow.com/q/51248467
upvote count: 2
possible better answer: http://stackoverflow.com/a/51248621
has answer: http://stackoverflow.com/a/51248732
has answer: http://stackoverflow.com/a/51248727
has answer: http://stackoverflow.com/a/51248621
type: Question
has body: This is my code: onedata = str("&amp; "C:\Program Files\Windows Media Player\wmplayer.exe"") print (onedata) Im trying to run it but it says: onedata = str("&amp; "C:\Program Files\test.test") ^ SyntaxError: invalid syntax
has comment: http://stackoverflow.com/comment/89475831
accepted answer: http://stackoverflow.com/a/51248525
has comment: http://stackoverflow.com/comment/89475839
score: -2
downvote count: 4
has title: Python string invalid syntax
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51248525
tagged with: python
answer count: 4
type: AnsweredQuestion

http://stackoverflow.com/comment/89532777
comment on: http://stackoverflow.com/q/51277605
score: 0
type: QuestionComment
has text: Maybe check for changes in the page your are scraping ?
type: Comment

http://stackoverflow.com/comment/89448380
score: 2
type: AnswerComment
has text: `ast.literal_eval` would be much safer
type: Comment
comment on: http://stackoverflow.com/a/51234513

http://stackoverflow.com/q/51244141
has body: I use cv.imread to read a png file in python. When I then use cv.imwrite function to immediately save the image i then find that the colours in the image have changed slightly. I am trying to perform character recognition on this image and the OCR performs far less well on the image in python than the original image. The first image is the original, and the second is the saved one with OpenCV. We can see that the green has changed slightly and whilst this does not seem important it affects the OCR and I therefore imagine that other changes are happening to the png. Does anyone know why this might be and how i can resolve this. The code is as follows img = cv2.imread('file.png') cv2.imwrite('out.png', img) When I run file.png in tesseract for character recognition I get great results but when I run out.png in tesseract far less words get recognised correctly.
has comment: http://stackoverflow.com/comment/89470169
linked to: http://stackoverflow.com/q/33142786
has comment: http://stackoverflow.com/comment/89470995
has comment: http://stackoverflow.com/comment/89470436
type: Question
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/89469561
has comment: http://stackoverflow.com/comment/89470243
has comment: http://stackoverflow.com/comment/89470873
has comment: http://stackoverflow.com/comment/89467887
tagged with: python
favorite count: 0
score: 2
has answer: http://stackoverflow.com/a/51246946
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89467249
has title: Open CV cv.imread modifying image
tagged with: opencv

http://stackoverflow.com/q/51264932
type: AnsweredQuestion
score: 1
upvote count: 1
type: Question
tagged with: dataframe
has answer: http://stackoverflow.com/a/51264988
tagged with: pandas
downvote count: 0
answer count: 1
favorite count: 0
has title: How to properly make an assignment to a slice of a multiindexed dataframe in pandas?
has body: I am running Pandas 0.20.3 with Python 3.5.3 on macOS. I have a multiindexed dataframe similar to the following df: import pandas as pd import numpy as np refs = ['A', 'B'] dates = pd.date_range(start='2018-01-01', end='2018-12-31') df = pd.DataFrame({'ref': np.repeat(refs, len(dates)), 'date': np.tile(dates, len(refs)), 'value': np.random.randn(len(dates) * len(refs))}) df.set_index(["ref", "date"], inplace=True) I want to modify the dataframe and set some values to 0. Say where ref is equal to 'A' and where date is before 2018-01-15. I am using the following: df.loc["A"].loc[df.loc["A"].index &lt; pd.to_datetime('2018-01-15')] = 0 I do not get any SettingWithCopyWarningand the dataframe is modified correctly on my mac. However when I run this code on a Windows environment with the same pandas version, the dataframe is not modified. Hence my question: Is the above code incorrect? If not, how to properly make the assignment I need?
linked to: http://stackoverflow.com/q/17921010
tagged with: python
accepted answer: http://stackoverflow.com/a/51264988

http://stackoverflow.com/a/51237703
upvote count: 2
type: Answer
score: 2
has body: You need to also specify the instance where you want the files copied, otherwise the destination is interpreted as a local file, leading to the (2nd line of) your error message. From the gcloud compute scp examples: Conversely, files from your local computer can be copied to a virtual machine: $ gcloud compute scp ~/localtest.txt ~/localtest2.txt \ example-instance:~/narnia In your case it should be something like: gcloud compute scp /Users/abrahammathew/Desktop/LZ_demo_poc/helper_functions.py your_instance_name:/home/abraham_mathew/lz_text_classification/
downvote count: 0
answers question: http://stackoverflow.com/q/51237623

http://stackoverflow.com/comment/89397372
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51207770
has text: edited.........

http://stackoverflow.com/comment/89545998
score: 0
comment on: http://stackoverflow.com/q/51271997
type: Comment
type: QuestionComment
has text: question has nothing to do with `machine-learning` or `nlp` - kindly do not spam the tags (removed)

http://stackoverflow.com/q/51309895
answer count: 2
linked to: http://stackoverflow.com/q/14765351
tagged with: flask
favorite count: 0
linked to: http://stackoverflow.com/q/48205495
linked to: http://stackoverflow.com/q/23818572
has title: OSError: [Errno 48] Address already in use
tagged with: sockets
duplicate of: http://stackoverflow.com/q/48205495
tagged with: python
linked to: http://stackoverflow.com/q/19071512
upvote count: 3
type: UnansweredQuestion
has body: I'm trying to setup a server from Mac terminal. I've established a connection on port 5000 and want to open another port in 5002 using this command: python Blockchain.py -p 5002 But this gives the error: OSError: [Errno 48] Address already in use I tried to verify if port 5002 is open and listening. So I run shell command lsof -i:5002 but it returns none. Stacktrace Error log & stacktrace attached below: Traceback (most recent call last): File "Blockchain.py", line 290, in <module> app.run(host='0.0.0.0', port=5000) File "/anaconda/envs/blockchain/lib/python3.6/site-packages/flask/app.py", line 841, in run run_simple(host, port, self, **options) File "/anaconda/envs/blockchain/lib/python3.6/site-packages/werkzeug/serving.py", line 814, in run_simple inner() File "/anaconda/envs/blockchain/lib/python3.6/site-packages/werkzeug/serving.py", line 774, in inner fd=fd) File "/anaconda/envs/blockchain/lib/python3.6/site-packages/werkzeug/serving.py", line 666, in make_server passthrough_errors, ssl_context, fd=fd) File "/anaconda/envs/blockchain/lib/python3.6/site-packages/werkzeug/serving.py", line 577, in __init__ self.address_family), handler) File "/anaconda/envs/blockchain/lib/python3.6/socketserver.py", line 453, in __init__ self.server_bind() File "/anaconda/envs/blockchain/lib/python3.6/http/server.py", line 136, in server_bind socketserver.TCPServer.server_bind(self) File "/anaconda/envs/blockchain/lib/python3.6/socketserver.py", line 467, in server_bind self.socket.bind(self.server_address) OSError: [Errno 48] Address already in use Research I've referred various answers on the same issue: socket.error: [Errno 48] Address already in use Flask and Pycharm socket.error Python - Socket Error, Address In Use What I tried Also, I tried the following methods to resolve the issue: Restarting the terminals Restarting PyCharm Running on different sockets (gives same error). None of that seems to work. I'm fairly new to Python. Any help is appreciated.
downvote count: 1
score: 2
has answer: http://stackoverflow.com/a/51309985
type: Question
has answer: http://stackoverflow.com/a/51310430

http://stackoverflow.com/q/51197176
has comment: http://stackoverflow.com/comment/93409360
downvote count: 0
score: 1
type: Question
tagged with: dataframe
has answer: http://stackoverflow.com/a/51197732
has comment: http://stackoverflow.com/comment/93411791
tagged with: string-search
accepted answer: http://stackoverflow.com/a/51197884
answer count: 2
tagged with: pandas
upvote count: 1
has comment: http://stackoverflow.com/comment/89376081
possible better answer: http://stackoverflow.com/a/51197732
favorite count: 0
has answer: http://stackoverflow.com/a/51197884
has title: pandas, python, excel, search for substring in column of df 1 to write string to column in df2
tagged with: python
has body: I am using the package pandas in python to work with and read and write to excel spreadsheets. I have created 2 different dataframes (df1 and df2) that have cells that are all of the data type string. df1 has over 50,000 rows. There are many cells in each column of df1 that were “Nan”and I have converted to to a string that says “Empty”. df2 has over 9000 rows. Every row in “WHSE_Nbr” and “WHSE_Desc_HR” contains an accurate string value. Only some rows have values other than the string “Empty” in the last 2 columns of df2. The “Warehouse” column in df1 has many cells containing names with only words. The rows of the “Warehouse” column in df1 that I am interested in identifying are the ones that contain any of the warehouse numbers that are found in df2 in the “WHSE_Nbr” column. Example of dataframe1 - df1 Job Warehouse GeneralDescription Purpose Empty AP Accounts Payable Accounting Empty Empty Empty Empty Empty Cyber Security GA Security &amp; Compliance Data Security Empty Merch|04-1854 Empty Empty Empty WH -1925 Empty Empty Empty Montreal-10 Empty Empty Empty canada| 05-4325 Empty Empty Example of dataframe2 - df2 WHSE_Nbr WHSE_Desc_HR WHSE_Desc_AD WHSE_Abrv 1 Technology Tech 2 Finance ... ... 10 Recruiting Campus Outreach 1854 Community Relations ... ... 1925 HumanResources 4325 Global People 9237 International Tech Example of dataframe2 df2 So I want to iterate through all rows of the “Warehouse Column” of df1 to search for WHSE numbers that appear in the WHSE_Nbr column of df2. In this example, I would want my code to find 1854 in the “Warehouse” column of df1 and map that number to the associated cell in the WHSE_Desc_HR column of df2 and write “Community Relations” in the “GeneralDescription” column of df1 (to same row that contains substring “1854” In Warehouse column. And it would also write “Human Resources” to Warehouse column in same row substring “1925” appears in the Warehouse column. When the iteration reaches “Montreal 10”, I would want my code to wr…
tagged with: excel
type: AnsweredQuestion

http://stackoverflow.com/a/51297955
has body: It's a simple typo. You're calling for .hours but actually the keyword is .hour Try going with t = t2.hour - t1.hour From Python interpreter: &gt;&gt;&gt; t1 = datetime.time(10,49,00) &gt;&gt;&gt; t2 = datetime.time(16,38,00) &gt;&gt;&gt; t = t2.hour - t1.hour &gt;&gt;&gt; t 6 But just so you know, if you want to use the .hour keyword, it's useless to use a float, because it will always return x.0 because whatever full hours you decide to subtract, you will never get a float that isn't .0
answers question: http://stackoverflow.com/q/51297844
type: Answer
score: 2
upvote count: 2
downvote count: 0

http://stackoverflow.com/comment/89410657
type: Comment
has text: You'll have to import it. I think its from here: `from google.api_core.exceptions import InvalidArgument ` [https://googlecloudplatform.github.io/google-cloud-python/latest/core/exceptions.html#google.api_core.exceptions.InvalidArgument](https://googlecloudplatform.github.io/google-cloud-python/latest/core/exceptions.html#google.api_core.exceptions.InvalidArgument) The reason why it ran through as if there were no errors is because using `Exception` will catch/handle everything. Which is not what you want.
comment on: http://stackoverflow.com/a/51200829
score: 0
type: AnswerComment

http://stackoverflow.com/q/51235402
has body: I'm having something strange happen with the Robinhood API. Specifically with getting all of the options instruments (just data about the options). The code below is part of my program def get_options_instruments(self): params = { "chain_symbol" : "AMD", "chain_id" : "e66ce029-db96-4572-87a0-b144613c08bf", "type": "call", "state": "active", "tradability": "tradable", "strike_price" : "16.0000", "expiration_date": "2018-10-19" } #API_URLS['option-instrument']= "https://api.robinhood.com/options/instruments/" response = self.login_session.get(API_URLS['option-instrument'],params = params) response = response.json()["results"] print(json.dumps(response,indent = 4,separators=(',', ': ')))#'option-instrument' : "https://api.robinhood.com/options/instruments/", All parameters seem to have an effect when receiving the option instruments EXCEPT expiration date (which is the most one of the important parameters that I need to use). Below is a sample response of an option instrument. { "issue_date": "1987-01-12", "strike_price": "16.0000", "url": "https://api.robinhood.com/options/instruments/3cb75cca-0987-46d7-bff1-20cadfb74a83/", "expiration_date": "2018-07-20", "tradability": "tradable", "chain_id": "e66ce029-db96-4572-87a0-b144613c08bf", "updated_at": "2018-06-03T00:16:56.985489Z", "min_ticks": { "cutoff_price": "3.00", "below_tick": "0.01", "above_tick": "0.05" }, "state": "active", "id": "3cb75cca-0987-46d7-bff1-20cadfb74a83", "chain_symbol": "AMD", "type": "call", "created_at": "2017-11-18T04:15:17.795113Z" } I'm just wondering if anybody has any idea why something like this might happen? Could it perhaps be something on the API's side and not mine? Thank you.
tagged with: python-2.7
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/55028328
has title: Robinhood API Python
type: UnansweredQuestion
tagged with: python
tagged with: http://stackoverflow.com/tag/json
tagged with: python-requests
type: Question

http://stackoverflow.com/q/51316937
has title: Cannot use gcloud compute ssh command in python subprocess
tagged with: google-cloud-platform
downvote count: 0
answer count: 3
has body: I have a compute engine already set up, I can use ssh command in command prompt, like gcloud compute ssh test-instance@cloud-engine-noapi --zone us-central1-f --command "rm -f test.txt" and successfully delete the test.txt in server. However, when I call these in python. subprocess.call(['gcloud', 'compute', '--project', 'test-project','ssh', temp_instance, '--zone', zone, '--command', '"cd /home"'], shell=True) subprocess.call(['gcloud', 'compute', '--project', 'test-project','ssh', temp_instance, '--zone', zone, '--command', '"ls -l"'], shell=True) subprocess.call(['gcloud', 'compute', '--project', 'test-project','ssh', temp_instance, '--zone', zone, '--command', '"rm -f /home/test.txt"'], shell=True) The return is always like bash: /command : No such file or directory and for command like ls bash: /command : command not found Is there any process I have to do first?
tagged with: python
favorite count: 0
has answer: http://stackoverflow.com/a/51354235
upvote count: 1
tagged with: google-compute-engine
accepted answer: http://stackoverflow.com/a/51354235
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/78562315
has answer: http://stackoverflow.com/a/71205236
score: 1
possible better answer: http://stackoverflow.com/a/71205236
type: Question

http://stackoverflow.com/q/51206916
downvote count: 0
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/51209869
tagged with: pandas
has comment: http://stackoverflow.com/comment/89395263
tagged with: python
accepted answer: http://stackoverflow.com/a/51209869
tagged with: python-3.x
upvote count: 1
tagged with: dictionary
type: AnsweredQuestion
has body: If I have a dataframe df_i and I want to split it into sub-dataframes based on unique values of 'Cycle Number' I use: dfs = {k: df_i[df_i['Cycle Number'] == k] for k in df_i['Cycle Number'].unique()} Assuming the 'Cycle Number' ranges from 1 to 50 and in each cycle, I have steps ranging from 1 to 15, how do I split each data frame into 15 further data frames? I am presuming something of this type would work: for i in range(1,51): dsfs = {k: dfs[i][dfs[i]['Step Number'] == k] for k in dfs[i]['Step Number'].unique()} But, this will return me 15 data frames only from the cycle number corresponding to 50, not the ones before. If I want to access a sub-dataframe in the 20th Cycle with step number 10, is there a way of generating the subdata frame such that I can access it using something like dfs[20][10]? A simple parallel: Step Number Cycle Number Desired Access 1 1 dfs[1][1] 2 1 dfs[1][2] 3 1 dfs[1][3] 4 1 dfs[1][4] 5 1 dfs[1][5] 1 2 dfs[2][1] 2 2 dfs[2][2] 3 2 dfs[2][3] 4 2 dfs[2][4] 5 2 dfs[2][5] 1 3 dfs[3][1] 2 3 dfs[3][2] 3 3 dfs[3][3] 4 3 dfs[3][4] 5 3 dfs[3][5] 1 4 dfs[4][1] 2 4 dfs[4][2] 3 4 dfs[4][3] 4 4 dfs[4][4] 5 4 dfs[4][5]
score: 1
tagged with: dataframe
has comment: http://stackoverflow.com/comment/89394718
type: Question
has title: Subdataframes of Subdataframes

http://stackoverflow.com/comment/89617320
type: QuestionComment
has text: `where python` will give me 3 pythons (the ones that are in the two directories of version 2.7.15 and 2.73, and a third one, which is in the Abaqus directory.) The 2.7.15 is listed first. If I `where python` in the directory of python 2.7.3, the version 2.7.3 will come first.
comment on: http://stackoverflow.com/q/51320802
score: 0
type: Comment

http://stackoverflow.com/comment/89955257
score: 0
type: AnswerComment
type: Comment
has text: I clearly explained what .bytes is used for. FYI, it has nothing to do with "graph model for the brain in ML" as you mentioned in your answer. It's used to represent binary files not supported in Unity.
comment on: http://stackoverflow.com/a/51301766

http://stackoverflow.com/a/51235285
has body: You want to cross this plot line : plt.plot([0,W_[1]],[0,W_[2]]) with your scatter plot? If so the suppose problem are in this range plot. Your scatter plot have this axis ranges: X: 4~8 Y: 1.5~5 But you line plot have the ranges X:[0,W_[1]] Y:[0,W_[2]] You should ''normalize'' both ranges to have a good graphical merge.
has comment: http://stackoverflow.com/comment/89450378
has comment: http://stackoverflow.com/comment/89450263
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51235127
answers question: http://stackoverflow.com/q/51235127
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/89452902

http://stackoverflow.com/q/51169415
score: -1
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/89321769
has body: I have a csv file which contains the sgpa of students. I have to calculate the cgpa of these students. The student's id_no is the primary key in the csv file. The file is in the form: St_id St_name sem_id sgpa 1 abc 1 2 2 pqr 1 2.5 1 abc 2 3 2 pqr 2 3.5 3 xzy 1 4.0 I now need a new column that calculates the cgpa of students. The new table should be in the form: St_id St_name sem_id sgpa cgpa 1 abc 1 2 2.5 2 pqr 1 2.5 3.0 1 abc 2 3 2.5 2 pqr 2 3.5 3.0 3 xzy 1 4.0 4.0 I have thousands of students like this, so I cannot calculate it manually. Can someone please suggest a way to accomplish this task in Python? Thank you in advance for your help.
has answer: http://stackoverflow.com/a/51169852
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/89321614
possible better answer: http://stackoverflow.com/a/51169971
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51169971
accepted answer: http://stackoverflow.com/a/51169852
downvote count: 1
type: Question
has title: Calculate the average of a quantity based on a primary key in a csv file
answer count: 2
upvote count: 0

http://stackoverflow.com/q/51171028
has body: Here is a leaf I want to find the length of it's periphery i.e. it's perimeter using openCV and Python.I tried writing a code but it is not giving the desired result.I have to reset the threshold for every example and also it's not giving a closed contour.I want it to be a generalized code to work on all such leaves. Please help me here: import cv2 #reading the image col = cv2.imread("leaf2.jpg") width,height,channels = col.shape col=cv2.resize(col,(width,height),interpolation=cv2.INTER_CUBIC) image=cv2.pyrMeanShiftFiltering(col,10,100,3) edged = cv2.Canny(image, 0,10) kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (7, 7)) closed = cv2.morphologyEx(edged, cv2.MORPH_CLOSE, kernel) #finding_contours image, contours, hierarchy = cv2.findContours(closed, cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE) perimeter=0 for c in contours: peri = cv2.arcLength(c, True) approx = cv2.approxPolyDP(c, 0.02 * peri, True) cv2.drawContours(image, [approx], -1, (0, 255, 0), 2) perimeter = perimeter+cv2.arcLength(c,True) print(perimeter) cv2.imshow("Output", image) cv2.waitKey(0)
upvote count: 2
tagged with: canny-operator
downvote count: 1
tagged with: opencv
type: AnsweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/89325019
tagged with: image-processing
has answer: http://stackoverflow.com/a/51172475
has comment: http://stackoverflow.com/comment/89326212
type: Question
tagged with: contour
has comment: http://stackoverflow.com/comment/89324947
has title: Find the perimeter of the leaf
has comment: http://stackoverflow.com/comment/89325929
accepted answer: http://stackoverflow.com/a/51172475
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/89325676
tagged with: python
has comment: http://stackoverflow.com/comment/89324692

3d
tags question: http://stackoverflow.com/q/51167814
type: Tag
tags question: http://stackoverflow.com/q/51215206
tags question: http://stackoverflow.com/q/51172765
tags question: http://stackoverflow.com/q/51306488
tag name: 3d
tags question: http://stackoverflow.com/q/51218964
tags question: http://stackoverflow.com/q/51254419

http://stackoverflow.com/q/51217067
tagged with: opencv
has body: I want to make a desktop app for video editing. It will be a Windows based app. My question is should I use python or .Net, because main part is working with video and audio. I know that .NET's wpf is great framework for making desktop apps (I have experience in it) with its xaml for creating GUI and all tools which .NET provides, but OpenCV in python is great tool for video editing and I do not have any experience in making desktop apps in python or any GUI based apps. Can .NET offer me some libraries for video editing that could match OpenCV ?
downvote count: 0
has answer: http://stackoverflow.com/a/51217119
score: 1
type: Question
tagged with: .net
has title: Video editor desktop app for Windows .NET or python
upvote count: 1
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python
tagged with: video-editing

http://stackoverflow.com/comment/89473379
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51247168
has text: @Scotty1- see my edit

http://stackoverflow.com/comment/89528603
type: QuestionComment
comment on: http://stackoverflow.com/q/51274595
has text: "My code works, please look it over" is probably a question for Code Review, not for Stack Overflow.
score: 0
type: Comment

http://stackoverflow.com/comment/89583953
comment on: http://stackoverflow.com/a/51278197
has text: File "H:\python-anaconda\lib\site-packages\PIL\Image.py", line 1917, in save raise ValueError('unknown file extension: {}'.format(ext)) ValueError: unknown file extension:
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/51221385
upvote count: 1
has body: I think you need to loop on your find_all: for div in soap.find_all("div")
has comment: http://stackoverflow.com/comment/89423420
type: Answer
answers question: http://stackoverflow.com/q/51221190
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/89423427

http://stackoverflow.com/a/51226905
upvote count: 2
has body: pop is not a built-in Python function. Only things.pop() works in your example. On the other hand, if you're asking about list.pop(things), then yes it is identical to things.pop(). Although list.pop(things) is slightly less readable than things.pop() and is therefore not recommended in general, list.pop can be useful when you use it as a function for certain iterator-based operations. For example, the following gives you a list of the last item of each sub-list of a list: &gt;&gt;&gt; a=[[1, 2, 3],[9, 8, 7]] &gt;&gt;&gt; list(map(list.pop, a)) [3, 7] &gt;&gt;&gt;
score: 2
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51226871
downvote count: 0
answers question: http://stackoverflow.com/q/51226871
type: Answer

http://stackoverflow.com/q/51300372
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/51300422
tagged with: pandas-groupby
tagged with: pandas
favorite count: 0
upvote count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/51300422
type: AnsweredQuestion
has title: Groupby apply with multiple arguments
score: 1
tagged with: apply
has body: I'd like to calculate the percentile rank based on which Group they belongs to. I have written the following codes and was able to calculate, say zscore as there is only one input. What shall I do with a function which has two arguments? Thanks. import pandas as pd import scipy.stats as stats import numpy as np funZScore = lambda x: (x - x.mean()) / x.std() funPercentile = lambda x, y: stats.percentileofscore(x[~np.isnan(x)], y) A = pd.DataFrame({'Group' : ['A','A','A','A','B','B','B'], 'Value' : [4, 7, None, 6, 2, 8, 1]}) # Compute the Z-score by group A['Z'] = A.groupby('Group')['Value'].apply(funZScore) print(A) Group Value Z 0 A 4.0 -1.091089 1 A 7.0 0.872872 2 A NaN NaN 3 A 6.0 0.218218 4 B 2.0 -0.440225 5 B 8.0 1.144586 6 B 1.0 -0.704361 # compute the percentile rank by group # how to put two arguments into groupby apply? # I hope to get something like below Group Value Z P 0 A 4.0 -1.091089 33.33 1 A 7.0 0.872872 100 2 A NaN NaN NaN 3 A 6.0 0.218218 66.67 4 B 2.0 -0.440225 66.67 5 B 8.0 1.144586 100 6 B 1.0 -0.704361 33.33
tagged with: scipy
type: Question

http://stackoverflow.com/q/51227601
has body: How would I go about formatting a 10 digit string: 0123456789 to phone number format: (012) 345-6789 Is there a specific library to use or can you use regex? I've done it the other way around by using re.sub('[^0-9]', '', '(012) 345-6789')
has answer: http://stackoverflow.com/a/66233632
answer count: 6
has comment: http://stackoverflow.com/comment/138838086
has answer: http://stackoverflow.com/a/51227649
accepted answer: http://stackoverflow.com/a/51227649
upvote count: 7
downvote count: 1
has answer: http://stackoverflow.com/a/51227710
favorite count: 0
tagged with: python-3.x
score: 6
tagged with: python
tagged with: regex
has title: Python format phone number
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51227667
has answer: http://stackoverflow.com/a/51227770
type: Question
has answer: http://stackoverflow.com/a/62219947
possible better answer: http://stackoverflow.com/a/51227667

http://stackoverflow.com/comment/89486934
score: 0
comment on: http://stackoverflow.com/q/51252936
has text: I am unable to reproduce an `AssertionError` error. This should actually throw a `RuntimeError` since no application is bound to the current context. Add something like `application.app_context().push()` as the first line of your `setUp` function. Also, you should probably have something like `self.client = application.test_client()` instead of `self.application = application.test_client()`.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89538935
comment on: http://stackoverflow.com/a/51208775
type: AnswerComment
score: 0
type: Comment
has text: @alluri I've converted lists of labels and values into `numpy` arrays. This is because Abaqus is expecting that labels and values are allocated as contiguous blocks of memory. When defining arrays, we can define data types. Labels are always integers and field outputs are floting point numbers.

http://stackoverflow.com/q/51237022
score: 0
linked to: http://stackoverflow.com/q/50884185
has title: Use of pcolormesh() to project onto a geographic map
duplicate of: http://stackoverflow.com/q/31822553
has comment: http://stackoverflow.com/comment/89463218
tagged with: matplotlib-basemap
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89464743
answer count: 0
has comment: http://stackoverflow.com/comment/89462999
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89463074
has comment: http://stackoverflow.com/comment/89457702
has comment: http://stackoverflow.com/comment/89453284
has comment: http://stackoverflow.com/comment/89459463
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/89457888
type: Question
has comment: http://stackoverflow.com/comment/89457175
linked to: http://stackoverflow.com/q/35168638
has body: I am using this program to project my ammonia concentration over India region, but when I run this code: from mpl_toolkits.basemap import Basemap import matplotlib.pyplot as plt import numpy as np def read_datafile(file_name): data = np.genfromtxt(file_name, delimiter=',', names=['lat', 'lon', 'nh']) return data data = read_datafile('E:/algo/data/combining/FINAL_DATA.csv') map = Basemap(llcrnrlon=66,llcrnrlat=6,urcrnrlon=98.5,urcrnrlat=38, resolution='i', projection='cyl') map.drawcoastlines() map.drawlsmask() map.drawcountries() parallels = np.arange(6,38,5) meridians = np.arange(66,99,5) map.drawparallels(parallels,labels=[1,0,0,0],fontsize=10) map.drawmeridians(meridians,labels=[0,0,0,1],fontsize=10) lons,lats= np.meshgrid(data['lon'][1:],data['lat'][1:],sparse = 'True') x,y = map(lons,lats) map.pcolormesh(x,y,data['nh'][1:]) plt.show() It shows me the error: ValueError: not enough values to unpack (expected 2, got 1) in the map.pcolor(x,y,z) And I used data['lon'][1:] because the 1st value was nan maybe due to header. So, any way to remove that error, please!!! The csv file contains: ,lat,lon,Unnamed: 0,nh 0,7.75,71.75,0.5,8501464385113510.0 1,7.75,74.25,2.5,8019719264331602.0 2,7.75,75.25,4.5,7708972186355438.0 3,7.75,78.75,6.5,1.5269509187007006e+16 4,7.75,87.75,8.5,1.5235106744690036e+16 5,7.75,88.25,10.0,8944079502837338.0 6,7.75,91.25,12.0,1.1589890596655764e+16 7,7.75,91.75,14.5,1.0453168566752552e+16 8,7.75,92.75,16.0,1.0493223728181644e+16 9,7.75,93.25,18.5,1.0345603893411792e+16 10,7.75,95.25,21.0,1.141171929073354e+16 11,7.75,96.75,22.5,7782035033549430.0 12,8.25,70.25,24.0,8201072171587072.0 13,8.25,70.75,25.5,7602494056851770.0 14,8.25,73.25,28.0,9214770255302838.0 15,8.25,73.75,30.0,7005492206478936.0 16,8.25,74.25,31.0,8266837257825698.0 17,8.25,76.25,32.5,8149348547108306.0 18,8.25,78.25,34.5,7761299283688882.0 19,8.25,79.25,36.5,8122365507049480.0 20,8.25,84.25,38.5,7505510890250006.0 21,8.25,86.75,40.0,9349574410796046.0 22,8.25,87.25,41.0,97590…
has comment: http://stackoverflow.com/comment/89457979
has comment: http://stackoverflow.com/comment/89462746

http://stackoverflow.com/comment/89587138
type: QuestionComment
comment on: http://stackoverflow.com/q/51305222
score: 1
type: Comment
has text: That's not necessarily a real thing, just example code to show how you might go about testing something. There is a [`ttk.Widget`](https://docs.python.org/2/library/ttk.html?highlight=widget#widget), but it *"is not supposed to be directly instantiated"*.

http://stackoverflow.com/q/51184116
answer count: 3
has title: Import chainer in python throws error
tagged with: python
has answer: http://stackoverflow.com/a/51184369
type: UnansweredQuestion
tagged with: chainer
has answer: http://stackoverflow.com/a/51184234
has body: I get the error: module 'matplotlib.colors' has no attribute 'to_rgba', when i import chainer in ipynb. I am using python 2 ,anaconda 4.1.1 ,chainer 4 and matplotlib 1.5.1.could anyone asses the problem
tagged with: anaconda
type: Question
has answer: http://stackoverflow.com/a/51184401
score: 0

http://stackoverflow.com/a/51263709
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51256446
answers question: http://stackoverflow.com/q/51256446
type: Answer
has body: Your static file mapping for images is at at /images, but you're accessing the image from /snapcapsule/images. Either change your media_url or your static file mapping so that they match.
upvote count: 1
score: 1

http://stackoverflow.com/q/51277978
tagged with: google-sheets-api
tagged with: google-sheets
has title: Insert a list into google sheets using gspread
answer count: 1
tagged with: gspread
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/56481375
score: 0
has body: list = [['Akbar',1,34],['lata',1,56],['sita',5,45]] I want this list inserted as cell_list = worksheet.range('A1:C7') for cell in cell_list: cell.value = 'O_o' # Update in batch worksheet.update_cells(cell_list) This is mentioned in gspread 3.0.1 docs is there anything that is direct? like in the previous version?(3.0.0) spread_sheet.values_update( RANGE, params={'valueInputOption': 'RAW'}, body={'values': list} )
type: Question

http://stackoverflow.com/comment/89489355
has text: You should never access files from Python web applications via relative paths, or rely on the current working directory being a specific directory, as the current working directory could be anything depending on server and environment, and could change. Always calculate the absolute path in some way, such as ``file = os.path.join(os.path.dirname(__file__), 'filename.txt')``. See: http://modwsgi.readthedocs.io/en/develop/user-guides/application-issues.html#application-working-directory
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51254381

http://stackoverflow.com/comment/89516961
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51257538
has text: My bad. I was wrong. Upon closer inspection, I see what you meant by it creating more copies under the newly created copies. This is caused by `shutil.copytree` copying the entire directory into the newly created copy.

http://stackoverflow.com/comment/89557704
comment on: http://stackoverflow.com/a/51289493
score: 0
type: AnswerComment
type: Comment
has text: Yes it works now must of copied it incorrectly. Okay see the way it only gets the Centre Threshold because it looks for the word Maximum then breaks? How can you also print the Corner results ans then break.

axes
tag name: axes
tags question: http://stackoverflow.com/q/51199433
type: Tag
tags question: http://stackoverflow.com/q/51212669

http://stackoverflow.com/a/51303980
has comment: http://stackoverflow.com/comment/89585051
has comment: http://stackoverflow.com/comment/89586721
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/89585017
accepted answer of: http://stackoverflow.com/q/51303361
type: Answer
answers question: http://stackoverflow.com/q/51303361
has comment: http://stackoverflow.com/comment/89585624
has comment: http://stackoverflow.com/comment/89585893
score: 9
upvote count: 9
has body: As @Fredrik suggested, you can use plt.imshow(gray, cmap='gray', vmin = 0, vmax = 255) to get you a grayscale output or you can also convert the Grayscale image to a 3 channel RGB image using gray = cv2.cvtColor(gray, cv2.COLOR_GRAY2RGB). Basically the problem is that gray = cv2.cvtColor(RGB_img, cv2.COLOR_RGB2GRAY) returns a single channel matrix, where as matplotlib is expecting a 3 channel RGB matrix to be shown, So you can either tell plt.imshow() that your input matrix is a single channel matrix using plt.imshow(gray, cmap='gray', vmin = 0, vmax = 255) or you can simply convert the single channel matrix to 3 channel matrix and then simply use plt.imshow(gray) and everything would work fine. For the second part of your question where res = np.hstack((img,equ)) is raising error, it is always helpful to debug the shape of matrices, you want to apply operation upon, You can do that by print img.shape, print equ.shape. As far as I can see your img is a 3-channel matrix (BGR), whereas your equ is a single channel matrix (gray), hence error, you would need to convert this equ matrix to a 3-channel matrix again using cv2.cvtColor(equ, cv2.COLOR_GRAY2RGB).

http://stackoverflow.com/comment/89414258
type: Comment
has text: I'll point out that the fourth from the last line reads `pring`, rather than `print`. These mistakes are harder to make in an editor that has syntax highlighting.
score: 0
comment on: http://stackoverflow.com/q/51216532
type: QuestionComment

http://stackoverflow.com/a/51224078
type: Answer
has body: Embedding layer expects the first argument to be size of vocabulary, i.e it is the maximum integer index + 1 But you are passing the number of features as vocabulary size. What you can do is, find the maximum number in flows_nd and pass the maximum number plus one to the Embedding layer. voc_size = flows_nd.max()+1 model = Sequential() model.add(Embedding(voc_size, 32))
accepted answer of: http://stackoverflow.com/q/51223936
answers question: http://stackoverflow.com/q/51223936
score: 16
upvote count: 16
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/51194867
accepted answer of: http://stackoverflow.com/q/51191502
has body: There is a (somehow mind twisting) technique to expand string lists to arrays by replacing the spaces (or any other char) between the list elements with a count and a set to form the array. From your lists and the for it is unclear if you want a 0 or 1 based index. (more easy would be a for /l %%A in (2,1,10) Do ...) For better understanding I used shorter variable names and echo the split'ed python command to several lines. :: Q:\Test\2018\07\05\SO_51191502.cmd @Echo off &amp; SetLocal EnableDelayedExpansion set i=0&amp;Set "ImgIn= 1 2 3 4 5 6 7 8 9 10" Set "ImgIn=%ImgIn: ="&amp;Set /a i+=1&amp;Set "ImgIn[!i!]=%" :: Set ImgIn set i=0&amp;Set "ImgOut= 2 3 4 5 6 7 8 9 10 11" Set "ImgOut=%ImgOut: ="&amp;Set /a i+=1&amp;Set "ImgOut[!i!]=%" :: Set ImgOut set i=0&amp;Set "ImgNext= 002 003 004 005 006 007 008 009 010 011" Set "ImgNext=%ImgNext: ="&amp;Set /a i+=1&amp;Set "ImgNext[!i!]=%" :: Set ImgNext For /L %%A IN (1,1,10) DO ( Echo python batchLayer4ThirdVideo.py ^ --input_image !ImgIn[%%A]! ^ --next_undreamed_image !ImgNext[%%A]! ^ --output_image !ImgOut[%%A]! ) Sample output: &gt; Q:\Test\2018\07\05\SO_51191502.cmd python batchLayer4ThirdVideo.py --input_image 1 --next_undreamed_image 002 --output_image 2 python batchLayer4ThirdVideo.py --input_image 2 --next_undreamed_image 003 --output_image 3 python batchLayer4ThirdVideo.py --input_image 3 --next_undreamed_image 004 --output_image 4 python batchLayer4ThirdVideo.py --input_image 4 --next_undreamed_image 005 --output_image 5 python batchLayer4ThirdVideo.py --input_image 5 --next_undreamed_image 006 --output_image 6 python batchLayer4ThirdVideo.py --input_image 6 --next_undreamed_image 007 --output_image 7 python batchLayer4ThirdVideo.py --input_image 7 --next_undreamed_image 008 --output_image 8 python batchLayer4ThirdVideo.py --input_image 8 --next_undreamed_image 009 --output_image 9 python batchLayer4ThirdVideo.py --input_image 9 --next_undreamed_image 010 --output_image 10 python batchLayer4ThirdVideo.py --input…
has comment: http://stackoverflow.com/comment/89389005
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51191502
type: Answer
upvote count: 2
score: 2
has comment: http://stackoverflow.com/comment/89383490

http://stackoverflow.com/comment/89485868
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51253411
has text: Still, better to first show how to make just the change to the OP's code that they asked for, and then explain why and how it could be improved, than to imply that rewriting everything is required in order to make the OP's change when it really isn't.

http://stackoverflow.com/a/51324466
type: Answer
answers question: http://stackoverflow.com/q/51234876
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51234876
score: 3
upvote count: 3
has body: The issue is in the CustomJS code as you suspected. There are two things that need to be fixed. Bokeh has deprecated get() and set() methods and replaced them by getv() or setv(). However, the preferred way of accessing or modifying model properties is through usual JavaScript attributes, e.g., source_visible.data. Bokeh has deprecated trigger('change') and replaced it by change.emit(). The fixed CustomJS code: slider.callback = CustomJS( args=dict(source_visible=source_visible, source_available=source_available), code=""" var selected_function = cb_obj.value.toString(); // Get the data from the data sources var data_visible = source_visible.data; var data_available = source_available.data; // Change bar height to the selected value data_visible.top = data_available[selected_function]; // Update the plot source_visible.change.emit(); """) JavaScript errors and warnings are seen in the browser's console. Here are instructions for opening the console in different browsers.
type: AcceptedAnswer

http://stackoverflow.com/a/68324072
has body: I used tor to connect and my problem was fixed. Download, install and run the tor browser. Install pysocks dependency. pip install pysocks And in the code: REQUEST_KWARGS = { 'proxy_url': 'socks5h://127.0.0.1:9150' }
type: Answer
score: 0
answers question: http://stackoverflow.com/q/51321151

http://stackoverflow.com/comment/89378173
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51198109
has text: @PauloScardine Also, the OP just removed the numpy tag, so he presumably wants an `itertools.product` answer (whether he knows that or not).

http://stackoverflow.com/q/51220389
linked to: http://stackoverflow.com/q/1342601
tagged with: string
tagged with: operators
favorite count: 0
upvote count: 0
has comment: http://stackoverflow.com/comment/89421709
has comment: http://stackoverflow.com/comment/89421661
downvote count: 5
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/130818429
answer count: 4
has body: So lets say I have this Sentence = "A surprise to be sure but a welcome one" keyword_list = ['surprise', 'welcome', 'one'] def or_maker(sentence): for i in range(len(keyword_list)): if keywordlist[i] in Sentence: return keywordlist[i] or keywordlist[i + 1] or keyword_list[i + 2] or ... etc. So hopefully when I call the function or_maker(Sentence) it returns to me 'surprise' or 'welcome' or 'one' Is this possible in Python?
tagged with: list
score: -5
has answer: http://stackoverflow.com/a/51221009
has comment: http://stackoverflow.com/comment/89421568
has comment: http://stackoverflow.com/comment/89421606
has answer: http://stackoverflow.com/a/51220430
duplicate of: http://stackoverflow.com/q/1342601
type: Question
has comment: http://stackoverflow.com/comment/89421678
tagged with: function
has title: Is it possible to return a string followed by an 'or' operator followed by another string until there are no more strings? Python 3.6
has answer: http://stackoverflow.com/a/51220977
has answer: http://stackoverflow.com/a/51220560
duplicate of: http://stackoverflow.com/q/2361426

http://stackoverflow.com/comment/89579038
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51298698
has text: Wait, are there lists inside `Source` column? Could you please provide a reproducible code snippet?
score: 0

http://stackoverflow.com/q/51296579
tagged with: python-3.x
type: Question
score: 3
linked to: http://stackoverflow.com/q/47814787
has title: When does python decide if a name is local or a reference to a global variable?
tagged with: python
has comment: http://stackoverflow.com/comment/89570560
tagged with: namespaces
downvote count: 1
duplicate of: http://stackoverflow.com/q/370357
has body: Consider the following code: def f(): y = x + 1 x = 1 f() This code runs fine. As I understand it, when the function is called, python searches for the name x first in the local scope, and since it doesn't find it, it searches the global scope, reads the value of x and execution of code continues from there. So far, so good. But the following piece of code throws an UnboundLocalError: local variable 'x' referenced before assignment: def g(): y = x + 1 x = y x = 1 g() So my guess is that python decided that x inside the g definition is a local variable. But when does this decision happen? I guess it doesn't happen during code execution (when g is called in the last line). Because then python would read the first line inside the definition of g and interpret it like it happens in f, as a reference to the global variable x. Then it would read the second line in the definition of g, and it would create a local variable x. That would mean that inside the definition of g, the same name x would mean global and local at different lines, which would be a nightmare! I'm wondering if the decision to bind x to the local namespace is taken while the def statement is parsed. What confuses me though is that the error is thrown only when the function is called (so during execution) and not after the def statement, when the function definition has been parsed.
type: UnansweredQuestion
upvote count: 4
linked to: http://stackoverflow.com/q/9264763
answer count: 0
favorite count: 0

http://stackoverflow.com/a/51248070
type: AcceptedAnswer
type: Answer
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/51247978
answers question: http://stackoverflow.com/q/51247978
has comment: http://stackoverflow.com/comment/89476217
has comment: http://stackoverflow.com/comment/89475334
has comment: http://stackoverflow.com/comment/89475527
has comment: http://stackoverflow.com/comment/89475282
has body: Create an aggregator function: f = dict.fromkeys(dataFrame, 'first') f.update({'runs': [np.sum,np.min,np.max,np.mean], 'strike_rate':'mean', 'player_id' : 'count' }) Now, pass f to player_data: player_data = dataFrame.groupby('player_id').aggregate(f) The idea here is to have everything you don't want lost aggregated as having the first value from the original group of values. In the case of "Name", every value is the same (AKA, the player name), so taking just the first value makes sense in theory. Another method, if it's just the Name column you want added in (and nothing else), you can build a mapping of player_ids to Names, and then manually add in your column of Names to the result. mapping = dict(zip(dataFrame.player_id, dataFrame.name)) ... player_data['name'] = player_data['player_id'].map(mapping)
has comment: http://stackoverflow.com/comment/89475572
upvote count: 1

http://stackoverflow.com/comment/89545670
has text: This is just printing all values of a list - what the OP is looking for is a way to loop over a dynamic number of elements - as far as I understand :)
type: Comment
comment on: http://stackoverflow.com/a/51284127
score: 0
type: AnswerComment

http://stackoverflow.com/comment/89489596
comment on: http://stackoverflow.com/q/51255230
has text: @abarnert Correct and in PHP, POSIX has been depreciated in later versions. So pretty much exactly like `re.split()`.
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/comment/89599678
comment on: http://stackoverflow.com/q/51311365
score: 0
type: QuestionComment
has text: @IzzyChong is your file located inside the `/static/` directory? like, `/static/vendor/animsition/animsition.min.js` ?
type: Comment

http://stackoverflow.com/comment/89358633
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51184408
has text: I am using on windows.

http://stackoverflow.com/q/51312059
has answer: http://stackoverflow.com/a/51326002
upvote count: 2
tagged with: pyinstaller
type: UnansweredQuestion
tagged with: can-bus
tagged with: python
score: 2
has answer: http://stackoverflow.com/a/64570617
has title: Kvaser's CAN library has been loaded, but program executable outputs a "No module named 'can.interfaces.kvaser'" error
type: Question
downvote count: 0
has answer: http://stackoverflow.com/a/67936441
answer count: 3
tagged with: exe
favorite count: 0
has body: I made a working application that successfully uses the python-can module to receive incoming messages on a kvaser CAN bus. When I used PyInstaller to convert this program to an executable file, the terminal logged that it "loaded kvaser's CAN library." The outputted .exe GUI runs as normal, yet the program suddenly doesn't receive any more CAN messages like it had beforehand. In the terminal, I printed the error it catches: "Cannot import module can.interfaces.kvaser for CAN interface 'kvaser': No module named 'can.interfaces.kvaser". Note that in the .spec file that I used to create the executable, I added "import can.interfaces.kvaser" at the top. I am not sure if the error I am getting is because I am not using pyinstaller correctly or if it is because I am somehow importing the CAN dependencies incorrectly, yet I suspect it is likely due to the latter. Is there a different way to import the python-can kvaser module that may solve this discrepancy between CAN functionality of the program before and after it was converted to an executable?

http://stackoverflow.com/comment/89561702
type: Comment
comment on: http://stackoverflow.com/q/51275627
has text: @crypdick I missed the cylinder part. However, you can always approximate a cylinder with a polyhedron (the same way you can approximate a circle with a regular polygon -- just use enough edges). Could you maybe post a screenshot of your `mplot3d` code to give us a better idea what you're after?
type: QuestionComment
score: 0

http://stackoverflow.com/comment/89368500
score: 3
type: Comment
type: QuestionComment
has text: I don't really know about Python, but in Matlab you need to create a meshgrid before plotting a surface. This gives you a grid wrt x and y (instead of vectors) to be plotted and that seems to be your problem.
comment on: http://stackoverflow.com/q/51193342

http://stackoverflow.com/comment/89569764
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51234900
has text: @Blckknght you can also refer to the image which I just mentioned in the post. ThankYou

http://stackoverflow.com/q/51253538
has comment: http://stackoverflow.com/comment/89491176
has title: Cloudflare Scrapy
has comment: http://stackoverflow.com/comment/89486196
favorite count: 0
has comment: http://stackoverflow.com/comment/90074034
type: Question
score: 3
has comment: http://stackoverflow.com/comment/90023177
has comment: http://stackoverflow.com/comment/89525704
tagged with: python
has comment: http://stackoverflow.com/comment/89525919
has comment: http://stackoverflow.com/comment/90037758
upvote count: 3
tagged with: web-scraping
tagged with: scrapy
answer count: 1
has comment: http://stackoverflow.com/comment/90029317
has body: I'm trying to scrape a URL using Scrapy with Cloudflare but I can't obtain any results: 2018-07-09 22:14:00 [scrapy.core.engine] INFO: Spider opened 2018-07-09 22:14:00 [scrapy.extensions.logstats] INFO: Crawled 0 pages (at 0 pages/min), scraped 0 items (at 0 items/min) 2018-07-09 22:14:00 [scrapy.extensions.httpcache] DEBUG: Using filesystem cache storage in C:\Users\Luis\Mister\.scrapy\httpcache 2018-07-09 22:14:00 [scrapy.extensions.telnet] DEBUG: Telnet console listening on 127.0.0.1:6023 2018-07-09 22:14:00 [scrapy.core.engine] DEBUG: Crawled (200) &lt;GET https://www.mister-auto.es/robots.txt&gt; (referer: None) ['cached'] 2018-07-09 22:14:00 [scrapy.core.engine] DEBUG: Crawled (200) &lt;GET https://www.mister-auto.es/global_search2.html? idx=prod_monoindex_ESes&amp;q=FEBI+BILSTEIN&gt; (referer: None) ['cached'] 2018-07-09 22:14:00 [scrapy.core.engine] INFO: Closing spider (finished) 2018-07-09 22:14:00 [scrapy.statscollectors] INFO: Dumping Scrapy stats: {'downloader/request_bytes': 633, 'downloader/request_count': 2, 'downloader/request_method_count/GET': 2, 'downloader/response_bytes': 20858, 'downloader/response_count': 2, 'downloader/response_status_count/200': 2, 'finish_reason': 'finished', 'finish_time': datetime.datetime(2018, 7, 9, 20, 14, 0, 833000), 'httpcache/hit': 2, 'log_count/DEBUG': 4, 'log_count/INFO': 7, 'response_received_count': 2, 'scheduler/dequeued': 1, 'scheduler/dequeued/memory': 1, 'scheduler/enqueued': 1, 'scheduler/enqueued/memory': 1, 'start_time': datetime.datetime(2018, 7, 9, 20, 14, 0, 594000)} 2018-07-09 22:14:00 [scrapy.core.engine] INFO: Spider closed (finished) As the website is protected by Cloudflare, I've installed this: https://github.com/clemfromspace/scrapy-cloudflare-middleware When I modified my settings.py, I obtained the next error: Traceback (most recent call last): File "C:\Users\Luis\Anaconda2\lib\site-packages\twisted\internet\defer.py", line 1386, in _inlineCallbacks result = g.send(result) File "C:\Users\Lui…
has comment: http://stackoverflow.com/comment/89610077
has answer: http://stackoverflow.com/a/55239935
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89584691
has comment: http://stackoverflow.com/comment/90033760
downvote count: 0

http://stackoverflow.com/a/51255085
type: Answer
answers question: http://stackoverflow.com/q/51255024
score: 1
upvote count: 1
downvote count: 0
has body: You can use pandas for that task. &gt;&gt;&gt; df = pd.read_csv('/path/to/file.csv') &gt;&gt;&gt; df.index = df.iloc[:, 0] &gt;&gt;&gt; df.to_dict('index') Not sure why you want to duplicate the value of the first column, but in case you don't the above simplifies to: &gt;&gt;&gt; pd.read_csv('/path/to/file.csv', index_col=0).to_dict('index')

http://stackoverflow.com/q/51323651
favorite count: 0
accepted answer: http://stackoverflow.com/a/51428746
tagged with: python
has comment: http://stackoverflow.com/comment/89828100
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51428746
score: 1
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/89828539
type: Question
downvote count: 0
tagged with: javascript
has body: I have a newbie question with receiving JSON data from Python working as a server. I need to tell you that the server is based on WebSockets and I'm sending JSON data from Python to JavaScript successfully but I can't find any source how to proceed with this data to parse this and show it in different divs like value of the first_name in the id="message-1" div, second_name in the message2 div etc. Could you help me figure this out? Here is the code and picture what my firefox return: Web page. I almost forgot to mention that I'm using localhost with xampp or ngrok to "host" my client-side. Also, there is a connection because I'm receiving logs on the website as well as in python console Thanks in advance :) Here is python code: import asyncio import websockets import json async def time(websocket, path): while True: d = {'first_name': 'Guido', 'second_name': 'Rossum', 'titles': ['BDFL', 'Developer'], } parsed = json.dumps(d) name = "Jeremy" # now = datetime.datetime.utcnow().isoformat() + 'Z' for i in range(1): await websocket.send(parsed) response = await websocket.recv() print(response) start_server = websockets.serve(time, '127.0.0.1', 4040) asyncio.get_event_loop().run_until_complete(start_server) asyncio.get_event_loop().run_forever() Here is HTML/JS code
has title: How to receive JSON data with Python (server with websockets) and JavaScript (client-side)
upvote count: 1
answer count: 1
tagged with: websocket

http://stackoverflow.com/comment/89504790
type: QuestionComment
has text: your expected result is wrong: you're assuming that `"İ".lower() == "i"` (regular "i")
comment on: http://stackoverflow.com/q/51263013
score: 0
type: Comment

http://stackoverflow.com/comment/89425072
has text: take a look at: https://stackoverflow.com/questions/18096748/pandas-dataframes-to-html-highlighting-table-rows
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51221865

http://stackoverflow.com/comment/89576559
comment on: http://stackoverflow.com/q/51299780
score: 0
type: Comment
has text: @seuling just updated my post
type: QuestionComment

http://stackoverflow.com/a/51286988
answers question: http://stackoverflow.com/q/51286922
has body: new_list = [ a if b == ' ' else b for a,b in zip( other_list, empty_list)] new_list += empty_list[len(other_list):]
downvote count: 0
score: 1
upvote count: 1
type: Answer

http://stackoverflow.com/comment/89524916
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51272909
has text: @HarvIpan for example, my overall dataset shows highest frequency of weddings in the summer. I was able to determine this through barcharts. What I'd like to do is approach the same question of when weddings are most frequent in seasonal terms. If you take two example rows, where one shows a non-wedding value in the spring, and the second row shows a wedding value in the summer, then you can begin to build correlations. Does that make sense?
score: 0

http://stackoverflow.com/a/51231006
type: Answer
score: 2
upvote count: 2
accepted answer of: http://stackoverflow.com/q/51197338
answers question: http://stackoverflow.com/q/51197338
has body: It looks like this is an instance of a known, but long-standing bug: https://bugs.python.org/issue21478
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/61354451
type: Answer
has body: If you're not using the multi-user environment, the solution is to disable the security feature that prevents the authentication token used to launch the browser from being visible (which can be hijacked by other users on the same computer). If you don't already have a jupyter notebook config file (usually ~/.jupyter/jupyter_notebook_config.py on linux): Create it: $ jupyter notebook --generate-config Open the autogenerated file in a text editor and find the line: #c.NotebookApp.use_redirect_file = True Uncomment that line if it's commented out Replace True with False If you already have the config file and it doesn't have this setting, simply add to it: c.NotebookApp.use_redirect_file = False After changing the config file, you need to restart the jupyter server. Note that you need jupyter-notebook >= 6.0.3 for this feature to work. Finally, remember after every jupyter server restart you must reload each notebook for this to work. Only restarting the kernel will not solve this issue (even though it misleadingly says that kernel has been restarted).
upvote count: 3
accepted answer of: http://stackoverflow.com/q/51204250
downvote count: 1
answers question: http://stackoverflow.com/q/51204250
score: 2
type: AcceptedAnswer

http://stackoverflow.com/q/51175336
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/89333812
upvote count: 0
score: -1
has answer: http://stackoverflow.com/a/51175385
has body: I tried to do this: ip_dict = dict() ip_list = ["10.0.0.1", "10.0.0.2"] ip_dict.dict.setdefault(i for i in ip_list, 0) And I get this exception: File "&lt;stdin&gt;", line 1 SyntaxError: Generator expression must be parenthesized if not sole argument Can I do that in one line, or I have to do it in two lines?
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89333568
accepted answer: http://stackoverflow.com/a/51175385
possible better answer: http://stackoverflow.com/a/51175395
has title: Insert to dict multiple keys from list with for loop in one line - dict.setdefault
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/51175395
downvote count: 1
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89333585
has comment: http://stackoverflow.com/comment/89333563

http://stackoverflow.com/q/51220394
upvote count: 1
has body: I try to send a base64 json form node.js server to python flask server and than return a same base64 code back to node.js server. Flask can successfully receive my json but when it response to node and node try to print out the response. I got a error message say: "Unexpected end of JSON input". I found the reason is node server can not receive the base64 completely. It just only receive a small portion. What is the problem? Is post request has a string limit? I tested when I change the base64 code to a short string. Node server can receive response normally. Anyone can help me? Thank you. This is my code: &lt;&lt;&lt; Node.js Server >>> var express = require('express'); var http = require('http'); var app = express(); app.get('/', (req, res) =&gt; res.send('Hello World!')); app.listen(10000, () =&gt; console.log('Running on http://localhost:10000')); postData = JSON.stringify({ 'code': &lt;base64 code or short string here&gt; }); var options = { hostname: 'localhost', port: 10001, path: '/test', method: 'POST', headers: { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(postData) } }; var req = http.request(options, (res) =&gt; { res.on('data', (chunk) =&gt; { var data = JSON.parse(chunk); console.log(data.message); }); res.on('end', () =&gt; { console.log('No more data in response.'); }); }); req.on('error', (e) =&gt; { console.error(`problem with request: ${e.message}`); }); req.write(postData); req.end(); &lt;&lt;&lt; Python Flask Server >>> from flask import Flask from flask import request from flask import jsonify app = Flask(__name__) @app.route('/test', methods=['POST']) def test(): request_data = request.get_json() print(request_data['code']) return jsonify( message = request_data['code'] ) app.run(host='localhost', port=10001)
answer count: 1
has title: http post a base64 json request between Node.js and Python Flask server but Node received an incomplete json
tagged with: http://stackoverflow.com/tag/json
tagged with: base64
accepted answer: http://stackoverflow.com/a/51220563
type: AnsweredQuestion
downvote count: 0
score: 1
tagged with: flask
favorite count: 0
type: Question
tagged with: python
tagged with: node.js
has answer: http://stackoverflow.com/a/51220563

http://stackoverflow.com/comment/89403020
has text: That's good information, I will look into that further...
comment on: http://stackoverflow.com/q/51210433
score: 0
type: Comment
type: QuestionComment

aiohttp
tags question: http://stackoverflow.com/q/51271477
tags question: http://stackoverflow.com/q/51219907
tag name: aiohttp
type: Tag
tags question: http://stackoverflow.com/q/51314530

http://stackoverflow.com/comment/89557600
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51289008
type: Comment
has text: Seems that my webapp is now deployed but there is an error in `heroku logs`. `app[web.1]: bash: gunicorn: command not found`

http://stackoverflow.com/comment/89852616
score: 0
type: Comment
has text: There is countless post and documentation about sleep and tkinter. Unless you are using threading and running sleep in a separate thread then sleep does in fact freeze the tkinter instance until sleep has completed.
comment on: http://stackoverflow.com/a/51299593
type: AnswerComment

http://stackoverflow.com/comment/89603989
type: QuestionComment
has text: Take a look [here](https://stackoverflow.com/questions/30669474/beyond-top-level-package-error-in-relative-import)
comment on: http://stackoverflow.com/q/51313593
score: 0
type: Comment

http://stackoverflow.com/a/51194323
score: 0
type: Answer
has body: Is this what you are looking for? file = open(“testfile.txt”, “r”) for line in file: if line[:1] != "@": print line or whatever
upvote count: 1
downvote count: 1
answers question: http://stackoverflow.com/q/51194106

http://stackoverflow.com/q/51209015
has answer: http://stackoverflow.com/a/51209559
has title: Docker build pytest :Failed to establish a new connection: [Errno 111] Connection refused
has comment: http://stackoverflow.com/comment/89463855
tagged with: docker
answer count: 2
accepted answer: http://stackoverflow.com/a/51242575
has comment: http://stackoverflow.com/comment/89426532
downvote count: 0
has comment: http://stackoverflow.com/comment/89422451
has comment: http://stackoverflow.com/comment/89423362
favorite count: 0
possible better answer: http://stackoverflow.com/a/51209559
has answer: http://stackoverflow.com/a/51242575
has comment: http://stackoverflow.com/comment/89422538
tagged with: django
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/89399705
has body: I am facing a serious issue while docker build. The pytest is not working but after build(remove the pytest part) the same pytest work from inside container Here is my docker file: FROM phusion/baseimage:0.9.22 RUN apt-get update &amp;&amp; apt-get install -y build-essential git libaio1 libffi-dev libjpeg-dev libssl-dev libxml2-dev python-wand libmagickwand-dev\ libxslt-dev libz-dev python3-pip python3-setuptools unzip ADD requirements.pip / RUN pip3 install -r /requirements.pip VOLUME ["/app"] WORKDIR /app ADD . . EXPOSE 8000 RUN python3 manage.py runserver 0.0.0.0:8000 &amp; RUN python3 -m pytest tests/test_demo.py Here is my test file: import requests def test_demo(): response = requests.get('http://0.0.0.0:8000/' + "demo") assert (response.status_code == 200) Please help.
type: AnsweredQuestion
tagged with: pytest
score: 1
has comment: http://stackoverflow.com/comment/89399847
has comment: http://stackoverflow.com/comment/89449981
type: Question

http://stackoverflow.com/comment/89374395
comment on: http://stackoverflow.com/q/51178632
has text: I did this but it didn't take out the error. But I according to this. https://stackoverflow.com/questions/51169401/cannot-push-django-app-to-heroku/51169459#51169459 The issue is now resolved. Thanks.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89400541
comment on: http://stackoverflow.com/a/51209253
type: Comment
has text: pictures are discouraged! Make it easier for everyone to use your data
score: 1
type: AnswerComment

http://stackoverflow.com/a/51287192
has comment: http://stackoverflow.com/comment/89552210
type: Answer
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/51276877
answers question: http://stackoverflow.com/q/51276877
has comment: http://stackoverflow.com/comment/89552843
upvote count: 1
type: AcceptedAnswer
has body: Quoting from the shuffle_batch_join TF documentation : The tensors_list argument is a list of tuples of tensors, or a list of dictionaries of tensors. Each element in the list is treated similarly to the tensors argument of tf.train.shuffle_batch(). Basically, shuffle_batch_join expects to: Receive a list of tensors Perform shuffle_batch on each member of the list Return a list of tensors with the same number and types as tensors_list[i]. Be aware that if you use shuffle_batch_join : len(tensors_list) threads will be started, with thread i enqueuing the tensors from tensors_list[i]. tensors_list[i1][j] must match tensors_list[i2][j] in type and shape, except in the first dimension if enqueue_many is true. Here is a link to the doc.

http://stackoverflow.com/q/51285848
has title: Proper Class and Property Structure
score: 2
has answer: http://stackoverflow.com/a/51286057
downvote count: 0
type: Question
type: AnsweredQuestion
has body: I understand how properties and classes work in Python with the clearest example of using properties I can think of is when setting a temperature to not let it go below absolute zero. I am now wondering it is a good idea to use a property if the method is actually going to be some transformation. Grabbing this example of properties from Wikipedia: class Pen(object): def __init__(self): self._color = 0 # "private" variable @property def color(self): return self._color @color.setter def color(self, color): self._color = color Let's say that color was important to class of Pen and makes sense to be there, but the actual value setter looks something more like this: @color.setter def color(self, rgb_hex): self._color = hex_handler.get_color(rgb_hex) I like that from the object perspective, you just have the color, but the implementation is a little obfuscated to someone unless they dig into it. So is that a good way to use properties or should it be something more like: def set_color_from_rgb_hex(self, rgb_hex): self._color = hex_handler.get_color(rgb_hex) Where it's clearer how color is actually derived.
favorite count: 0
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/51286057
upvote count: 2
has comment: http://stackoverflow.com/comment/89549359
tagged with: python
tagged with: properties
answer count: 1

http://stackoverflow.com/q/51267673
has answer: http://stackoverflow.com/a/51267793
upvote count: 2
answer count: 1
tagged with: keras
favorite count: 0
has body: I am unable to correctly connect my dense layer to my LSTM layers. My Y values range from 0-1 so sigmoid seems logical to me. I get the error: Error when checking target: expected dense_4 to have 2 dimensions, but got array with shape (993, 300, 1) To me it seems i have the input shape correct total DF is (350700 , 2413) which i reshape to a ( 1169 , 300 , 2413 ) // not including Y value. I just can't seem to figure out how to get the dense layer working and apply the sigmoid to my Y. With the train test split i have a y_train of (993, 300, 1) which is the main issue of my error but i can't seem to understand what i have done wrong. x_train is ( 933, 300, 2413) x_test = ( 176, 300 , 2413) y_test= (176, 300, 1) Here is the network i have set up. backend tensorflow (also used theano same issue) _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= lstm_21 (LSTM) (None, 300, 1000) 13656000 _________________________________________________________________ lstm_22 (LSTM) (None, 300, 500) 3002000 _________________________________________________________________ lstm_23 (LSTM) (None, 300, 250) 751000 _________________________________________________________________ lstm_24 (LSTM) (None, 300, 100) 140400 _________________________________________________________________ lstm_25 (LSTM) (None, 50) 30200 _________________________________________________________________ dense_4 (Dense) (None, 1) 51 ================================================================= Total params: 17,579,651 Trainable params: 17,579,651 Non-trainable params: 0 _________________________________________________________________ here is a my code. import numpy as np import pandas as pd from keras.models import Sequential from keras.layers.advanced_activations import LeakyReLU from keras.layers import Dense, Activation, LSTM, Flatten from keras import backend as K from sklearn.model_selection i…
tagged with: python
has title: Understanding connecting a Dense layer to LSTM
score: 2
type: AnsweredQuestion
downvote count: 0
tagged with: machine-learning
accepted answer: http://stackoverflow.com/a/51267793
type: Question

knn
tags question: http://stackoverflow.com/q/51229016
tag name: knn
type: Tag
tags question: http://stackoverflow.com/q/51216020

http://stackoverflow.com/comment/89518054
comment on: http://stackoverflow.com/a/51269940
type: AnswerComment
has text: If this answers your question, please accept it also.
score: 0
type: Comment

http://stackoverflow.com/q/51182962
tagged with: tweepy
has title: Getting the: " FileNotFoundError: [Errno 2] No such file or directory: 'posted.txt '" even though I do have such file
type: UnansweredQuestion
tagged with: python
has body: Hey guys so I am working on a twitter bot that takes posts from reddit and tweets them. My problem right now is when I run it I get the " FileNotFoundError: [Errno 2] No such file or directory: 'posted.txt '" error. But the thing is as you will see in the image below and through my code, 'posted.txt' does exist and it is in the same directory. So I am kind of stuck on what the actual problem is. I have a nearly identical program to this where the 'Already_Tweeted' function works but the only difference is that this one takes in image files as well (using BeautifulSoup). Could that be contributing to this error? This is not the complete project, only what is hopefully relevant import praw import tweepy import time import os from bs4 import BeautifulSoup as bs import requests posted_reddit_ids = 'posted.txt' def tweet_creator(subreddit_info): '''Goes through posts on reddit and extracts a shortened link, title &amp; ID''' post_links = [] #list to store our links post_titles = [] #list to store our titles post_ids = [] #list to store our id's post_imgs = [] print("[bot] extracting posts from sub-reddit") for submission in subreddit_info.new(limit=5): if not already_tweeted(submission.id): post_titles.append(submission.title) post_links.append(submission.shortlink) post_ids.append(submission.id) post_imgs = get_image(submission.url) print(post_imgs) else: print("Already Tweeted") return post_links, post_titles, post_ids, post_imgs def already_tweeted(id): '''reads through our .txt file and determines if tweet has already been posted''' found = 0 with open(posted_reddit_ids, 'r') as f: for line in f: if id in line: found = 1 break return found def main(): '''Main function''' # If the tweet tracking file does not already exist, create it if not os.path.exists(posted_reddit_ids): with open(posted_reddit_ids, 'w'): pass if not os.path.exists(img_dir): os.makedirs(img_dir) subreddit = setup_connection_reddit(subreddit_to_watch) post_links, post_titles, post_ids, post_imgs = …
type: Question
tagged with: function
answer count: 1
score: 0
has answer: http://stackoverflow.com/a/51183393
tagged with: praw

http://stackoverflow.com/comment/89547711
type: QuestionComment
type: Comment
has text: @JHBonarius will rename
score: 0
comment on: http://stackoverflow.com/q/51284945

http://stackoverflow.com/q/51229216
possible better answer: http://stackoverflow.com/a/51229257
favorite count: 0
has body: I want a DataFrame where the top rows of one column (called 'cat') have value "LOW", the mid and bottom parts of the frame will have values "MID" and "HI". So, for a frame of 1,200 rows, the value counts for the cat columns should result in: LOW 400 MID 400 HI 400 This should be easy. But, apparently it is not really. To no avail I tried to select and change the bottom rows using df.loc[-400:,["cat"]] = "HI" But, this approach does work for the top-rows: df.loc[:399,["cat"]] = "LOW" The sample below shows a working example, and note that it requires both loc and iloc. Is this where pandas can improve? import pandas as pd import numpy as np df = pd.DataFrame(np.random.random([1200, 4]), columns=['A', 'B', 'C', 'D']) df["cat"] = "MID" df.loc[:399,["cat"]] = "LOW" df.iloc[-400:,-1] = "HI" # The -1 selects the last column ('cat') - not ideal. df.cat.value_counts()
tagged with: python
score: 2
type: AnsweredQuestion
upvote count: 2
accepted answer: http://stackoverflow.com/a/51229245
type: Question
has comment: http://stackoverflow.com/comment/89438162
has answer: http://stackoverflow.com/a/51229257
answer count: 2
tagged with: pandas
has title: Why do loc and iloc work differently for slicing rows of a pandas DataFrame?
downvote count: 0
has answer: http://stackoverflow.com/a/51229245

http://stackoverflow.com/a/62512031
answers question: http://stackoverflow.com/q/51294534
score: 0
has body: I had the same problem, try to use a new browser and it will make the trick for you. Me - I had problem it Chrome, it worked after clear the cache, but the same doesn't happen with FireFox, over FireFox works like a charm. You can try others browsers as well just in case.
type: Answer

http://stackoverflow.com/q/51248442
has comment: http://stackoverflow.com/comment/90172266
upvote count: 2
type: UnansweredQuestion
has title: Behavior of the parameter 'throttle_secs' in tf.estimator.EvalSpec for use in tf.estimator.train_and_evaluate
tagged with: python
score: 2
answer count: 0
tagged with: tensorflow
type: Question
has body: I am using tensorflow's train_and_eval function as in the example. Therefore i create an instance of tf.estimator.EvalSpec, according to eval_spec = tf.estimator.EvalSpec(input_fn=...,throttle_secs=60). According to its documentation the explanation of the parameter throttle_secs states that "Of course, evaluation does not occur if no new checkpoints are available, hence, this is the minimum." However, i observe a different behavior. If there is no new checkpoint and evaluation should be triggered according to the passed parameter a new checkpoint is created and evaluation is performed. Is this a bug or am i missing something here?
downvote count: 0
favorite count: 0

http://stackoverflow.com/comment/132204905
has text: What if I want to distinguish between lambda/regular function and class with `__call__` method (which is also callable)? e.g. `inspect.isfunction`/`inspect.isclass` return values?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51225097
type: Comment

http://stackoverflow.com/q/51203198
tagged with: digits
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51203388
tagged with: matching
type: Question
tagged with: decimal
answer count: 2
has title: Need matching digits between two decimals
favorite count: 0
possible better answer: http://stackoverflow.com/a/51203388
score: 0
tagged with: python
has body: let's say I have 2 decimals(float). a = 123.62903 b = 123.6233 now I want the result to matching digits of this decimal. so result here should be 123.62. If, a =234.2387 b =232.2138 then, the result should be result = 23. It would be a great help thank you.
has comment: http://stackoverflow.com/comment/89388077
has answer: http://stackoverflow.com/a/51203305
accepted answer: http://stackoverflow.com/a/51203305
upvote count: 1
downvote count: 1

http://stackoverflow.com/comment/89389899
has text: No, I didn't do that.
comment on: http://stackoverflow.com/q/51204370
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51215176
type: AcceptedAnswer
has body: I think that you are totally on the right track. Looks like classic over-fitting. One option is adding dropout if you don't already have it. It falls into the category of regularization, but it is more commonly used now then L1 and L2 regularization. Changing the model architcture could get better results but it's hard to say what specifically would be best. It could help to make it deeper with more layers and possibly some pooling layers. It will likely still overfit but you might get a higher accuracy on the dev set before that happens. Getting more data may be one of the best things you could do. If you can't get more data you can try to augment the data. You can also try cleaning the data to remove noise which can help prevent the model from fitting to noise. You may ultimately want to try setting up a hyperparameter optimization search. This, however, can take a while on neural nets which take a while to train. Make sure you remove a test set before hyper parameter tuning.
downvote count: 0
score: 4
type: Answer
answers question: http://stackoverflow.com/q/51212755
accepted answer of: http://stackoverflow.com/q/51212755
upvote count: 4

http://stackoverflow.com/q/51204370
has body: Well this is a piece of my script: k = int(raw_input()) order = [] o = [] for i in range(1, k): o.append(raw_input()) order.append([int(n) for n in list(o[i])]) and I've been getting the following error after these input lines: 3 241356789 Traceback (most recent call last): File "[path]", line 11, in &lt;module&gt; order.append([int(n) for n in list(o[i])]) IndexError: list index out of range But I just cannot figure out why. Can anybody help me please? (I'm a beginner)
has comment: http://stackoverflow.com/comment/89389899
has answer: http://stackoverflow.com/a/51204689
tagged with: python-2.7
score: 0
has comment: http://stackoverflow.com/comment/89389905
tagged with: arrays
answer count: 5
accepted answer: http://stackoverflow.com/a/51204689
tagged with: input
tagged with: python
has title: Python2 - IndexError: creating an array of arrays
has answer: http://stackoverflow.com/a/51204483
possible better answer: http://stackoverflow.com/a/51204460
has answer: http://stackoverflow.com/a/51204506
type: AnsweredQuestion
tagged with: raw-input
has answer: http://stackoverflow.com/a/51204460
has answer: http://stackoverflow.com/a/51204462
type: Question

http://stackoverflow.com/comment/89605966
type: Comment
comment on: http://stackoverflow.com/a/51312676
score: 0
type: AnswerComment
has text: I would try removing (or fixing?) `cat.pxd`

http://stackoverflow.com/q/51180388
tagged with: python
tagged with: tkinter
tagged with: widget
type: UnansweredQuestion
has body: I tried to google it but couldn't find out. I am trying to create a CheckList widget with a tkinter.tix package in Python3.5 and set background color to white with this code: from tkinter import tix as tk checklist = tk.CheckList(parent, browsecmd=br, width=650) checklist.tk_setPalette(background="white") Unluckily all of the widgets on the screen got white background. I have tried checklist = tk.CheckList(parent, browsecmd=br, width=650, background="white") but it seems not to have any effect on the background of CheckList any ideas?
tagged with: background
type: Question
score: 0
has answer: http://stackoverflow.com/a/51208786
has answer: http://stackoverflow.com/a/59093935
answer count: 2
tagged with: tix
has title: How to change background color for a CheckList widget from tkinter.tix module?

http://stackoverflow.com/a/51211872
downvote count: 0
has body: If I understand your question correctly, you might want to pass an additional option to std::ofstream::open: myfile.open("file.txt", std::ios_base::app); This will append anything that your write to that file. From python, you can delete the file like this import os os.remove("file.txt") which will cause the compiled executable to append to a newly created file.
answers question: http://stackoverflow.com/q/51211758
upvote count: 2
type: Answer
score: 2

http://stackoverflow.com/q/51233161
has answer: http://stackoverflow.com/a/51233273
linked to: http://stackoverflow.com/q/50165120
has body: I have two on_messages events: The problem is that when both of them are in the same code only the one that is in lower position works. When I remove it the other one works and the opposite. both of them finish with await client.process_commands(message). @client.event async def on_message(message): contents = message.content.split(" ") #contents is a list type for word in contents: if word.upper() in chat_filter: if not message.author.id in bypass_list: await client.delete_message(message) await client.send_message(message.channel, "Hey! You are not allowed to use that word here!") await client.process_commands(message) @client.event async def on_message(message): if message.content.startswith('ping'): await client.send_message(message.channel, 'pong') await client.process_commands(message)
favorite count: 0
duplicate of: http://stackoverflow.com/q/50165120
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89445472
downvote count: 1
type: Question
tagged with: discord.py
upvote count: 0
answer count: 1
score: -1
has title: discord.py on_message event error

http://stackoverflow.com/q/51246828
has comment: http://stackoverflow.com/comment/89504060
has comment: http://stackoverflow.com/comment/89476578
has comment: http://stackoverflow.com/comment/89473486
has comment: http://stackoverflow.com/comment/89472472
favorite count: 0
has comment: http://stackoverflow.com/comment/89536127
has title: Python sending hexadecimal data, efficient storage
type: Question
has comment: http://stackoverflow.com/comment/89474272
tagged with: python
score: 4
has comment: http://stackoverflow.com/comment/89474260
answer count: 1
downvote count: 1
has body: I'm currently working on a project that involves some very remote data gathering. At the end of each day, a very short summary is sent back to the server via a satellite connection. Because sending data over the satellite is very expensive, I want the data to be as compact as possible. Additionally, the service I'm using only allows for sending data in the following two formats: ASCII, hexadecimal. Most of the data I will be sending consists of floats, where the precision should be as high as possible without taking up too much space. Below I have a working version of what I'm currently using, but there should be a more efficient way to store the data. Any help would be much appreciated. import ctypes #------------------------------------------------------------------ #This part is known to the client as well as the server class my_struct(ctypes.Structure): _pack_ = 1 _fields_ = [('someText', ctypes.c_char * 12), ('underRange', ctypes.c_float), ('overRange', ctypes.c_float), ('TXPDO', ctypes.c_float)] def print_struct(filled_struct): d = filled_struct for name,typ in d._fields_: value = getattr(d, name) print('{:20} {:20} {}'.format(name, str(value), str(typ))) #------------------------------------------------------------------ # This part of the code is performed on the client side #Filling the struct with some random data, real data will come from sensors s = my_struct() s.someText = 'Hello World!'.encode() s.underRange = 4.01234 s.overRange = 4.012345 s.TXPDO = 1.23456789 #Rounding errors occurred when converting to ctypes.c_float print('Data sent:') print_struct(s) data = bytes(s) #Total length is 24 bytes (12 for the string + 3x4 for the floats) data_hex = data.hex() #Total length is 48 bytes in hexadecimal format #Now the data is sent over a satellite connection, it should be as small as possible print('\nLength of sent data: ',len(data_hex),'bytes\n') #------------------------------------------------------------------ # This part of the code is performed on t…
has comment: http://stackoverflow.com/comment/89474421
has comment: http://stackoverflow.com/comment/89476360
linked to: http://stackoverflow.com/q/26753147
has answer: http://stackoverflow.com/a/51247385
upvote count: 5
has comment: http://stackoverflow.com/comment/89472604
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89474685

http://stackoverflow.com/comment/89507274
has text: `user.save(using=self._db, commit=commit)` unknown arguement commit.
type: Comment
comment on: http://stackoverflow.com/a/51262599
score: 0
type: AnswerComment

http://stackoverflow.com/comment/89595535
type: Comment
score: 1
comment on: http://stackoverflow.com/q/51288330
type: QuestionComment
has text: Not sure if I'm understanding you. Basically, the observed behavior is that the weights in your last layers will change, but as your backpropagate towards the first layers, the weights will change less and less, so therefore, by the time you get to your first layer, the gradient is so small that the weights won't change. I'm not too sure how many layers you created, but this problem happens for very deep layers. Also, if you used ReLU as your activation, then I doubt vanishing gradient is the problem.

http://stackoverflow.com/a/51326244
has comment: http://stackoverflow.com/comment/89631966
has comment: http://stackoverflow.com/comment/89628930
score: 1
has comment: http://stackoverflow.com/comment/89630956
has comment: http://stackoverflow.com/comment/89634818
has comment: http://stackoverflow.com/comment/89631815
upvote count: 1
has comment: http://stackoverflow.com/comment/89631204
has comment: http://stackoverflow.com/comment/89629819
has body: The data set you have looks more like Rexthor, the dog-bearer than something that a smooth curve can follow. You don't have an issue with SciPy; you have an issue with data. By increasing the parameter s you can get progressively smoother plots that deviate further and further from the data, eventually approaching the cubic polynomial that is the "best" least-squares fit for the data. But here "best" means "very bad, probably worthless". A smooth curve can be useful to display a pattern that the data already follows. If the data does not follow a smooth pattern, one should not draw a curve for the sake of drawing. The data points on the first plot should just be presented as is, without any connecting or approximating curves. The data comes from hourly reading taken from 9:00 to 16:00 (with one stray 17:00 value mixed it - throw it out.) This structure matters. Do not pretend that Tuesday 9:00 is what happens one hour after Monday 16:00. The data can be meaningfully summarized by daily totals Day Total 2018-04-02 289841 2018-04-03 256293 2018-04-04 401004 2018-04-05 419054 2018-04-06 375993 2018-04-09 266233 2018-04-10 278118 2018-04-11 151390 2018-04-12 318497 2018-04-13 310578 and by hourly averages (average number of events at 9:00, across all days, etc). Hour Average 9:00:00 16698.6 10:00:00 39705.2 11:00:00 47451.9 12:00:00 21758.8 13:00:00 20941.5 14:00:00 29086.1 15:00:00 65627 16:00:00 65411 In these things we can maybe observe some pattern. Here is the hourly one: hourly_averages = np.array([16698.6, 39705.2, 47451.9, 21758.8, 20941.5, 29086.1, 65627, 65411]) hours = np.arange(9, 17) hourly_s = 0.1*np.diff(hourly_averages).max()**2 hourly_spline = interp.UnivariateSpline(hours, hourly_averages, s=hourly_s) xx = np.linspace(min(hours), max(hours), 1000) # 1000 is an arbitrary number here. plt.plot(hours, hourly_averages, 'bo') plt.plot(xx, hourly_spline(xx), 'r') plt.show() The curve shows the lunch break and the end-of-day rush. My choice of s as 0.1*np.dif…
has comment: http://stackoverflow.com/comment/89630478
has comment: http://stackoverflow.com/comment/89629142
answers question: http://stackoverflow.com/q/51315721
has comment: http://stackoverflow.com/comment/89630772
downvote count: 0
has comment: http://stackoverflow.com/comment/89631964
has comment: http://stackoverflow.com/comment/89632382
type: Answer

http://stackoverflow.com/q/51245821
has answer: http://stackoverflow.com/a/51260803
type: Question
tagged with: robotframework
has body: When I tried to convert XML to HTML format in allure report, it throws an exception. Does anyone face this issue? How to resolve this exception. Also, the HTML report generates blank results. enter image description here
has title: Allure Report generate NaN report in robot frameowork
has comment: http://stackoverflow.com/comment/89470200
downvote count: 3
answer count: 1
tagged with: allure
favorite count: 0
type: UnansweredQuestion
score: -3
tagged with: python
has comment: http://stackoverflow.com/comment/89473386
upvote count: 0

http://stackoverflow.com/a/51247932
accepted answer of: http://stackoverflow.com/q/51242735
score: 1
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51242735
type: Answer
has body: Basic Configuration STATIC_URL = '/static/' BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_ROOT = os.path.join(BASE_DIR, 'static') In your server try to access http://localhost:8000/static/img/logo2.png and check if the image is propely loaded, if the image loads so your confugiration at settings.py is right. EDIT: You using heroku? im not sure if you will e able to use your static files with django at heroku, probabily use some external static server as Amazon S3
upvote count: 1

http://stackoverflow.com/comment/89610010
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51316881
score: 4
has text: Yes! Simply delete the instances of `.date()`. You _had_ full-blown `datetime.datetime` objects before you went out of your way to damage them ;-)

http://stackoverflow.com/comment/129133218
comment on: http://stackoverflow.com/q/51296268
type: Comment
type: QuestionComment
has text: I've never tried it with Jupyter, @Jens_Wagemaker, but it's definitely worth looking at. Thanks.
score: 0

http://stackoverflow.com/q/51237093
has answer: http://stackoverflow.com/a/51237247
upvote count: 0
has answer: http://stackoverflow.com/a/51237266
has comment: http://stackoverflow.com/comment/89453268
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51237314
score: -3
tagged with: python
has title: What is the most efficient method for reiterating a string backwards with a "while" loop?
answer count: 4
has comment: http://stackoverflow.com/comment/89453219
has answer: http://stackoverflow.com/a/51237275
downvote count: 3
has comment: http://stackoverflow.com/comment/89453162
has body: I know there must be a better method with less lines of code, how would you go about reversing the numbers in "some_numbers?" some_numbers =[1,2,3,4,5,6,7,8,9,11,22,33,44,55,66,77] new_string = [] print('some_numbers string: ',some_numbers) print('new_string string: ',new_string) #pop the last variable and insert into 'new_string' new_string.insert(-1,some_numbers[-1]) #begin loop while some_numbers: #insert the pops from some_numbers into new string in a reverse order new_string.insert(-1,some_numbers.pop()) #delete redundant number at the end of list del new_string[-1] print("some_numbers string: ",some_numbers) print("reversed string: ",new_string)
type: Question

http://stackoverflow.com/q/51285041
has comment: http://stackoverflow.com/comment/89547251
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89548509
tagged with: list
upvote count: 2
score: 0
downvote count: 2
type: Question
tagged with: format
has answer: http://stackoverflow.com/a/51285084
linked to: http://stackoverflow.com/q/275018
has title: Formatting a Python list
duplicate of: http://stackoverflow.com/q/275018
has body: Hello I am currently scraping information from online and putting it into a list however the elements are appearing as : ['\n Michael\n ', '\n Elad\n ', '\n Yair\n ', '\n Liron\n ', '\n Idan\n ', '\n Tomer\n ', '\n Ofer\n ', '\n Asaf\n ', '\n Tomer\n ', '\n Ronit\n ', '\n Guy\n ', '\n Lior\n '] Is there a way to format the list to erase the line indentations and the white space? Thank you
answer count: 1
favorite count: 0

http://stackoverflow.com/comment/89452762
score: 0
type: Comment
type: QuestionComment
has text: Also, In addition to the full traceback, could you please post the output of `data.dtypes`
comment on: http://stackoverflow.com/q/51236715

http://stackoverflow.com/q/51273969
favorite count: 0
has comment: http://stackoverflow.com/comment/89527075
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89526355
tagged with: pip
tagged with: python
has comment: http://stackoverflow.com/comment/89526244
downvote count: 0
has comment: http://stackoverflow.com/comment/89526954
score: 1
tagged with: setuptools
has body: I've been trying to follow this guide: https://www.youtube.com/watch?v=x9lKLGTfQFU and I've come to a problem running the line pip install -r requirements.txt within the virtual environment, this is what happens: (venv) C:\Users\George\Desktop\Kodi&gt; pip install -r requirements.txt Collecting gunicorn (from -r requirements.txt (line 1)) Using cached https://files.pythonhosted.org/packages/8c/da/b8dd8deb741bff556db53902d4706774c8e1e67265f69528c14c003644e6/gunicorn-19.9.0-py2.py3-none-any.whl Collecting pytz (from -r requirements.txt (line 2)) Using cached https://files.pythonhosted.org/packages/30/4e/27c34b62430286c6d59177a0842ed90dc789ce5d1ed740887653b898779a/pytz-2018.5-py2.py3-none-any.whl Collecting flask-ask&gt;=0.9.8 (from -r requirements.txt (line 3)) Using cached https://files.pythonhosted.org/packages/6a/f5/d4709ae94584a0b1541e9b52b2d25a8a1bdb6e2da9d6870f23fdd0523a30/Flask-Ask-0.9.8.tar.gz 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\george\appdata\local\temp\pip-install-b3jnkl\flask-ask\setup.py", line 8, in &lt;module&gt; from pip.req import parse_requirements ImportError: No module named req ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in c:\users\george\appdata\local\temp\pip-install-b3jnkl\flask-ask\ I've looked online, upgraded setuptools and ez install but to no avail
type: Question
has comment: http://stackoverflow.com/comment/89526856
has title: Virtutalenv Command "python setup.py egg_info" failed with error code 1
has comment: http://stackoverflow.com/comment/89527135
has comment: http://stackoverflow.com/comment/91407467
upvote count: 1

http://stackoverflow.com/q/51202594
tagged with: multithreading
tagged with: python
has body: I have a question about using dask to parallelize my code. I have a pandas dataframe and 8 cores CPU. So I want apply some function row-wise. Here is example: import dask.dataframe as dd from dask.multiprocessing import get # o - is pandas DataFrame o['dist_center_from'] = dd.from_pandas(o, npartitions=8).map_partitions(lambda df: df.apply(lambda x: vincenty((x.fromlatitude, x.fromlongitude), center).km, axis=1)).compute(get=get) That code run 8 CPU's simultaneously. Now, I have a problem that each process eats much memory, like the main process. So, I want to run it multi-threaded with shared memory. I tried, to change from dask.multiprocessing import get to from dask.threaded import get. But it doesn't use all of my CPUs, and I think it runs on single core.
has comment: http://stackoverflow.com/comment/89402644
type: AnsweredQuestion
type: Question
has title: Switching from multiprocess to multithreaded Dask.DataFrame
has comment: http://stackoverflow.com/comment/89389832
has answer: http://stackoverflow.com/a/51222961
tagged with: dataframe
score: 4
upvote count: 4
tagged with: pandas
answer count: 1
downvote count: 0
favorite count: 0
tagged with: dask
accepted answer: http://stackoverflow.com/a/51222961

http://stackoverflow.com/q/51219374
tagged with: tensorflow
type: Question
has answer: http://stackoverflow.com/a/51390509
accepted answer: http://stackoverflow.com/a/51390509
score: 0
tagged with: deep-learning
tagged with: distributed
answer count: 1
has title: Tensorflow distributed: CreateSession still waiting for response from worker: /job:ps/replica:0/task:0
has body: I'm trying to run my first example of distributed training with TF. I've used the example that is in TF documentation https://www.tensorflow.org/deploy/distributed with one ps and one worker each on a different cluster. However, I'm always getting CreateSession still waiting for response from worker: /job:ps/replica:0/task:0 on the worker cluster as shown below! trainer.py import argparse import sys import tensorflow as tf FLAGS = None def main(_): ps_hosts = FLAGS.ps_hosts.split(",") worker_hosts = FLAGS.worker_hosts.split(",") # Create a cluster from the parameter server and worker hosts. cluster = tf.train.ClusterSpec({"ps": ps_hosts, "worker": worker_hosts}) # Create and start a server for the local task. server = tf.train.Server(cluster, job_name=FLAGS.job_name, task_index=FLAGS.task_index) if FLAGS.job_name == "ps": server.join() elif FLAGS.job_name == "worker": # Assigns ops to the local worker by default. with tf.device(tf.train.replica_device_setter( worker_device="/job:worker/task:%d" % FLAGS.task_index, cluster=cluster)): # input images with tf.name_scope('input'): # None -> batch size can be any size, 784 -> flattened mnist image x = tf.placeholder(tf.float32, shape=[None, 784], name="x-input") # target 10 output classes y_ = tf.placeholder(tf.float32, shape=[None, 10], name="y-input") # model parameters will change during training so we use tf.Variable tf.set_random_seed(1) with tf.name_scope("weights"): W1 = tf.Variable(tf.random_normal([784, 100])) W2 = tf.Variable(tf.random_normal([100, 10])) # bias with tf.name_scope("biases"): b1 = tf.Variable(tf.zeros([100])) b2 = tf.Variable(tf.zeros([10])) # implement model with tf.name_scope("softmax"): # y is our prediction z2 = tf.add(tf.matmul(x,W1),b1) a2 = tf.nn.sigmoid(z2) z3 = tf.add(tf.matmul(a2,W2),b2) y = tf.nn.softmax(z3) # specify cost function with tf.name_scope('cross_entropy'): # this is our cost loss = tf.reduce_mean( -tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1])) global_step = tf.contri…
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/q/51281523
tagged with: django
upvote count: 1
tagged with: python
type: AnsweredQuestion
has body: I can't figure out how to change attribute for multiple columns in one for loop. I want to set orderable=False to multiple columns. The only way which works is to explicitely define all these columns so I can add orderable=False to constructor. class PizzaTable(tables.Table): class Meta: template_name = 'django_tables2/bootstrap-responsive.html' model = Pizza fields = ['created', 'ham', 'olives', 'corn', 'price',] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) unorderable_columns = ['ham', 'olives', 'corn',] for column in unorderable_columns: self.columns[column].orderable = False This raises: can't set attribute It has to be able to do it somehow, otherwise I would have to specify all of those columns: ham = tables.Column(accessor='ham',orderable=False) Do you have any ideas?
score: 1
accepted answer: http://stackoverflow.com/a/51282207
type: Question
has comment: http://stackoverflow.com/comment/89541559
has answer: http://stackoverflow.com/a/51282207
has title: Django-tables2: Change attribute for multiple columns in __init__()
downvote count: 0
answer count: 1
tagged with: django-tables2
favorite count: 0
tagged with: python-3.x
tagged with: constructor

http://stackoverflow.com/comment/89356590
score: 0
has text: still did not manage to do that :( please see the update
comment on: http://stackoverflow.com/q/51169843
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51250600
tagged with: python
has comment: http://stackoverflow.com/comment/89480377
has comment: http://stackoverflow.com/comment/89480451
has title: TypeError: include and exclude must both be non-string sequences
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51250826
has comment: http://stackoverflow.com/comment/89480100
has comment: http://stackoverflow.com/comment/89480474
type: AnsweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/89480262
type: Question
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/89480154
tagged with: pandas
accepted answer: http://stackoverflow.com/a/51250826
upvote count: 1
has comment: http://stackoverflow.com/comment/89480402
has body: I have data with a variety of dtypes: Restaurant ID int64 Restaurant Name object Country Code int64 ... Rating text object Votes int64 dtype: object When I run the code below: too_verbose_columns = (data.select_dtypes(include = 'O')\ .columns[data.select_dtypes(include='O').nunique() &gt; 2]\ .tolist()) I get this error: TypeError: include and exclude must both be non-string sequences. How can I resolve this error?

distributed
tags question: http://stackoverflow.com/q/51219374
type: Tag
tag name: distributed

http://stackoverflow.com/comment/89436845
has text: Looks sorted to me...
comment on: http://stackoverflow.com/q/51228473
score: 4
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89351578
score: 1
comment on: http://stackoverflow.com/q/51184734
type: Comment
type: QuestionComment
has text: You want a dictionary of lists, where book names are the keys and lists of tuples `(score,count)` are the values. A dictionary of `Counter`s may be an even better choice.

http://stackoverflow.com/a/51269078
accepted answer of: http://stackoverflow.com/q/51268715
has body: y_train[i]**2 - pred**2 is not the distance between actual and expected. (Is y_train always larger than pred? Why might this distance metric be lowest for the outliers you pointed out?) Try(y_train[i] - pred)**2 to get the actual distance.
has comment: http://stackoverflow.com/comment/89516688
score: 3
answers question: http://stackoverflow.com/q/51268715
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 3

http://stackoverflow.com/q/51196028
has comment: http://stackoverflow.com/comment/89374005
has comment: http://stackoverflow.com/comment/89374351
favorite count: 0
tagged with: linux
has comment: http://stackoverflow.com/comment/89374121
tagged with: python
has title: How to split qr codes in separate images?
has answer: http://stackoverflow.com/a/51196275
linked to: http://stackoverflow.com/q/51195584
has comment: http://stackoverflow.com/comment/89374253
downvote count: 2
upvote count: 1
type: Question
has body: I have hundreds of pictures with qr codes (sometimes there are 0, 1, 2 or more qr codes on one page...but they are always in one line). I want to decode the qr codes from left to right. My idea is to split the qr codes in separate images. Does somebody know a Linux (or Python) solution for this problem? The order I want is: url1, url2, url3, url4, url5, url6.
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51196275
tagged with: qr-code
score: -1
tagged with: image
has comment: http://stackoverflow.com/comment/89373895
answer count: 1

http://stackoverflow.com/q/51236149
downvote count: 0
tagged with: windows-10
duplicate of: http://stackoverflow.com/q/4906977
has comment: http://stackoverflow.com/comment/89451466
favorite count: 0
has title: accessing certain system-name folders (%appdata%) in Windows with Python
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89451455
tagged with: python
score: 2
has comment: http://stackoverflow.com/comment/89485888
answer count: 0
duplicate of: http://stackoverflow.com/q/5258647
has comment: http://stackoverflow.com/comment/89457460
has comment: http://stackoverflow.com/comment/89457404
type: Question
duplicate of: http://stackoverflow.com/q/11278738
has body: I'm a noob to this site, found lots of answers to other coding challenges in the past. I'm also a noob to programming in Python. I have some code I wrote in DOS few years ago. Let me explain why:- when you are using Windows 10 it keeps a log of "files used recently" this can be a big problem when I did a Windows 10 rollout at a big charity, and our HR team needed to borrow a laptop for a meeting, and when I got it back, logging on with the generic log on which was shared, a file was deleted but in frequently used files was something along the lines of "internal investigation into Mr _____.docx" which sounded very confidential. Anyways, this script I wrote, doesn't disable Windows 10 recently used files, it makes a copy of these files and throws them in a 7zip file. When its finished, it deletes the frequently used list of files, and re-opens with 7zip and puts the files back where they were, so no one knows something sensitive has been used in the meantime. I did this using part of this script in DOS calling 7zip from command line. rem *** get rid of the current shortcut list of recently used files *** del /F /Q %APPDATA%\Microsoft\Windows\Recent\AutomaticDestinations\* rem *** put back the previously copied set of shortcuts *** x:\apps\7-zip\7z.exe x x:\internals\scripts\win10recent.7z -o%APPDATA%\Microsoft\Windows\Recent -y I'm now trying to rewrite this in Python. I'm entirely new to Python, (I'm not an actual programmer by trade) but learned a lot from Googling around to make some portions of the code work so far functional. Just opening 7zip from within Python I have to do this:- subprocess.call(['x:\\apps\\7-zip\\7z.exe']) Here's the bit I am stuck. To call certain generic paths with the % symbols around it, example for %appdata%. I've searched around but I am not sure how I can call this path within Python? any ideas?
has comment: http://stackoverflow.com/comment/89451399
duplicate of: http://stackoverflow.com/q/44916777
linked to: http://stackoverflow.com/q/4906977
has comment: http://stackoverflow.com/comment/89451288
tagged with: environment-variables
has comment: http://stackoverflow.com/comment/89451437

http://stackoverflow.com/a/51309927
upvote count: 1
type: Answer
has body: The algorithm boils down what number you are using to double the items in the list (1 or 2). Here is my take on this problem: lis = [4, 8, 2, 4, 6] def double_with_my_condition(l, doubler=2): for i in l: yield i * doubler if i == 2: doubler = 1 continue doubler = 2 new_lis = [*double_with_my_condition(lis)] print(new_lis) Outputs: [8, 16, 4, 4, 12]
answers question: http://stackoverflow.com/q/51309762
downvote count: 0
score: 1

http://stackoverflow.com/q/51266761
has comment: http://stackoverflow.com/comment/89514505
has comment: http://stackoverflow.com/comment/89511735
has title: Python Subprocess efficiently check if child process terminated
type: UnansweredQuestion
has body: I am running this bash cmd using subprocess to start jmeter in a remote system. ['java', '-server', '-XX:+HeapDumpOnOutOfMemoryError', '-Xms512m', '-Xmx512m', '-XX:+UseG1GC', '-XX:MaxGCPauseMillis=250', '-XX:G1ReservePercent=20', '-Djava.security.egd=file:/dev/urandom', '-Xms1024m', '-Xmx1024m', '-jar', '/jmeter/apache-jmeter-4.0/bin/ApacheJMeter.jar', '-n', '-t', '/code/jmx_file.jmx', '-JReplica_ID=1', '-JService_Name=execution-b063818a', '-l', '/code/logs/logs.log'] Now I am using while loop to check the child processes are terminated are not and if terminated flush log files like below sub_proc = subprocess.Popen( bash_cmd, stdout=proc_log, stderr=proc_log ) # while the process is still running, dump the data to the file. while sub_proc.poll() is None: proc_log.flush() os.fsync(proc_log) sub_proc.wait() But this while loop is shooting my process to 100% CPU utilization . I want to know if there is any other way to efficiently check if child process terminated or not like above to reduce the CPU usage.
has comment: http://stackoverflow.com/comment/89512310
has answer: http://stackoverflow.com/a/51267033
tagged with: python
tagged with: subprocess
type: Question
score: 0
answer count: 1

http://stackoverflow.com/a/51319372
answers question: http://stackoverflow.com/q/51318855
has comment: http://stackoverflow.com/comment/89614958
upvote count: 3
score: 3
has comment: http://stackoverflow.com/comment/89615142
has comment: http://stackoverflow.com/comment/89615669
has comment: http://stackoverflow.com/comment/139536137
has comment: http://stackoverflow.com/comment/89616779
downvote count: 0
type: Answer
has body: This is a common construct in most object-oriented languages that support inheritance. When a child class (in your case int) inherits from a parent (in your case object), it is said to have an "is-a" relationship. That is, an int is a (or an) object. This "is-a" relationship is what isinstance is checking. From the docs: Return true if the object argument is an instance of the classinfo argument, or of a (direct, indirect or virtual) subclass thereof. There is a similar issubclass function to check the same relationship for a class instead of an instance of that class. In fact, in most cases, isinstance(x, y) == issubclass(type(x), y). type returns the exact class that an object was constructed from. That means that checking type(3) == object is exactly equivalent to checking int == object. Hopefully you can see that that's unambiguously false. On a related tangent, classes should always be the same reference within a given run of the interpreter, so you can use is instead of == for comparison. So type(3) is int will be true. That's how == is implemented for all the types you're ever likely to come across anyway.

http://stackoverflow.com/q/51218488
tagged with: statistics
tagged with: pandas
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/96288931
score: 6
accepted answer: http://stackoverflow.com/a/51218659
has title: Pandas how to place an array in a single dataframe cell?
possible better answer: http://stackoverflow.com/a/57160228
tagged with: python
upvote count: 6
has answer: http://stackoverflow.com/a/57160228
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89418198
has body: So I currently have a dataframe that looks like: And I want to add a completely new column called "Predictors" with only one cell that contains an array. So [0, 'Predictors'] should contain an array and everything below that cell in the same column should be empty. Here's my attempt, I tried to create a separate dataframe that just contained the "Predictors" column, and tried appending it to the current dataframe, but I get: 'Length mismatch: Expected axis has 3 elements, new values have 4 elements.' How do I append a single cell containing an array to my dataframe? # create a list and dataframe to hold the names of predictors dataframe=dataframe.drop(['price','Date'],axis=1) predictorsList = dataframe.columns.get_values().tolist() predictorsList = np.array(predictorsList, dtype=object) # Combine actual and forecasted lists to one dataframe combinedResults = pd.DataFrame({'Actual': actual, 'Forecasted': forecasted}) predictorsDF = pd.DataFrame({'Predictors': [predictorsList]}) # Add Predictors to dataframe #combinedResults.at[0, 'Predictors'] = predictorsList pd.concat([combinedResults,predictorsDF], ignore_index=True, axis=1)
type: Question
answer count: 2
tagged with: dataframe
has answer: http://stackoverflow.com/a/51218659
tagged with: data-science

http://stackoverflow.com/q/51219790
type: Question
upvote count: 2
tagged with: pandas
accepted answer: http://stackoverflow.com/a/51219853
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/51219853
tagged with: python
has title: Reading a date in a pandas dataFrame column as base day to generate hourly data
score: 2
downvote count: 0
has body: I have a column of data in a pandas dataFrame like: Date: 1960-01-01 1960-01-02 1960-01-03 I need to read the first value as base day like (Date[0] which is 1960-01-01) to use in the function below: Base = Date[0] arr = numpy.array( [base + datetime.timedelta(hours=i) for i in range(len(daily)] ) error: ufunc add cannot use operands with types dtype('&lt;M8[ns]') and dtype('O')
has comment: http://stackoverflow.com/comment/89420542
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89420575

http://stackoverflow.com/q/51244194
upvote count: 1
has answer: http://stackoverflow.com/a/51245318
has answer: http://stackoverflow.com/a/51244266
has answer: http://stackoverflow.com/a/51246811
favorite count: 0
answer count: 3
has comment: http://stackoverflow.com/comment/89466809
tagged with: python
type: AnsweredQuestion
downvote count: 0
possible better answer: http://stackoverflow.com/a/51245318
tagged with: django
type: Question
has body: SO in using paypalrestsdk i have gone to paypal, submitted an order and the redirect url is: http://localhost:8000/confirm_order?paymentId=XYZ&amp;token=123&amp;PayerID=ABC How do i dynamically obtain these values from the url??
score: 1
tagged with: paypal-rest-sdk
accepted answer: http://stackoverflow.com/a/51244266
has title: How to get variables from a url

http://stackoverflow.com/a/51375105
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51239301
has comment: http://stackoverflow.com/comment/89723150
answers question: http://stackoverflow.com/q/51239301
type: Answer
upvote count: 4
downvote count: 0
score: 4
has body: Forget about matplotlib... Have a look at plotly, this will make you reach your goal! import pandas as pd from plotly import __version__ from plotly.offline import init_notebook_mode, plot, iplot import plotly.graph_objs as go init_notebook_mode(connected=True) df = pd.DataFrame() df['timestamp']=['2018-07-04 08:11:54.170000', '2018-07-04 08:15:01.910000', '2018-07-04 08:23:09.700000', '2018-07-04 08:25:17.490000', '2018-07-04 08:42:25.290000', '2018-07-04 09:16:33.300000', '2018-07-04 09:27:40.830000', '2018-07-04 09:33:48.620000', '2018-07-04 09:45:56.410000', '2018-07-04 09:50:04.200000', '2018-07-04 10:13:11.950000', '2018-07-04 10:19:19.740000'] df['a']=[5.732026, 5.483141, 5.454963, 6.031954, 5.860383, 5.654590, 5.277766, 5.568183, 5.886682, 6.141217, 5.894507, 5.720255] df['b']=[7.930378, 8.040632, 7.634940, 7.256924, 7.488524, 7.697418, 7.817510, 7.752958, 7.326519, 7.462479, 7.515888, 7.387331] df['c']=[8.606152, 8.414517, 8.940616, 8.380531, 8.358526, 8.476449, 8.887601, 9.019584, 8.714343, 8.745352, 8.752824, 8.755654] df=df.set_index(['timestamp']) df.index = pd.to_datetime(df.index) z = [] z.append(list(df['c'])) z.append(list(df['b'])) z.append(list(df['a'])) data = [ go.Heatmap( z=z, x=df.index, y=['c','b','a'], ) ] layout = go.Layout( xaxis = dict(ticks='', nticks=25), yaxis = dict(ticks='' ) ) fig = go.Figure(data=data, layout=layout) iplot(fig) Have fun!

series
tag name: series
type: Tag
tags question: http://stackoverflow.com/q/51259229
tags question: http://stackoverflow.com/q/51300956
tags question: http://stackoverflow.com/q/51310072
tags question: http://stackoverflow.com/q/51243702
tags question: http://stackoverflow.com/q/51309108
tags question: http://stackoverflow.com/q/51180102
tags question: http://stackoverflow.com/q/51279903
tags question: http://stackoverflow.com/q/51226960
tags question: http://stackoverflow.com/q/51205373
tags question: http://stackoverflow.com/q/51208570
tags question: http://stackoverflow.com/q/51187850
tags question: http://stackoverflow.com/q/51301149
tags question: http://stackoverflow.com/q/51278861
tags question: http://stackoverflow.com/q/51291382
tags question: http://stackoverflow.com/q/51268370

http://stackoverflow.com/comment/89568315
comment on: http://stackoverflow.com/q/51295378
score: 0
type: Comment
type: QuestionComment
has text: saved as a file and calling through file.py on cmd on windows. it looks like it runs through the script and then opens the browser, which says the site can't be reached.

http://stackoverflow.com/q/51266814
tagged with: pycharm
has comment: http://stackoverflow.com/comment/98416439
downvote count: 0
tagged with: python
score: 2
type: AnsweredQuestion
tagged with: pytest
has answer: http://stackoverflow.com/a/51306156
accepted answer: http://stackoverflow.com/a/51306156
has body: Let's say I have an app.py file with the following contents: def foo(): return 'bar' Even with py.test set as a default test runner in PyCharm (Settings -&gt; Tools -&gt; Python Integrated Tools), PyCharm always generate unittest-like tests (right-click on a function name -&gt; Go To -&gt; Test -&gt; Create New Test), eg.: from unittest import TestCase class TestFoo(TestCase): def test_foo(self): self.fail() I can change Python Unit Test template in Setting -&gt; Editor -&gt; File and Code Templates, but it only has effect when creating new file (New -&gt; Python File -&gt; Kind: Python unit test). I would like the generated tests to be more py.test-like: def test_foo(): assert False Even better would be to have proper imports already placed in: from my_app import foo def test_foo(): assert False
type: Question
upvote count: 2
has title: Is it possible to generate py.test test files in PyCharm?
answer count: 1
favorite count: 0

http://stackoverflow.com/q/51172820
has comment: http://stackoverflow.com/comment/89330145
has comment: http://stackoverflow.com/comment/89329267
has body: In django forms, for saving other data I usually use form_valid() but as I can also use save() method of formclass. Today I overrided save() instead of form_valid() and I got problem with my manytomanyfield. When using , the values of manytomanyfield are not saved but when I use form_valid() they start saving. Can anybody tell me the reason and what are the differences between both, which is the most convenient method and in what situation? Here is my overriding of save() method: class ProductCreateForm(forms.ModelForm): sizes = make_ajax_field(ProductCreateModel,'sizes','sizes') colours = make_ajax_field(ProductCreateModel,'colours','colours') class Meta: model = ProductCreateModel fields = ('title','category', 'regions',) def __init__(self,*args,**kwargs): self.request = kwargs.pop("request") super(ProductCreateForm, self).__init__(*args, **kwargs) def save(self): product = super(ProductCreateForm, self).save(commit=False) user = self.request.user product.location = user.user_location product.save() return product When I override form_valid() method: def get_form_kwargs(self): kwargs = super(ProductCreateView,self).get_form_kwargs() kwargs.update({'request':self.request}) return kwargs def form_valid(self, form): product = form.save(commit=False) user = self.request.user form.instance.user = user form.instance.location = user.user_location form.save() return super(ProductCreateView, self).form_valid(form) sizes,colours and regions are m2m fields, as I mentioned when I overrides save() values of m2m not get saved but when I overrides form_valid they start saving.
favorite count: 0
type: UnansweredQuestion
tagged with: django
tagged with: python
has title: Django - form_valid() vs save()
score: 14
tagged with: django-views
tagged with: django-forms
downvote count: 1
has answer: http://stackoverflow.com/a/51174259
type: Question
upvote count: 15
answer count: 2
has answer: http://stackoverflow.com/a/51173740
tagged with: django-models

http://stackoverflow.com/a/51278690
has comment: http://stackoverflow.com/comment/89614388
has body: If your df has always 2 values for each ID, you could first order the rows, then fill Value1 and Value2 and then remove the duplicates: df = df.sort_values(['ID', 'Value1'], ascending=[True, False]) df'Value1', 'Value2' = df'Value1', 'Value2'.replace('', np.NaN) df['Value1'] = df['Value1'].ffill() df['Value2'] = df['Value2'].bfill() df = df.drop_duplicates(subset=['ID']) Output: ID Name Age Value1 Value2 1 1 Arya 10 20 3 2 Sansa 67 56
has comment: http://stackoverflow.com/comment/89535039
upvote count: 1
has comment: http://stackoverflow.com/comment/89534848
type: Answer
has comment: http://stackoverflow.com/comment/89614503
has comment: http://stackoverflow.com/comment/89534900
has comment: http://stackoverflow.com/comment/89614416
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/51278376

http://stackoverflow.com/comment/89598466
type: Comment
comment on: http://stackoverflow.com/a/51310846
score: 0
has text: Yes I have tried this method but always seem to get several errors, I tried right now and it says: AtrivbuteError: "list" object has no attrictute "split"
type: AnswerComment

http://stackoverflow.com/a/51272535
type: Answer
score: 0
has body: You can try like this to achieve the expected output: for items in soup.find_all("td"): if "Focus" in items.text: data = items.find_parent("tr") for elem in data.find_next_siblings(): if "Result" in elem.find(class_="label").text:break item = elem.find(class_="label").get_text(strip=True) value = elem.find(class_="value").get_text(strip=True) print(f'{item} {value}') Output: Centre_Score: 0.08565902709961 Top_Left_Score: 0.06830544769764 Top_Right_Score: 0.06978666782379 Bottom_Right_Score: 0.06947886943817 Bottom_Left_Score: 0.07671363651752
answers question: http://stackoverflow.com/q/51269596

http://stackoverflow.com/comment/89492016
score: 0
comment on: http://stackoverflow.com/a/51256403
has text: I think that did it. Thanks!!
type: AnswerComment
type: Comment

http://stackoverflow.com/q/51302672
linked to: http://stackoverflow.com/q/25260088
has body: I am trying to download a file in all the machine and therefore I have created a python script. It uses the module paramiko just a snippet from the code: from paramiko import SSHClient, AutoAddPolicy ssh = SSHClient() ssh.load_system_host_keys() ssh.set_missing_host_key_policy(AutoAddPolicy()) ssh.connect(args.ip,username=args.username,password=args.password) stdin, stdout, stderr = ssh.exec_command("wget xyz") print(stdout.read()) The output will be printed after the download has been completed.! Is there a way I can print the output real time? Edit: I have looked at this answer and applied something like this: def line_buffered(f): line_buf = "" print "start" print f.channel.exit_status_ready() while not f.channel.exit_status_ready(): print("ok") line_buf += f.read(size=1) if line_buf.endswith('\n'): yield line_buf line_buf = '' in, out, err = ssh.exec_command("wget xyz") for l in line_buffered(out): print l But, It is not printing the data real time.! It waits for the file to download and then prints the whole status of the download. Also, I have tried this command : echo one &amp;&amp; sleep 5 &amp;&amp; echo two &amp;&amp; sleep 5 &amp;&amp; echo three and the output is realtime with line_buffered function. But, for wget command, it is not working..
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51355046
has comment: http://stackoverflow.com/comment/89582690
type: Question
has answer: http://stackoverflow.com/a/51355046
has title: Real time output of wget command by using exec_command in Paramiko
tagged with: paramiko
score: 0
answer count: 1

http://stackoverflow.com/q/51175939
tagged with: django-urls
type: UnansweredQuestion
type: Question
tagged with: python
has answer: http://stackoverflow.com/a/51176362
has answer: http://stackoverflow.com/a/51178009
score: 0
answer count: 2
tagged with: django
has title: How to change URLs based on a column data from the Database
has body: I tried a lot but I am just not able to reach the exact solution. I want to change the URLs of the list which is being generated by a for loop in HTML. Here is my code for that view in views.py file: class DashboardHomeViewClass(View): def get(self, request, *args, **kwargs): device_objects = device_user_data.objects.filter(User_Name = request.user.username) device_list = [] for device in device_objects: device_list.append(device.Device_Alias_Data) context_logged = {'device_list': device_list} return render(request, "dashboardhometemplate.html", context_logged) Here is the code where this context is being used in the HTML template: {%for item in device_list%} &lt;li&gt; &lt;a href="#" aria-expanded="false"&gt;&lt;i class="fa fa-bar-chart"&gt;&lt;/i&gt;&lt;span class="hide-menu"&gt;{{item}}&lt;/span&gt;&lt;/a&gt; {% endfor %} Now what I need exactly is: Different links should open on clicking different list view items based on device_Alias_Data. eg : http://127.0.0.1:8000/dashboard/{{Device_Alias_Data}} where Device_Alias_Data is character varying field in a table named device_user_data in my database. Here is my urls.py file : from django.conf.urls import url from django.contrib import admin from dashboardhome.views import DashboardHomeViewClass from dashboardhome.views import login_view from django.contrib.auth.views import login urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^login/$', login ,{'template_name': 'login_template.html'}), url(r'^dashboard/$', DashboardHomeViewClass.as_view()), ]

http://stackoverflow.com/a/51245395
score: 0
has body: You can get hour from timestamp. from pyspark.sql import functions as F day_timestamps = 24*60*60 hour_timestamps = 60*60 hour = 10 tmstmp2hour = lambda tm: (tm%day_timestamp)/hour_timestamp df.filter( (tmstmp2hour(F.col('start'))&lt;hour) &amp; (tmstmp2hour(F.col('end'))&gt;hour) )
type: Answer
has comment: http://stackoverflow.com/comment/89497769
answers question: http://stackoverflow.com/q/51241445

http://stackoverflow.com/q/51315047
accepted answer: http://stackoverflow.com/a/51315320
has body: I have created 2 python sets created from 2 different CSV files which contains some stings. I am trying to match the 2 sets so that it will return an intersection of the 2 (the common strings from both the sets should be returned). This is how my code looks: from nltk.corpus import stopwords from nltk.tokenize import word_tokenize import string import nltk #using content mmanager to open and read file #converted the text file into csv file at the source using Notepad++ with open(r'skills.csv', 'r', encoding="utf-8-sig") as f: myskills = f.readlines() #converting mall the string in the list to lowercase list_of_myskills = map(lambda x: x.lower(), myskills) set_of_myskills = set(list_of_myskills) #print(type(nodup_filtered_content)) print(set_of_myskills) #open and read by line from the text file with open(r'list_of_skills.csv', 'r') as f2: #using readlines() instead of read(), becasue it reads line by line (each line as a string obj in the python list) contents_f2 = f2.readlines() #converting mall the string in the list to lowercase list_of_skills = map(lambda x: x.lower(), contents_f2) #converting into sets set_of_skills = set(list_of_skills) print(set_of_skills) And this is the function that I am using: def set_compare(set1,set2): if(set1 &amp; set2): return print('The matching skills are: '(set1 &amp; set2)) else: print("No matching skills") After I run the code: set_compare(set_of_skills,set_of_myskills) Output: No matching skills The contents of the 'skills.csv' is: {'critical thinking,identify user needs,business intelligence,business analysis,teamwork,database,data visualization,data analysis,relational database,mysql,oracle sql,design,entity-relationship,develop ,use-cases ,scenarios,project development ,user requirement,design,sequence diagram,state diagram,identifying,uml diagrams,html5,css3,php,clean,analyze,plot,data,python,pandas,numpy,matplotlib,ipython notebook,spyder,anaconda,jupyterlab,data analysis,data visualization,tableau,database,surveys,prototy…
type: Question
tagged with: python
tagged with: jupyter-notebook
score: 0
answer count: 2
has title: Unable to compare 2 Python sets that contains strings
possible better answer: http://stackoverflow.com/a/51315523
has answer: http://stackoverflow.com/a/51315523
tagged with: jupyter-lab
has answer: http://stackoverflow.com/a/51315320
type: AnsweredQuestion

http://stackoverflow.com/comment/89453224
has text: Will the first element list of `a` alway have the same index as the matching element list element in `b`?
comment on: http://stackoverflow.com/q/51237032
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51189103
has comment: http://stackoverflow.com/comment/89360228
has comment: http://stackoverflow.com/comment/89476166
has comment: http://stackoverflow.com/comment/89457531
has comment: http://stackoverflow.com/comment/89360162
upvote count: 1
has comment: http://stackoverflow.com/comment/89459774
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51188496
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51188496
type: Answer
has body: If you are using Java 9 or later, use Process::info() to get the ProcessHandle.Info object for the process (if available). Depending on what the JVM supports on your OS platform, that may give you the total CPU time for the process, and the processes start time ... which you can use to calculate the elapsed time, under some circumstances. Another alternative on a Linux system is to execute the command as "/usr/bin/time your command", and parse the last three lines of standard output to get the elapsed time, "user" CPU time and "system" CPU time. For example: $ time date Thu Jul 5 20:25:01 AEST 2018 real 0m0.002s user 0m0.001s sys 0m0.001s Capture and parse the last 3 lines. (Implementing this in Java is left as an exercise ...) The GNU version of the time command has options that can be used to show memory usage as well. This is described in the manual entry. Some equivalent commands for Windows are described here: https://superuser.com/questions/228056/windows-equivalent-to-unix-time-command For the record, this (roughly speaking) is the way use time using ProcessBuilder: ProcessBuilder pb = new ProcessBuilder( "sh", "-c", "/usr/bin/time python filename.py"); or ProcessBuilder pb = new ProcessBuilder( "/usr/bin/time python filename.py"); If you are going to run commands in a subshell using "sh -c", the shell input string must be a single command argument. Since ProcessBuilder doesn't understand quoting, this means that you must do the splitting yourself; see above. To get the GNU time to output the memory parameters, you need to use a format string, as described in "man time"; e.g. /usr/bin/time -f "%e %s %u %M" command to be run Note that it is important to use "/usr/bin/time" rather than "time", since the builtin "time" command in some shells doesn't understand the "-f" option.
score: 1

http://stackoverflow.com/q/51270207
upvote count: 4
has comment: http://stackoverflow.com/comment/89520206
has answer: http://stackoverflow.com/a/51307448
has body: I am trying to detect ellipses in some images. After some functions I got this edges map: I tried using Hough transform to detect ellipses, but this transform has very high complexity, so my computer didn't finish running the transform command even after 5 hours(!). I also tried doing connected components and got this: In last case I also tried continue and binarized the image. In all cases I am stuck in these steps, and have no idea how continue from here. My mission is detect tomatoes in the image. I am approaching this by trying to detect circles and ellipses and find the radius (or average radius in ellipses case) for each one. edited: I add my code for the first method (the result is edge map from above): img = cv2.imread(r'../images/assorted_tomatoes.jpg') gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) imgAfterLight=lightreduce(img) imgAfterGamma=gamma_correctiom(imgAfterLight,0.8) th2 = 255 - cv2.adaptiveThreshold(imgAfterGamma,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY,5,3) median2 = cv2.medianBlur(th2,3) where median2 is the result of shown above in edge map and the code for connected components: import scipy from scipy import ndimage import matplotlib.pyplot as plt import cv2 import numpy as np fname=r'../images/assorted_tomatoes.jpg' blur_radius = 1.0 threshold = 50 img = scipy.misc.imread(fname) # gray-scale image gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) print(img.shape) # smooth the image (to remove small objects) imgf = ndimage.gaussian_filter(gray_img, blur_radius) threshold = 80 # find connected components labeled, nr_objects = ndimage.label(imgf &gt; threshold) where labeled is the result above another edit: this is the input image: Input The problem is that after edge detection, there are a lot of unnecessary edges in sub regions that disturbing for make smooth edge map
type: UnansweredQuestion
tagged with: computer-vision
type: Question
has comment: http://stackoverflow.com/comment/89521053
tagged with: opencv
score: 3
tagged with: scikit-image
tagged with: image-processing
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/89519004
favorite count: 0
has title: Difficulty in detected ellipses in image
has comment: http://stackoverflow.com/comment/89518866
tagged with: python

http://stackoverflow.com/comment/89533947
type: QuestionComment
type: Comment
has text: Is there any way to build that class step-by-step, in order to spot mistakes very early? Like this, I hit run, see that nothing happens and ask myself why.
comment on: http://stackoverflow.com/q/51277848
score: 0

http://stackoverflow.com/comment/89403913
score: 0
type: AnswerComment
type: Comment
has text: I've edited my answer to point out a couple of other suspected issues.
comment on: http://stackoverflow.com/a/51210035

http://stackoverflow.com/q/51238876
tagged with: python
has answer: http://stackoverflow.com/a/51238898
favorite count: 0
type: AnsweredQuestion
score: 1
tagged with: dataframe
tagged with: mask
type: Question
upvote count: 1
answer count: 1
downvote count: 0
has body: I would like to mask a df using another one regardless the name of the columns, but considering only their positions. For example, given these 2 df: df = pd.DataFrame({'D': [10,20,0], 'E': [0, 30, 10], 'F': [0, 0, 10]}) df2 = pd.DataFrame({'A': [1,1,1], 'C': [1, 1, 1], 'E': [1, 1, 1]}) and using this mask: mask = (df != 0) I would like: A C E 0 NaN 1.0 1.0 1 NaN NaN 1.0 2 1.0 NaN NaN Where D masks A, E(of the first df) masks C and F masks E(of the second df). I can do this removing columns names: df.columns = [''] * len(df.columns) mask = (df != 0) df2.columns = [''] * len(df2.columns) dfn = df2.mask(mask) But is there a better way? Thanks in advance
accepted answer: http://stackoverflow.com/a/51238898
tagged with: pandas
has title: Mask 2 df by columns position

http://stackoverflow.com/comment/89565508
has text: @dfri Yeah, that's a better way to put what I was trying to say.
score: 0
comment on: http://stackoverflow.com/q/51293326
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89386208
type: Comment
has text: If you have an error message please include it in the question. It's a great way to give specific information about your error, that you may not have realised was helpful or relevant.
score: 0
comment on: http://stackoverflow.com/q/51202383
type: QuestionComment

http://stackoverflow.com/comment/89605443
score: 3
has text: Forcing it to allocate memory in advance will probably be slower, not faster. There are occasionally reasons to do so, but they're mostly related to cases where you're pushing the limits of your RAM and fighting the OS's overcommit, or cases where you're trying to get more detailed platform-specific benchmarks or profiling, etc., and usually you end up having to do something low-level and platform-specific anyway.
comment on: http://stackoverflow.com/q/51314255
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89336716
type: Comment
has text: @Uchiha_Itachi the value of jsonResp = {}. The serialized json is not getting read correctly. I am not sure if print json.dumps(dd) is the right way to pass data back to groovy script.
comment on: http://stackoverflow.com/q/51173328
score: 0
type: QuestionComment

http://stackoverflow.com/comment/89547413
has text: I think you need to separate `joined`, since it will be quoted and interpreted as a single argument otherwise.
score: 3
type: QuestionComment
comment on: http://stackoverflow.com/q/51285073
type: Comment

http://stackoverflow.com/q/51262031
has title: Google Dataflow - Failed to import custom python modules
has answer: http://stackoverflow.com/a/68370602
favorite count: 0
type: UnansweredQuestion
tagged with: apache-beam
tagged with: python
has body: My Apache beam pipeline implements custom Transforms and ParDo's python modules which further imports other modules written by me. On Local runner this works fine as all the available files are available in the same path. In case of Dataflow runner, pipeline fails with module import error. How do I make custom modules available to all the dataflow workers? Please advise. Below is an example: ImportError: No module named DataAggregation at find_class (/usr/lib/python2.7/pickle.py:1130) at find_class (/usr/local/lib/python2.7/dist-packages/dill/dill.py:423) at load_global (/usr/lib/python2.7/pickle.py:1096) at load (/usr/lib/python2.7/pickle.py:864) at load (/usr/local/lib/python2.7/dist-packages/dill/dill.py:266) at loads (/usr/local/lib/python2.7/dist-packages/dill/dill.py:277) at loads (/usr/local/lib/python2.7/dist-packages/apache_beam/internal/pickler.py:232) at apache_beam.runners.worker.operations.PGBKCVOperation.__init__ (operations.py:508) at apache_beam.runners.worker.operations.create_pgbk_op (operations.py:452) at apache_beam.runners.worker.operations.create_operation (operations.py:613) at create_operation (/usr/local/lib/python2.7/dist-packages/dataflow_worker/executor.py:104) at execute (/usr/local/lib/python2.7/dist-packages/dataflow_worker/executor.py:130) at do_work (/usr/local/lib/python2.7/dist-packages/dataflow_worker/batchworker.py:642)
score: 8
downvote count: 0
has answer: http://stackoverflow.com/a/51847744
upvote count: 8
type: Question
tagged with: google-cloud-dataflow
answer count: 2

http://stackoverflow.com/q/51318909
tagged with: python
has body: I successfully installed keras in RStudio on Windows. By default it installed miniconda with python 3.6 and all the required packages. I would like to use keras directly in python with the same installation. But when I run python from command line and then import keras I get an error: Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ModuleNotFoundError: No module named 'keras' I do see keras-2.1.6-py36_0 directory in pkgs. Please help how I can solve this without breaking keras installation in RStudio.
has comment: http://stackoverflow.com/comment/89626056
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89625965
type: Question
has answer: http://stackoverflow.com/a/51325523
score: 0
has title: How to use keras in python 3.6 (miniconda) installed through RStudio keras::install_keras()?
answer count: 1
tagged with: keras
accepted answer: http://stackoverflow.com/a/51325523
tagged with: rstudio

http://stackoverflow.com/a/51189261
has comment: http://stackoverflow.com/comment/89539528
has comment: http://stackoverflow.com/comment/89458168
has comment: http://stackoverflow.com/comment/89385223
has comment: http://stackoverflow.com/comment/115079965
has comment: http://stackoverflow.com/comment/89387927
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/115087775
downvote count: 0
has comment: http://stackoverflow.com/comment/89387186
has comment: http://stackoverflow.com/comment/89388258
answers question: http://stackoverflow.com/q/51183411
type: Answer
upvote count: 6
accepted answer of: http://stackoverflow.com/q/51183411
has body: The trick is to make your faint single pixel boundary slightly bolder. I do it by changing any white pixel that has two adjacent black pixels (above, below, to the left or to the right) to black. (I do it extremely slow, though. I'm pretty sure there must be a smarter way to do it with OpenCV or Numpy.) Here is my code: #!/usr/bin/env python import numpy as np import cv2 THRESH = 240 orig = cv2.imread("map.png") img = cv2.cvtColor(orig, cv2.COLOR_BGR2GRAY) # Make the faint 1-pixel boundary bolder rows, cols = img.shape new_img = np.full_like(img, 255) # pure white image for y in range(rows): if not (y % 10): print ('Row = %d (%.2f%%)' % (y, 100.*y/rows)) for x in range(cols): score = 1 if y &gt; 0 and img.item(y-1, x) &lt; THRESH else 0 score += 1 if x &gt; 0 and img.item(y, x-1) &lt; THRESH else 0 score += 1 if y &lt; rows-1 and img.item(y+1, x) &lt; THRESH else 0 score += 1 if x &lt; cols-1 and img.item(y, x+1) &lt; THRESH else 0 if img.item(y, x) &lt; THRESH or score &gt;= 2: new_img[y, x] = 0 # black pixels show boundary cv2.imwrite('thresh.png', new_img) # Find all contours on the map _th, contours, hierarchy = cv2.findContours(new_img,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE) print "Number of contours detected = %d" % len(contours) # Fill second level regions on the map coln = 0 colors = [ [127, 0, 255], [255, 0, 127], [255, 127, 0], [127, 255, 0], [0, 127, 255], [0, 255, 127], ] hierarchy = hierarchy[0] for i in range(len(contours)): area = cv2.contourArea(contours[i]) if hierarchy[i][3] == 1: print (i, area) coln = (coln + 1) % len(colors) cv2.drawContours(orig, contours, i, colors[coln], -1) cv2.imwrite("colored_map.png", orig) Input image: Output image: Here I color only the direct descendants of the outmost contour (hierarchy[i][3] == 1). But you can change it to exclude the lakes.
score: 6
has comment: http://stackoverflow.com/comment/115089732
has comment: http://stackoverflow.com/comment/115074298

http://stackoverflow.com/comment/89554982
type: QuestionComment
has text: Note: you should import everything from `all`, as sendup isn’t really located in utils... except for contrib modules or TLS, there should be no need to import it as so
type: Comment
comment on: http://stackoverflow.com/q/51287871
score: 0

http://stackoverflow.com/a/51194907
has body: From the comments it sounds like the biggest problem you have is an inconsistent data source. In the given list of values you have regular floating point values: nan, 1.0, 0.0 strings that represent floats: "1.0", "0.0" and strings that contain integers as binary values: "\x01" It's relatively trivial to sort out the floats from the strings with something like: if type(item) == float: #do stuff Furthermore if you want to sort out the nan values (a special type of float) you can do this: if type(item) == float if item == float('nan'): #do other stuff else: #do stuff Sorting out the strings is a little trickier as there are many ways to represent a value using a string.The regular string to float conversion using float("1.0") works if your string already looks like a float (rules for looking like a float). If however the value is represented by the binary value of the string characters (it sounds like this may be the case) you will have to find a way to differentiate between the two types of string. This may be as simple as first trying to call float(item) and catching errors when the format doesn't match the "like a float" criteria. Then assuming you only have a single character you could use ord(item) to return the binary representation of said character. This might look something like this: try: converted = float(item) catch ValueError: if len(item) == 1: converted = ord(item) else: #determine how to handle multi character values
has comment: http://stackoverflow.com/comment/89372021
type: Answer
answers question: http://stackoverflow.com/q/51193908
score: 0

http://stackoverflow.com/comment/89354565
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51185266
has text: @MagnusEriksson I tried two type of method, one is actually saving the file in my computer before uploading it, and the var dump shows correct result with the size of the file being the size of the uploaded file, however, the temp files only shows 0. Can I know why?
score: 0

http://stackoverflow.com/comment/89379226
type: Comment
type: QuestionComment
has text: I second @EugenePrimako. You have a syntax error and python fails at runtime just after printing the first line.
comment on: http://stackoverflow.com/q/51198673
score: 0

http://stackoverflow.com/a/51239856
score: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/106439654
has body: In both cases you are splitting data differently. But pos_tag needs an iterable as input. In your first case you are splitting a sentence letter by letter. For ex sentence = "cat" for word in sentence: print(word) # 'c' , 'a', 't' Then you are asking pos_tagger to find part of speech of each letter. print(nltk.pos_tag(word)) Obviously you get part of speech tag of each letter here since each time you are giving letter as input to pos_tag(). In your second example you are splitting the sentence by words. For example: sentence = 'I am a good boy' splitted_words = sentence.split() # you can use split() instead of split(' ') for word in splitted_words: print(word) # 'I', 'am', 'a', 'good', 'boy' Now important point to notice that each word is iterable. 'am' is iterable, we can itreate through 'am' and we get 'a' and 'm'. So as obvious pos_tagger gave results for letters in the words. How to overcome this issue: pos_tag() needs an iterable as argument(list,tuple etc). I would recommend you to use tokenizer() present with NLTK rather than manually splitting a sentence by spaces. So your code should be something like this: sentence = "I am a good boy" tokenised_words = word_tokenize(sentence) # ['I', 'am', 'a', 'good', 'boy'] print(nltk.pos_tag(tokenised_words)) output [('I', 'PRP'), ('am', 'VBP'), ('a', 'DT'), ('good', 'JJ'), ('boy', 'NN')]
upvote count: 3
type: Answer
answers question: http://stackoverflow.com/q/51239434

http://stackoverflow.com/comment/89614091
has text: Object is base-class. int is a sub_class from object. You can check here.https://stackoverflow.com/questions/100003/what-are-metaclasses-in-python?rq=1
score: 0
comment on: http://stackoverflow.com/q/51318855
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89453087
type: QuestionComment
score: 1
has text: Are you open to using libraries like `pandas`?
comment on: http://stackoverflow.com/q/51237032
type: Comment

http://stackoverflow.com/a/51181841
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51181710
has comment: http://stackoverflow.com/comment/89346291
answers question: http://stackoverflow.com/q/51181710
type: Answer
score: 1
has body: Your code takes quite a bit of time because of the numerous loops it runs through, and the fact that it opens a file each time it passes through the loop. Let's try to simplify the code here. Let word_list be the list of words you would like to pass to the program, and test_list the list you want to test the newly formed words against. The following code will print each word in word_list that has a new form in test_list, and print each of those words. def word_mix(word): return [word[i:]+word[:i] for i in range(1,len(word))] my_list = [set(word_mix(i)).intersection(test_list) for i in word_list] for i in range(0,len(word_list)): if bool(my_list(i)): print(word_list[i]+': '+','.join(my_list[i]))
upvote count: 1
type: AcceptedAnswer

http://stackoverflow.com/a/51419994
type: Answer
answers question: http://stackoverflow.com/q/51274664
has comment: http://stackoverflow.com/comment/89838003
has comment: http://stackoverflow.com/comment/90244816
has body: To narrow down the issue, you can install the azureiotedge-simulated-temperature-sensor module published by Microsoft to see whether the issue relative to the Edge environment issue or coding. I also wrote a sample Python code module based on the Python Module templates which works well for me, you can refer the code below: # Copyright (c) Microsoft. All rights reserved. # Licensed under the MIT license. See LICENSE file in the project root for # full license information. import random import time import sys import iothub_client from iothub_client import IoTHubModuleClient, IoTHubClientError, IoTHubTransportProvider from iothub_client import IoTHubMessage, IoTHubMessageDispositionResult, IoTHubError # messageTimeout - the maximum time in milliseconds until a message times out. # The timeout period starts at IoTHubModuleClient.send_event_async. # By default, messages do not expire. MESSAGE_TIMEOUT = 10000 # global counters RECEIVE_CALLBACKS = 0 SEND_CALLBACKS = 0 # Choose HTTP, AMQP or MQTT as transport protocol. Currently only MQTT is supported. PROTOCOL = IoTHubTransportProvider.MQTT # Callback received when the message that we're forwarding is processed. def send_confirmation_callback(message, result, user_context): global SEND_CALLBACKS print ( "Confirmation[%d] received for message with result = %s" % (user_context, result) ) map_properties = message.properties() key_value_pair = map_properties.get_internals() print ( " Properties: %s" % key_value_pair ) SEND_CALLBACKS += 1 print ( " Total calls confirmed: %d" % SEND_CALLBACKS ) # receive_message_callback is invoked when an incoming message arrives on the specified # input queue (in the case of this sample, "input1"). Because this is a filter module, # we will forward this message onto the "output1" queue. def receive_message_callback(message, hubManager): global RECEIVE_CALLBACKS message_buffer = message.get_bytearray() size = len(message_buffer) print ( " Data: &lt;&lt;&lt;%s&gt;&gt;&gt; &amp; Size=%d" % (mess…
has comment: http://stackoverflow.com/comment/90214600
has comment: http://stackoverflow.com/comment/89836261
score: 0

http://stackoverflow.com/comment/89556195
has text: Thank you for your help Martin! However I think I may have explained my issue poorly. The table you outlined above in your answer is the one that I have already extracted successfully. It is the other table (see my "product data" image in the edit) which has data such as indoor furniture, beds etc in the text fields. It is this table that I am unable to extract correctly when looping over my license codes.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/51289058
type: Comment

http://stackoverflow.com/a/67984510
score: 4
upvote count: 4
downvote count: 0
answers question: http://stackoverflow.com/q/51181170
type: Answer
has body: I know that this is an old question, but I think it is still relevant. I don't think shanmuga's solution is right because features within the same rank are not ordered by importance. That is, if selector.ranking_ has 3 features with rank 1, I don't think it is necessarily true that the first in the list is more important than the second or third. A naive solution to this problem would be to run RFE while setting n_features_to_select to the desired number and "manually" cross-validate it. In case you want n features from the optimal m features (with n<m) you can do: # selector is a RFECV fitted object feature_importance = selector.estimator_.feature_importances_ # or coef_ feature_importance_sorted = sorted(enumerate(feature_importance), key=lambda x: x[1]) top_n_idx = [idx for idx, _ in feature_importance_sorted[:n]] You should note that multiple features may have the same importance or coefficient, which you might leave out with this approach.
has comment: http://stackoverflow.com/comment/135978185

http://stackoverflow.com/a/51241744
has body: There were a few issues with your schema. First, exclusiveMinimum must be a boolean, not a string. Second, required needs to be an the object level, and not the property level, as the schema is specified as a draft-4 schema. You should use Draft4Validator if possible. Third, $ref. This keyword, all the way to draft-7, replaces the content of the whole object, meaning other key words in that object are ignored. The solution is to wrap the two schemas you want to apply to the instance property in an allOf. I've demonstrated this with the following schema, which seems to do what you're asking. { "$schema": "http://json-schema.org/draft-04/schema#", "type": "object", "properties": { "total_amount": { "$ref": "#/definitions/floatRefMTZ" }, "payable_amount": { "$ref": "#/definitions/floatRefMTZ" } }, "required": ["total_amount", "payable_amount"], "definitions": { "floatRef": { "type": "number" }, "floatRefMTZ": { "allOf": [ { "$ref": "#/definitions/floatRef" }, { "minimum": 0, "exclusiveMinimum": true } ] } } } ("MTZ" is just shorthand for More Than Zero. You can call it whatever you like.)
has comment: http://stackoverflow.com/comment/89467387
has comment: http://stackoverflow.com/comment/89464050
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51239072
has comment: http://stackoverflow.com/comment/89463897
upvote count: 2
type: Answer
answers question: http://stackoverflow.com/q/51239072
has comment: http://stackoverflow.com/comment/89467326
score: 2

http://stackoverflow.com/a/51296280
upvote count: 1
downvote count: 0
has body: Strings are immutable, so you can't assign to a string at specific index like text[i-1] = text[i]. Instead, use text = text[1:] + text[0] + 'ay' to do what you want: vowel = ['a','e','i','o','u'] counter = -1 while True: text = input("Write a word to translate. If you do not want to play anymore, write exit: ") if text == "exit": break elif text[0].lower() in vowel: text = text + 'ay' print(text) elif text[0].lower() not in vowel: text = text[1:] + text[0] + 'ay' print(text)
has comment: http://stackoverflow.com/comment/89570082
has comment: http://stackoverflow.com/comment/89570050
type: Answer
has comment: http://stackoverflow.com/comment/89570405
score: 1
answers question: http://stackoverflow.com/q/51296199

http://stackoverflow.com/comment/89402982
comment on: http://stackoverflow.com/q/51210929
type: Comment
has text: i am confused . as how i can save output x as list named champ_ids ?
score: 0
type: QuestionComment

http://stackoverflow.com/comment/89371248
has text: Is it like `time.clock_settime()`? How do I store time in the future?
comment on: http://stackoverflow.com/q/51191963
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/51302820
answer count: 1
has title: Conditional Column Creation DF Pandas
favorite count: 0
tagged with: python-3.x
tagged with: python
type: AnsweredQuestion
downvote count: 0
score: 1
type: Question
has body: I am having trouble creating a column based on a Boolean conditional that maps a sum of 3 columns if True and average of the same three columns if False. I saw a few stack questions that could map simple string identifiers but can't seem to get my equations to work. I solved my issue with a very clunky function method which I will show as well. But would like to see if anyone has a solution for a more efficient and potentially dynamic way of creating the fields. Data: import os import sys import pandas as pd import numpy as np import re import random df = pd.DataFrame({'A' : ['howdy_man_dude', 'howdy_dude', 'howdy_man_dude', 'howdy_dude', 'howdy_dude', 'howdy_dude', 'howdy_man_dude', 'howdy_dude'], '01-18' : np.random.randn(8).round(2), '02-18' : np.random.randn(8).round(2), '03-18' : np.random.randn(8).round(2), '04-18' : np.random.randn(8).round(2), '05-18' : np.random.randn(8).round(2), '06-18' : np.random.randn(8).round(2)}) pattern = '_man_' df['man'] = df['A'].str.contains(pattern) print(df) 01-18 02-18 03-18 04-18 05-18 06-18 A man 0 -1.47 -1.21 -0.06 0.12 -1.54 0.10 howdy_man_dude True 1 1.27 0.11 -0.42 -0.20 -1.76 0.47 howdy_dude False 2 -0.24 1.02 1.33 -0.59 -1.67 0.21 howdy_man_dude True 3 -0.36 0.54 1.79 0.14 1.40 1.11 howdy_dude False 4 0.31 0.40 0.21 -0.00 0.81 -1.29 howdy_dude False 5 1.09 -0.47 2.43 0.30 -1.28 0.54 howdy_dude False 6 -0.24 -0.19 0.48 1.94 -0.61 -0.51 howdy_man_dude True 7 1.71 -0.80 0.94 2.47 -0.76 -0.26 howdy_dude False These either throw errors, or create a list of lists that I can't easily add as a column: a = df['man'].map(lambda x: (df['01-18']+df['02-18']+df['03-18']) if x == True else (df['01-18']+df['02-18']+df['03-18'])/3 ) a = df['man'].map((df['01-18']+df['02-18']+df['03-18']) if df['man']==True else (df['01-18']+df['02-18']+df['03-18'])/3 ) a = df.map((df['01-18']+df['02-18']+df['03-18']) if df['man']==True else (df['01-18']+df['02-18']+df['03-18'])/3 ) My function will get me what I need (quarterly summation or averages …
has answer: http://stackoverflow.com/a/51303054
accepted answer: http://stackoverflow.com/a/51303054
tagged with: pandas
upvote count: 1

http://stackoverflow.com/a/51199456
has body: Solved by finding a way to call the function without subprocess. I think the issue may have related to default arguments not being set when it is executed through python and hence why below I have had to specify so many arguments. Code: from csvtotable import convert content = convert.convert("C:\\Users\\admin\\Google Drive\\test1743.csv",delimiter=",",quotechar='"',display_length=-1,overwrite=False,serve=False,pagination=True,virtual_scroll=1000, no_header=False, export=True, export_options=["copy","csv","json","print"]) convert.save("C:\\Users\\admin\\Google Drive\\test1743.html",content) Note that the argument names had to be changed where they had a - in the name. I just changed any instance e.g. display-length to display_length in convert.py
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51191345
type: Answer
score: 0
accepted answer of: http://stackoverflow.com/q/51191345

http://stackoverflow.com/comment/89525236
comment on: http://stackoverflow.com/q/51271836
type: Comment
type: QuestionComment
has text: Matplotlib can in general plot `datetime` objects. It has no suppoer for times. You need to attach a date to your times.
score: 1

http://stackoverflow.com/q/51305126
has answer: http://stackoverflow.com/a/56642868
type: UnansweredQuestion
has body: i am trying to fit distributions. The fitting is finished, but i need a measurement, to choose the best model. Many papers are using the Kolomogorov-Smirnov (KS) test. I tried to implement that, and i am getting very low p-value results. The implementation: #Histigram plot binwidth = np.arange(0,int(out_threshold1),1) n1, bins1, patches = plt.hist(h1, bins=binwidth, normed=1, facecolor='#023d6b', alpha=0.5, histtype='bar') #Fitting gevfit4 = gev.fit(h1) pdf_gev4 = gev.pdf(lnspc, *gevfit4) plt.plot(lnspc, pdf_gev4, label="GEV") logfit4 = stats.lognorm.fit(h) pdf_lognorm4 = stats.lognorm.pdf(lnspc, *logfit4) plt.plot(lnspc, pdf_lognorm4, label="LogNormal") weibfit4 = stats.weibull_min.fit(h1) pdf_weib4 = stats.weibull_min.pdf(lnspc, *weibfit4) plt.plot(lnspc, pdf_weib4, label="Weibull") burr12fit4 = stats.burr12.fit(h1) pdf_burr124 = stats.burr12.pdf(lnspc, *burr12fit4) plt.plot(lnspc, pdf_burr124, label="Burr") genparetofit4 = stats.genpareto.fit(h1) pdf_genpareto4 = stats.genpareto.pdf(lnspc, *genparetofit4) plt.plot(lnspc, pdf_genpareto4, label ="Gen-Pareto") #KS-Test print(stats.kstest(h1, lambda k : stats.genpareto.cdf(k, *genparetofit),args=(),N=len(h1),alternative ='two-sided', mode ='approx')) print(stats.kstest(h1, lambda k : stats.lognorm.cdf(k, *logfit),args=(),N=len(h1),alternative ='two-sided', mode ='approx')) print(stats.kstest(h1, lambda k : gev.cdf(k, *gevfit),args=(),N=len(h1),alternative ='two-sided', mode ='approx')) print(stats.kstest(h1, lambda k : stats.weibull_min.cdf(k, *weibfit),args=(),N=len(h1),alternative ='two-sided', mode ='approx')) print(stats.kstest(h1, lambda k : stats.burr12.cdf(k, *burr12fit),args=(),N=len(h1),alternative ='two-sided', mode ='approx')) After this runs, I get values like: KstestResult(statistic=0.065689774346523788, pvalue=2.3778862070128568e-20) KstestResult(statistic=0.063434691987405312, pvalue=5.2567851875784095e-19) KstestResult(statistic=0.065047355887551062, pvalue=5.8076254324909468e-20) KstestResult(statist…
has title: Kolmogorov Smirnov test for the fitting goodness in python
tagged with: model-fitting
type: Question
tagged with: python
tagged with: kolmogorov-smirnov
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/56651534
tagged with: statsmodels

http://stackoverflow.com/comment/89361259
score: 0
comment on: http://stackoverflow.com/q/51189423
has text: Do you have microsoft sdk's installed ?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89601878
type: AnswerComment
type: Comment
has text: Hey I am getting confused. I decided to start a new question. Please feel free to check it out: https://stackoverflow.com/questions/51312587/printing-employee-object-information-from-a-dictonoary-of-employees
comment on: http://stackoverflow.com/a/51311315
score: 0

http://stackoverflow.com/q/51194170
has body: I need to turn string that comes to me in the following format ' 7/ 7/2001 16 14 58' into a datetime object, but white spaces are not recognized as a time delimiter. I believe parser only recognizes [-,:/]. How can I add white spaces to dateutil? The following code: from dateutil import parser example_datetime = ' 7/ 7/2001 16 14 58' parsed_datetime = parser.parse(example_datetime) print(parsed_datetime) Returns this error: ValueError: ('Unknown string format:', ' 7/ 7/2001 16 14 58')
has answer: http://stackoverflow.com/a/51194499
favorite count: 0
upvote count: 1
tagged with: python
type: AnsweredQuestion
tagged with: python-dateutil
score: 1
accepted answer: http://stackoverflow.com/a/51194499
type: Question
answer count: 1
downvote count: 0
has title: dateutil parser: how to parse time separated with blank spaces?
tagged with: datetime

http://stackoverflow.com/q/51294742
has comment: http://stackoverflow.com/comment/89567374
possible better answer: http://stackoverflow.com/a/51307109
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89567206
has title: Python POpen Stdout not returning back when running python
tagged with: popen
has body: READ UPDATE!!! I'm having an issue getting output from a Python POpen from the subproccess module. It works fine on commands such as 'ls' , 'node' , and 'python3 -m pip install requests'. However When I run a simple python file, such as 'python3 test.py' that contains: print("Hello World!") It does not output. Nor does it work with: sys.stdout.write() It runs the code, this can be proven by this code being put in test.py f = open("text.txt","w") f.write("Hello :P") f.close() And it Writing to the file just fine. Here is the code extracted from the main file: def executeCmd(cmd): filename = "cmdlog_{}.txt".format(cmd.replace(" ","-").replace(".","-").replace("/","-")) with io.open(filename, 'wb') as writer, io.open(filename, 'rb', 1) as reader: process = sb.Popen(cmd, stdout=writer,stderr=writer, cwd=oss.getcwd(),shell=True) while process.poll() is None: rd = reader.read() sys.stdout.write(rd.decode("UTF-8")) time.sleep(0.1) time.sleep(0.5) rd = reader.read().decode("UTF-8") sys.stdout.write(rd) time.sleep(0.5) oss.remove(filename) As Extra Info, That function is called as a thread, from another thread that revives data from a socket. Hence the the dictionary 'data' bellow and the send function above. threading.Thread(target=proccessListen,args=([data["cmd"],data["name"]]),daemon=True).start() I'm at my wits end here, with this issue occurring on multiple os's and machines. With no fix yet found, and not related article a few hours worth of googling could not find, I request your help Thank in advance, Sam. UPDATE: After 1/2 hour of playing with code, and searching online to fix the new issue, I've hit a block again. Here is my new code: import io import sys import os import subprocess import time def executeCmd(cmd): process = subprocess.Popen(cmd,stdout=subprocess.PIPE,stderr=subprocess.STDOUT,cwd=os.getcwd(),shell=True) print("Started") while process.poll() is None: line = process.stdout.readline() sys.stdout.write(line) #process.stdout.flush() time.sleep(0.5) pri…
tagged with: stdout
has comment: http://stackoverflow.com/comment/89567639
score: -1
upvote count: 2
has comment: http://stackoverflow.com/comment/89567293
answer count: 2
has comment: http://stackoverflow.com/comment/89567383
has comment: http://stackoverflow.com/comment/89567129
has comment: http://stackoverflow.com/comment/89567260
has answer: http://stackoverflow.com/a/51307109
favorite count: 0
has comment: http://stackoverflow.com/comment/89567447
has comment: http://stackoverflow.com/comment/89567404
downvote count: 3
has comment: http://stackoverflow.com/comment/89567270
accepted answer: http://stackoverflow.com/a/51306846
tagged with: sockets
tagged with: python
has comment: http://stackoverflow.com/comment/89588148
has comment: http://stackoverflow.com/comment/89567241
tagged with: subprocess
has answer: http://stackoverflow.com/a/51306846

http://stackoverflow.com/q/51306623
has title: I want implement purity measure in python
has comment: http://stackoverflow.com/comment/89598354
has answer: http://stackoverflow.com/a/51307934
accepted answer: http://stackoverflow.com/a/51307934
downvote count: 2
tagged with: excel
type: Question
type: AnsweredQuestion
has body: I want implement purity measure in python, I have an excel file like this: The numbers are cluster of laptops. I want to get the number of laptops per cluster like this: can you help me??
upvote count: 0
score: -2
answer count: 1
favorite count: 0
tagged with: python

http://stackoverflow.com/q/51194652
downvote count: 0
answer count: 1
favorite count: 0
tagged with: pandas
has body: I'm trying to create a dictionary in python. However, I want to create the dictionary using the random values. The desired output should be in the form {'a':1, 'b':2} in the format. import numpy as np import pandas as pd import random import string value = np.random.random(10) np.random.seed(42) key = list(np.random.choice(list(string.ascii_lowercase), 10)) key, value def map_values(key, value): i = len(key) j = len(value) for i in len(key): print('key[i]' +'value[j]') i = i+1 j = j+1 return map_values() map_values(key, value) However while running the above code, I got the error 'int' object is not iterable. Can someone explain the reason for the error and rectify the code as I'm new to python and trying to learn it.
tagged with: python
tagged with: dictionary
has title: 'int' object is not iterable while creating dictionary
has comment: http://stackoverflow.com/comment/89370887
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89370966
has comment: http://stackoverflow.com/comment/89371089
upvote count: 1
score: 1
has answer: http://stackoverflow.com/a/51194812
type: Question
tagged with: numpy
tagged with: random

http://stackoverflow.com/comment/89612812
type: QuestionComment
type: Comment
score: 1
comment on: http://stackoverflow.com/q/51243966
has text: @DavidZemens because python-pptx does not support combination chart

http://stackoverflow.com/q/51227091
score: 14
tagged with: pyinstaller
type: UnansweredQuestion
tagged with: python
downvote count: 3
upvote count: 17
type: Question
has answer: http://stackoverflow.com/a/64046240
has title: How to convert exe back to Python script
has body: Recently I converted a .py file to a .exe file. I lost the original .py file and I'm left with the exe file. I converted it with pyinstaller. Is there anyway to reverse this to get my original .py file back?
has answer: http://stackoverflow.com/a/51227106
tagged with: python-2.7
answer count: 2
favorite count: 0

http://stackoverflow.com/comment/89627342
type: AnswerComment
has text: yes sir ! It did help. How beautiful ! The other 3 earlier lines also worked perfectly
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51325114

http://stackoverflow.com/comment/132809418
type: Comment
has text: FWIW in 2023 I couldn't get these arguments to pass correctly _until_ I used that esoteric "purpose" value in my launch.json
comment on: http://stackoverflow.com/a/73610759
score: 0
type: AnswerComment

http://stackoverflow.com/comment/89496851
type: Comment
has text: Thank you for your answer. I received the following output.
comment on: http://stackoverflow.com/a/51259202
type: AnswerComment
score: 0

http://stackoverflow.com/comment/89443999
has text: You can give that fix in comment.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51227060
score: 0

http://stackoverflow.com/comment/89609957
has text: Note: `.date()` truncates the time component from datetimes and creates a datetime.date object.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51316881
score: 3

http://stackoverflow.com/a/51315775
type: Answer
has body: add a comma after the print print(word[y]),
score: 0
answers question: http://stackoverflow.com/q/51315746

http://stackoverflow.com/comment/89616628
comment on: http://stackoverflow.com/a/51319993
score: 0
type: AnswerComment
has text: Column 0 is actually your *index*, that's why. Let me fix that.
type: Comment

http://stackoverflow.com/q/51219203
tagged with: http-status-code-403
tagged with: security
score: 0
answer count: 1
has title: Security error whens scraping ticketing website
tagged with: beautifulsoup
has comment: http://stackoverflow.com/comment/89441191
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/51219217
has comment: http://stackoverflow.com/comment/89419530
type: Question
has body: I'm trying to scrape a ticketing website for a festival to be notified when a new ticket is available (Note: I am not attempting to illegally buy this ticket through automation). from urllib.request import Request, urlopen from bs4 import BeautifulSoup import urllib.request req = urllib.request.Request('http://www.moshtix.com.au/v2/event/splendour-in-the-grass/103360', headers={'User-Agent': 'Mozilla/5.0'}) html = urllib.request.urlopen(req).read() print(html) and here is the following error: lib/python3.7/urllib/request.py", line 649, in http_error_default raise HTTPError(req.full_url, code, msg, hdrs, fp) urllib.error.HTTPError: HTTP Error 403: Forbidden I've tried using the answers from related questions with the same error code but all have failed.

http://stackoverflow.com/a/51245663
upvote count: 15
has comment: http://stackoverflow.com/comment/138392703
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51236304
has body: I took an approach suggested by aws_apprentice above which was to create the table first, then write data to the table. The code below first auto-generates a mysql table from a df (auto defining table names and datatypes) then writes the df data to that table. There were a couple of hiccups I had to overcome, such as: unnamed csv columns, determining the correct data type for each field in the mysql table. I'm sure there are multiple other (better?) ways to do this, but this seems to work. import pandas as pd from sqlalchemy import create_engine infile = r'path/to/file.csv' db = 'a001_db' db_tbl_name = 'a001_rd004_db004' ''' Load a csv file into a dataframe; if csv does not have headers, use the headers arg to create a list of headers; rename unnamed columns to conform to mysql column requirements ''' def csv_to_df(infile, headers = []): if len(headers) == 0: df = pd.read_csv(infile) else: df = pd.read_csv(infile, header = None) df.columns = headers for r in range(10): try: df.rename( columns={'Unnamed: {0}'.format(r):'Unnamed{0}'.format(r)}, inplace=True ) except: pass return df ''' Create a mapping of df dtypes to mysql data types (not perfect, but close enough) ''' def dtype_mapping(): return {'object' : 'TEXT', 'int64' : 'INT', 'float64' : 'FLOAT', 'datetime64' : 'DATETIME', 'bool' : 'TINYINT', 'category' : 'TEXT', 'timedelta[ns]' : 'TEXT'} ''' Create a sqlalchemy engine ''' def mysql_engine(user = 'root', password = 'abc', host = '127.0.0.1', port = '3306', database = 'a001_db'): engine = create_engine("mysql://{0}:{1}@{2}:{3}/{4}?charset=utf8".format(user, password, host, port, database)) return engine ''' Create a mysql connection from sqlalchemy engine ''' def mysql_conn(engine): conn = engine.raw_connection() return conn ''' Create sql input for table names and types ''' def gen_tbl_cols_sql(df): dmap = dtype_mapping() sql = "pi_db_uid INT AUTO_INCREMENT PRIMARY KEY" df1 = df.rename(columns = {"" : "nocolname"}) hdrs = df1.dtypes.index hdrs_list = [(hdr, st…
answers question: http://stackoverflow.com/q/51236304
type: Answer
score: 15

http://stackoverflow.com/comment/89609501
type: QuestionComment
has text: To make sure I understand, the values being lists, what you are looking to do is take each item from each list, and associate them to their corresponding key, eventually resulting in a list of dictionaries. Each dictionary is ultimately the example you show. Is that correct?
score: 1
comment on: http://stackoverflow.com/q/51316579
type: Comment

http://stackoverflow.com/comment/89617389
type: Comment
comment on: http://stackoverflow.com/a/51320448
has text: Im sorry. im using MySQLdb. Edited again above.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/89565767
has text: There you go. It is not a `dict`. So just instantiate a dict and change it.. e.g. `stocks_dict = {}` and `stocks_dict[key] = ...`
comment on: http://stackoverflow.com/q/51293999
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/comment/89411219
type: QuestionComment
comment on: http://stackoverflow.com/q/51214790
has text: Your question is unclear. Do you want to extract the "last login" time separately? Why not extract it within the same regex? `Name is ([A-Z])[\s\w,:]+Last Login: (.*)` should work. The reason why your regex matches so much is that `\s` also matches newlines. You can use that to your advantage.
type: Comment
score: 1

http://stackoverflow.com/q/51229714
tagged with: python
has body: I am using Pydev on Eclipse. This is my code import pandas as pd from urllib.request import urlopen from http.client import RemoteDisconnected xl_sheet = pd.read_excel('sample.xlsx', sheet_name='Sheet1') for i in xl_sheet.index: web_url = xl_sheet['Web'][i] if isinstance(web_url, str): if 'http://' not in web_url: web_url = 'http://' + web_url print(web_url) try: code = urlopen(web_url).getcode() except RemoteDisconnected: print('not working') Pydev shows unresolved import for from http.client import RemoteDisconnected this line. But when I run the code, it works (It prints not working for few of the sites that are down). What could be wrong?
has comment: http://stackoverflow.com/comment/89442440
tagged with: python-3.x
type: UnansweredQuestion
upvote count: 1
has comment: http://stackoverflow.com/comment/89439518
score: 1
has answer: http://stackoverflow.com/a/51251690
tagged with: eclipse
type: Question
tagged with: pydev
answer count: 1
downvote count: 0
favorite count: 0
has title: Pydev shows Unresolved import but code works

http://stackoverflow.com/q/51284354
has answer: http://stackoverflow.com/a/51284458
score: 2
type: AnsweredQuestion
type: Question
has title: StopIteration keeps showing randomly when running code
accepted answer: http://stackoverflow.com/a/51284669
has comment: http://stackoverflow.com/comment/89546065
possible better answer: http://stackoverflow.com/a/51284458
upvote count: 3
answer count: 3
has body: I'm very new to Python and I'm trying to put together a small program which does seem to work, however I get the below error every so often when running the code. The end goal is slightly more complex than the current code, however the idea is the program reads from 2 separate CSV files, picks a random row from each, then concatenates specific values from those rows and prints the result. Error Seen: Traceback (most recent call last): File ".\SimulationScript.py", line 57, in &lt;module&gt; counter(10) File ".\SimulationScript.py", line 45, in counter indicatorDefinition(indicator_file) File ".\SimulationScript.py", line 17, in indicatorDefinition chosen_row = next(row for row_number, row in enumerate(reader) StopIteration Code: from sys import argv import random import csv script, file1, file2 = argv f1 = '' f2 = '' def iDefinition(i): with open(i) as file: lines = sum(1 for line in file) line_number = random.randrange(lines) with open(i) as file: reader = csv.DictReader(file) chosen_row = next(row for row_number, row in enumerate(reader) if row_number == line_number) global f1 f1 = chosen_row['field_1']+'":"'+chosen_row['value_1']+'"' def nDefinition(n): with open(n) as file: lines = sum(1 for line in file) line_number = random.randrange(lines) with open(n) as file: reader = csv.DictReader(file) chosen_row = next(row for row_number, row in enumerate(reader) if row_number == line_number) global f2 f2 = '"code":"'+chosen_row['Node code']+'","' def counter(): count = 0 while count &lt; 6: nDefinition(file2) iDefinition(file1) print(f2+f1) count += 1 counter()
has answer: http://stackoverflow.com/a/51284591
downvote count: 1
has comment: http://stackoverflow.com/comment/89546146
has answer: http://stackoverflow.com/a/51284669
favorite count: 0
tagged with: python-3.x
tagged with: python

http://stackoverflow.com/q/51210985
tagged with: python
type: AnsweredQuestion
score: 1
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/51211033
tagged with: pandas-groupby
tagged with: pandas
has body: I have following database: df = pandas.DataFrame({'Buy':[10,np.nan,2,np.nan,np.nan,4],'Sell':[np.nan,7,np.nan,9,np.nan,np.nan]}) Out[37]: Buy Sell 0 10.0 NaN 1 NaN 7.0 2 2.0 NaN 3 NaN 9.0 4 NaN NaN 5 4.0 NaN I want o create two more columns called Quant and B/S for Quant it is working fine as follows: df['Quant'] = df['Buy'].fillna(df['Sell']) # Fetch available value from both column and if both values are Nan then output is Nan. Output is: df Out[39]: Buy Sell Quant 0 10.0 NaN 10.0 1 NaN 7.0 7.0 2 2.0 NaN 2.0 3 NaN 9.0 9.0 4 NaN NaN NaN 5 4.0 NaN 4.0 But I want to create B/S on the basis of "from which column they have taken value while creating Quant"
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/51211033
has title: Pandas combine two columns
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/q/51268729
linked to: http://stackoverflow.com/q/41901322
type: Question
has comment: http://stackoverflow.com/comment/89515775
answer count: 1
downvote count: 0
tagged with: pandas
tagged with: python
has answer: http://stackoverflow.com/a/51269086
has title: Pandas Dataframe subtraction
favorite count: 0
duplicate of: http://stackoverflow.com/q/51215628
duplicate of: http://stackoverflow.com/q/19960077
duplicate of: http://stackoverflow.com/q/41901322
upvote count: 1
has body: Given two dataframes, df1 and df2, each with a unique ID, ID, how do I get the elements in df2 not in df1? Right now, my solutions are: df2 - df1 = pd.concat([df2, df1, df1]).drop_duplicates(subset = 'ID', keep=False) df1 - df2 = pd.concat([df2, df2, df1]).drop_duplicates(subset = 'ID', keep=False) However, my results are the opposite of what's expected, i.e., RHS(1.) = LHS(2.) and vice versa. Referring to 1., my logic is that the records in df1 are removed as df1 is included twice. Records in df2 with matching IDs to those in df1 are also knocked out. Therefore, the records left are the records in df2 that don't share IDs with those in df1; said differently, the only records that remain are those found exclusively in df2. Pointers would be greatly appreciated. Thanks!
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51269086
score: 1
tagged with: set
tagged with: dataframe

http://stackoverflow.com/a/51177829
upvote count: 22
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51177738
answers question: http://stackoverflow.com/q/51177738
score: 22
has body: bincount returns the count of values in each bin from 0 to the largest value in the array i.e. np.bincount(my_list) == [count(i) for i in range(0, max(my_list))] == [count(0), count(1), ..., count(max(my_list))] e.g. np.bincount([0, 1, 2, 3, 4, 4, 6]) &gt;&gt;&gt; array([1, 1, 1, 1, 2, 0, 1]) Note: absent numbers (e.g. 5 above) return a count of 0 a ValueError is raised if the list contains negative numbers or NaN
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/a/51214922
answers question: http://stackoverflow.com/q/51214273
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: It's not particularly hard. Your code is nearly right (assuming the columns are laid out how you want them, and assuming you pass valid JSON in, because yours has an extra comma), you just need to add a little: for x in x: images = x["photos"] f.writerow([x["title"], x["description"], x["price"], images.pop(0) if images else None]) while images: f.writerow([None, None, None, images.pop(0)]) What this does in short is loop over all of the images in order and print them in new, otherwise-empty rows. Running it on your original code, example.csv ends up looking like this: title,description,price Title 1,Description 1,145,https://cdn.shopify.com/s/files/1/01/01/01/files/imgs-example.jpg?0101010101010 ,,,https://cdn.shopify.com/s/files/1/01/01/01/files/imgs-example2.jpg?0101010101010 ,,,https://cdn.shopify.com/s/files/1/01/01/01/files/imgs-example3.jpg?0101010101010 Title 2,Description 2,150,https://cdn.shopify.com/s/files/1/01/01/01/files/imgs-example4.jpg?0101010101010 ,,,https://cdn.shopify.com/s/files/1/01/01/01/files/imgs-example5.jpg?0101010101010 It should be pretty obvious how to get the things into different columns -- the Nones are just so csv.writer leaves the cell empty, so use them as placeholders for all the other columns. If this needed to be easy to modify, I'd recommend a different approach. This looks like a one-off conversion script, though, so a quick, easy hack will work just fine. A few notes: a if b else c, if b evaluates to True, means a; if it evaluates to False, it means c. ary.pop(n) pops (removes and returns) the object at index n from ary. An empty array evaluates to False (hence why I test just images, not len(images) == 0) You'll probably also want to update the headers. I just them as-is so my only changes were to the last while; you'll probably want to fix them to accurately label the columns.
upvote count: 1
score: 1
accepted answer of: http://stackoverflow.com/q/51214273

http://stackoverflow.com/a/51200446
answers question: http://stackoverflow.com/q/51200320
has comment: http://stackoverflow.com/comment/89424885
has comment: http://stackoverflow.com/comment/89458545
has comment: http://stackoverflow.com/comment/89462098
has body: See e.g. this question for why something like TypeError: method() takes at least n arguments (n given) is not as ridiculous as it may sound at first sight. Here you are calling make_image without any positional argument. The signature, however, is make_image(renderer, magnification=1.0, unsampled=False) So you are missing the renderer argument. In python 3.6 the error is a little more clear. It would say something like TypeError: make_image() missing 1 required positional argument: 'renderer' which allows to find out the problem more easily. Apart the question stays unclear on what the desired outcome is, so that's about what one can say at this point.
score: 4
has comment: http://stackoverflow.com/comment/89505927
upvote count: 4
has comment: http://stackoverflow.com/comment/89558678
downvote count: 0
has comment: http://stackoverflow.com/comment/89461539
type: Answer
has comment: http://stackoverflow.com/comment/89505638
has comment: http://stackoverflow.com/comment/89550453
has comment: http://stackoverflow.com/comment/89424856

http://stackoverflow.com/comment/89520441
comment on: http://stackoverflow.com/q/51252936
score: 0
has text: @LukeKenworthy, [this gist](https://gist.github.com/AbdouSeck/fbdfc9f3ded29e5fd534297de9c8e2e6) is my version of your code and the tests are passing just fine.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51286721
answer count: 1
linked to: http://stackoverflow.com/q/41994485
has answer: http://stackoverflow.com/a/51369532
has comment: http://stackoverflow.com/comment/128784080
score: 2
type: AnsweredQuestion
downvote count: 0
has body: I am using anaconda 3 and when I turn python scripts to .exe using pyinstaller they failed to open and I got an error message that said, Application can't start because could not find or load Qt platform plugin "windows" in " " I looked on stack overflow and found a solution for it here, and it solved my problem. However, now when I download other programs from the internet and try to open them they display the same error, Application can't start because could not find or load Qt platform plugin "windows" in " " I have delete the QT_PLUGIN_PATH from the environment variables in order to make the program that I installed work, but when I do that my .exe fails to open and I have to add the QT_PLUGIN_PATH again to make the .exe work. Is there a way to make both my .exe and installed programs work without having to add and delete the QT_PLUGIN_PATH from the environment variables every time? In environment variables I have, QT_PLUGIN_PATH="C:\Users\username\AppData\Local\Continuum\anaconda3\Library\plugins"
favorite count: 0
accepted answer: http://stackoverflow.com/a/51369532
type: Question
tagged with: pyinstaller
tagged with: python
has title: Changing QT_PLUGIN_PATH in environment variables causes programs to fail
upvote count: 2
tagged with: pyqt5

http://stackoverflow.com/q/51306375
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/11223011
tagged with: selenium
upvote count: 7
tagged with: webdriver
type: Question
score: 5
tagged with: javascript
has answer: http://stackoverflow.com/a/51306416
accepted answer: http://stackoverflow.com/a/51306713
has answer: http://stackoverflow.com/a/51306547
has answer: http://stackoverflow.com/a/51306433
favorite count: 0
has answer: http://stackoverflow.com/a/51306713
has title: AttributeError: 'list' object has no attribute 'click' using Selenium and Python
answer count: 5
downvote count: 2
tagged with: python
has answer: http://stackoverflow.com/a/65879249
possible better answer: http://stackoverflow.com/a/51306416
has body: I'd like to click the button 'Annual' at a page that is by default set on 'Quarterly'. There are two links that are basically called the same, except that one has data-ptype="Annual" so I tryed to copy the xpath to click the button (also tried other options but none did work). However, I get the AttributeError: 'list' object has no attribute 'click'. I read a lot of similar posts, but wasn't able to fix my problem.. so I assume that javascript event must be called/clicked/performed somehow differnt.. idk Im stuck from selenium import webdriver link = 'https://www.investing.com/equities/apple-computer-inc-balance-sheet' driver = webdriver.Firefox() driver.get(link) elm = driver.find_elements_by_xpath("/html/body/div[5]/section/div[8]/div[1]/a[1]").click() The html is the following: &lt;a class="newBtn toggleButton LightGray" href="javascript:void(0);" data-type="rf-type-button" data-ptype="Annual" data-pid="6408" data-rtype="BAL"&gt;..&lt;/a&gt;
tagged with: selenium-webdriver

http://stackoverflow.com/q/51198549
has answer: http://stackoverflow.com/a/51199050
answer count: 1
has comment: http://stackoverflow.com/comment/89518840
has body: I am trying to make a bot to scrape this page http://www.skysports.com/transfer-centre, when I open it in Chrome I can see the element I want in developer tool but when I use the code below, it return None: import requests from bs4 import BeautifulSoup page = requests.get('http://www.skysports.com/transfer-centre').text soup = BeautifulSoup(page, 'lxml') print(soup.find('time')) Am I missing something?
has comment: http://stackoverflow.com/comment/89379027
tagged with: beautifulsoup
tagged with: python
accepted answer: http://stackoverflow.com/a/51199050
has comment: http://stackoverflow.com/comment/116285128
has comment: http://stackoverflow.com/comment/89379089
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/44867425
has comment: http://stackoverflow.com/comment/89379768
type: Question
has title: I can't find an element using BeautifulSoup?
score: 0
has comment: http://stackoverflow.com/comment/89378929

http://stackoverflow.com/comment/89603905
score: 0
has text: In my one experience with Pygame, I used `play()` in a similar manner as OP, without any wait after calling it, and audio played as expected. I suspect something else is the problem here though I can't say for sure.
type: AnswerComment
comment on: http://stackoverflow.com/a/51313372
type: Comment

http://stackoverflow.com/comment/89463502
comment on: http://stackoverflow.com/a/51205506
score: 1
has text: Thanks a lot @SAMIULHUDA your answer worked perfectly for my problem.
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/89471950
type: AnswerComment
comment on: http://stackoverflow.com/a/51246209
score: 0
type: Comment
has text: Nice to hear it helped. consider upvotin and accepting the answer

http://stackoverflow.com/a/51175929
accepted answer of: http://stackoverflow.com/q/51175519
has body: When you face these type of issues, it is good pratice to try the Python Latin-1 encoding. mail = open(file_path, encoding='Latin-1') We often confound the Windows cp1252 encoding with the actual Python's Latin-1. Indeed, the latter maps all possible byte values to the first 256 Unicode code points. See this for more information.
answers question: http://stackoverflow.com/q/51175519
type: Answer
downvote count: 0
score: 1
type: AcceptedAnswer
upvote count: 1

http://stackoverflow.com/q/51269683
type: Question
has body: I did this command to check results of tensorflow training. python label_image.py --image xxx.jpg --graph retrained_graph.pb --labels retrained_labels.txt And found following errors. /Users/xxx/anaconda3/lib/python3.6/site-packages/h5py/__init__.py:36: FutureWarning: Conversion of the second argument of issubdtype from `float` to `np.floating` is deprecated. In future, it will be treated as `np.float64 == np.dtype(float).type`. from ._conv import register_converters as _register_converters 2018-07-11 00:39:22.028051: I tensorflow/core/platform/cpu_feature_guard.cc:140] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2 FMA Traceback (most recent call last): File "label_image.py", line 131, in input_operation = graph.get_operation_by_name(input_name) File "/Users/xxx/tensorFlow/lib/python3.6/site-packages/tensorflow/python/framework/ops.py", line 3718, in get_operation_by_name return self.as_graph_element(name, allow_tensor=False, allow_operation=True) File "/Users/xxx/tensorFlow/lib/python3.6/site-packages/tensorflow/python/framework/ops.py", line 3590, in as_graph_element return self._as_graph_element_locked(obj, allow_tensor, allow_operation) File "/Users/xxx/tensorFlow/lib/python3.6/site-packages/tensorflow/python/framework/ops.py", line 3650, in _as_graph_element_locked "graph." % repr(name)) KeyError: "The name 'import/Mul' refers to an Operation not in the graph." label_image.py is following lines. input_height = 299 input_width = 299 input_mean = 0 input_std = 255 input_layer = "Mul" output_layer = "final_result"
downvote count: 0
has comment: http://stackoverflow.com/comment/89517896
has title: tensorflow error KeyError: "The name 'import/Mul' refers to an Operation not in the graph."
answer count: 1
favorite count: 0
tagged with: python-3.x
upvote count: 2
type: UnansweredQuestion
tagged with: machine-learning
tagged with: python
score: 2
has answer: http://stackoverflow.com/a/51269893
tagged with: tensorflow

http://stackoverflow.com/a/51169750
score: 4
upvote count: 4
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/51168896
has comment: http://stackoverflow.com/comment/89324363
has body: The solution is simpler than I thought. In this line: hist, bin_edges=np.histogram(predict_kmeans) The number of bins is the standard number of bins from numpy (I belive it is 10). By doing this: hist, bin_edges=np.histogram(predict_kmeans, bins=num_clusters) The accuracy increased from the 53.62% I reported to 78.26% using 1000 clusters and, therefore 1000 dimensional vectors.
has comment: http://stackoverflow.com/comment/89347439

http://stackoverflow.com/comment/89458462
has text: But when I add 2 in rowno it giving me the solution what i needed. as below
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51233556
type: AnswerComment

http://stackoverflow.com/a/51240359
score: 1
has comment: http://stackoverflow.com/comment/89460242
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51240272
has body: Try this: name_list = ["Kate", "David"] for name in name_list: xpath = "//*[contains(text(), '" + str(name) + "')]" # simplified print xpath list = driver.find_elements_by_xpath(xpath) # locate all elements by xpath if len(list) &gt; 0: # if list is not empty, click on element list[0].click() # click on the first element in the list time.sleep(5) This will prevent from throwing common.exceptions.NoSuchElementException Note: also make sure, that you using the correct xPath.
answers question: http://stackoverflow.com/q/51240272
type: Answer
downvote count: 0

http://stackoverflow.com/q/51204422
answer count: 1
score: 0
tagged with: wizard
has body: This code only creates one record. What is wrong? class PartnerTagCreate(models.TransientModel): """ Choose tags to be added to partner.""" _name = 'partner.tags.create' _description = __doc__ market_id = fields.Many2one('partner.tags', string='Market Tag') application_id = fields.Many2one('partner.tags', string='Application Tag') partner_id = fields.Integer() @api.multi def create_contact_tag(self): for record in self.env['sale.order.line'].browse(self._context.get('active_ids', [])): vals = {} vals['partner_id'] = record.order_partner_id self.write(vals) return True I need this function to create one record for each order_partner_id I selected before opening the wizard... How to achieve that? Here my new code (function) ... def create_contact_tag(self): sale_order_line_ids = self.env['sale.order.line'].browse(self._context.get('active_ids', [])) for partner in sale_order_line_ids: values = {} values['partner_id'] = partner.order_partner_id self.create(values) return {} This creates one record for marketing_id and/or application_id and dedicated records for each partner_id in the record.
has comment: http://stackoverflow.com/comment/89399728
has comment: http://stackoverflow.com/comment/89557168
has comment: http://stackoverflow.com/comment/89556002
type: UnansweredQuestion
tagged with: python
tagged with: record
has title: Odoo: How to create many records in Transient.Model?
tagged with: odoo
has answer: http://stackoverflow.com/a/51213663
has comment: http://stackoverflow.com/comment/89565184
type: Question

http://stackoverflow.com/q/51252936
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89487327
has comment: http://stackoverflow.com/comment/89520441
type: Question
tagged with: testing
tagged with: flask
score: 0
has comment: http://stackoverflow.com/comment/89497928
tagged with: python
has title: Flask application runs, but fails initial unit test
has comment: http://stackoverflow.com/comment/89486934
answer count: 0
has body: I just started unit testing my flask application and it fails to return a 200 status code when I test it, even though it works perfectly. Here is the unit test code: # dev-environment/test_basic.py import unittest from application import application, db TEST_DB = "test.db" class BasicTests(unittest.TestCase): def setUp(self): application.config['TESTING'] = True application.config['DEBUG'] = False application.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + TEST_DB self.application = application.test_client() db.drop_all() db.create_all() self.assertEqual(application.debug, False) def tearDown(self): pass def test_main_page(self): response = self.application.get("/welcome", follow_redirects=True) self.assertEqual(response.status_code, 200) if __name__ == "__main__": unittest.main() And here is my "/welcome" view in application.py: # dev-environment/application.py @application.route("/welcome") def welcome(): return render_template("welcome.html") I get the following stack trace when I run the unit test file: ====================================================================== FAIL: test_main_page (__main__.BasicTests) ---------------------------------------------------------------------- Traceback (most recent call last): File "test_basic.py", line 22, in test_main_page self.assertEqual(response.status_code, 200) AssertionError: 404 != 200 ---------------------------------------------------------------------- Ran 1 test in 0.475s FAILED (failures=1)

http://stackoverflow.com/comment/89458014
type: QuestionComment
comment on: http://stackoverflow.com/q/51239512
has text: Try with chrome and see if same issue happens
score: 0
type: Comment

http://stackoverflow.com/comment/89378334
has text: Not the downvote here, but I *have* downvoted you several times before for answering obvious duplicates. That could also be the case here.
type: AnswerComment
score: 3
type: Comment
comment on: http://stackoverflow.com/a/51198155

http://stackoverflow.com/comment/98357016
comment on: http://stackoverflow.com/q/51320469
score: 0
type: Comment
type: QuestionComment
has text: I'm also facing same issue :( Were you able to solve it?

http://stackoverflow.com/a/51232515
has comment: http://stackoverflow.com/comment/89501211
has body: Your teacher seems to be (mostly) right. This does not necessarily seem like a problem that has to be addressed programmatically, it can also be solved mathematically (which is probably what your teacher did and why he could say your code must be bugged without looking at it). Math-based solution Let V(S, C) denote the value of choosing color C in a state S. We trivially have V(S2, C) = 0 for all colors C. It is easy to write down the true values V(S0, R) and V(S1, R) for selecting the red action in S0 or S1, because they don't depend on the values of any other states (technically they do depend on the values of S2, but those are 0 so we can leave them out): V(S0, R) = 0.9 * (-2 + gamma * V(S0, R)) V(S1, R) = 0.6 * (-5 + gamma * V(S1, R)) With a bit of arithmetic, these can be rewritten as: V(S0, R) = -1.8 / (1 - 0.9 * gamma) V(S1, R) = -3 / (1 - 0.6 * gamma) It is also useful to observe that a policy that selects B (blue) in both states S0 as well as S1 will never ever be optimal. Such a policy would never reach S2 and simply keep collecting an infinite number of negative rewards. Knowing that, we can easily write V(S0, B) in terms of V(S0, B) and V(S1, R). We don't have to consider a V(S1, B) term in the value V(S0, B) because it would never be optimal to play B in S1 when we're considering the case where we also play B in S0 already: V(S0, B) = 0.5 * (-2 + gamma * V(S0, B)) + 0.5 * (-5 + gamma * V(S1, R)) which simplifies to: V(S0, B) = -3.5 + 0.5 * gamma * V(S0, B) + 0.5 * gamma * (-3 / (1 - 0.6 * gamma)) Now that we have nice expressions for V(S0, R) and V(S0, B), we can subtract one from the other: if the expression V(S0, B) - V(S0, R) is positive, the optimal policy will play B in S0. If it is negative, R will be played instead. With a whole lot more of arithmetic, it should be possible to solve an inequality like V(S0, B) &gt; V(S0, R) now. A much easier solution (albeit one that your teacher probably wouldn't like you trying on an exam) is to plug the deduc…
type: Answer
answers question: http://stackoverflow.com/q/51221952
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51221952
score: 1
upvote count: 1
type: AcceptedAnswer

http://stackoverflow.com/comment/89515239
comment on: http://stackoverflow.com/q/51267230
type: QuestionComment
has text: @HarvIpan It did. Thank you again
score: 1
type: Comment

http://stackoverflow.com/q/51273612
tagged with: nginx
score: 1
upvote count: 1
downvote count: 0
tagged with: jquery
favorite count: 0
tagged with: ajax
has body: I searched through SO to find a solution to that problem (e.g., this), but I cannot get it to work. My aim was to call an index.html on my website, which calls a Python script with the GET parameters. While searching on SO I found out that it's not possible with GET, I have to take POST. So now I want to call the index.html on my website, which calls a python script on the server with the POST parameters: $.ajax({ url: "foo.py", type: "POST", data: {foo: 'bar'} }); This is my Python script: import cgi, cgitb cgitb.enable() data = cgi.FieldStorage() with open("output.txt", "w") as f: f.write(data["foo"].value) When calling index.html with the post parameter foo=foofoo I first got a 403. But apparently that was related to NGINX, which I fixed with error_page 405 =200 $uri; (in case somebody has similar problems). Now, that I am not getting a 403 anymore, I get a 404. I cannot understand why it would throw a 404. Both, the index.html and the script foo.py are present on the server. I just want to call the Python script with the parameters from a GET/POST request...
tagged with: python
answer count: 0
type: UnansweredQuestion
tagged with: python-requests
has title: Get request on nginx; Call python script
type: Question
linked to: http://stackoverflow.com/q/18978152

http://stackoverflow.com/comment/89620171
score: 1
type: Comment
comment on: http://stackoverflow.com/q/51322107
type: QuestionComment
has text: This code is a mess: 1- why are your loops i, ii ,iii .. not used efficiently as in iterating through elements? 2- `for iii in list(o):` you don't need to do `list(o)`, o is already type list. 3- the variable names are so confusing, refrain from using 1 letter variables and both uppercase and lowercase at the same time.

http://stackoverflow.com/q/51308036
has comment: http://stackoverflow.com/comment/89595544
upvote count: 0
answer count: 1
tagged with: sorting
favorite count: 0
tagged with: pandas
tagged with: python
has comment: http://stackoverflow.com/comment/89593433
type: UnansweredQuestion
has body: Looking for advise on how to solve the following problem. I have Pandas dataframe, let's say 1.000.000 rows by 10 columns (A, B, C...J). Data type is float. The task is to remove all the rows (i) in a dataframe if there exist another raw (j) with all values equal to or greater than values in original raw (i). (Ai&lt;=Aj) and (Bi&lt;=Bj) and (Ci&lt;=Cj) ... and (Ji&lt;=Jj) I wonder whether there any tools exist in pandas tool kit or any other analytics python module to efficiently solve this problem. I have a very inefficient solution with multiple iterations in a simple array. Hoping to find smth more promising. Simplified example, original data: 0 1 5 4 4 2 2 5 6 4 3 7 -2 5 6 5 3 7 0 0 0 0 0 1 0 0 0 0 0 8 Result to be: 0 1 5 4 4 2 2 5 6 4 3 7 -2 5 6 5 3 7 0 0 0 0 0 8
downvote count: 1
has title: Sorting data. Pandas dataframe
type: Question
has answer: http://stackoverflow.com/a/51308337
tagged with: dataframe
score: -1

http://stackoverflow.com/q/51283207
has answer: http://stackoverflow.com/a/51283383
answer count: 2
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89544551
has title: Word counter (Introduction to Programming 2(python))
type: Question
upvote count: 4
has body: I tried looking for an answer to this problem but it didn't work. (btw I am 15 and basically just started python) This is my program: all = [] count = {} line = input("Enter line: ") while line: word = line.split() line = input("Enter line: ") for w in word: if w in count: count[w] += 1 else: count[w] = 1 for word in sorted(count): print(word, count[word]) This is the answer I'm getting: Enter line: which witch Enter line: is which Enter line: is 1 which 1 When I should be getting: Enter line: which witch Enter line: is which Enter line: is 1 which 2 witch 1 Please, can someone help?
has answer: http://stackoverflow.com/a/51283322
score: 4
has comment: http://stackoverflow.com/comment/89543766

http://stackoverflow.com/comment/89417440
has text: How is the interpreter being started?
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51218108
type: Comment

http://stackoverflow.com/comment/89548153
type: QuestionComment
has text: @chepner What was wrong with that dupe?
score: 0
comment on: http://stackoverflow.com/q/51285035
type: Comment

http://stackoverflow.com/comment/89670270
has text: The error shows if no contour is found in the image. After this line `im2, cont, hierarchy = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)` check if contours are present by `if cont != None:` and then go to the `for` loop.
type: Comment
comment on: http://stackoverflow.com/a/51198891
score: 0
type: AnswerComment

http://stackoverflow.com/q/51208527
score: 1
upvote count: 1
type: Question
tagged with: inheritance
has title: Is it possible to import a module and have everything execute within the importing module’s context?
downvote count: 0
favorite count: 0
type: UnansweredQuestion
has body: Suppose I have a package containing two modules moduleA and moduleB. Both should provide two string manipulation functions as interface manipulate and undo_manipulation, however they should differ in the details of the manipulation. Let’s say I want the manipulate of moduleA to replace all instances of "i" with "u", move the first letter to the end and then capitalise the first letter: &gt;&gt;&gt;moduleA.manipulate("string") 'Trungs' In moduleB on the other hand it should replace "r" with "w", move the first letter to the end, then swap the new first and second letters and then capitalise: &gt;&gt;&gt;moduleB.manipulate("string") 'Wtings' For example I would implement moduleA as: to_replace = {"i": "u"} def manipulate(string): for key, value in to_replace.items(): string = string.replace(key, value) string = move_letter(string) return capitalise(string) def move_letter(string): return string[1:]+string[0] def capitalise(string): return string[0].upper()+string[1:] (for the sake of simplicity I’m assuming the input is always at least 3 characters) Now what I would like to do for moduleB is to let it just “inherit” the whole of moduleA then override the details (i.e. define a new to_replaced and move_letter). Then the user should be able to call moduleB.manipulate and it would call the imported function, only it would then use the updated context. So basically: from moduleA import manipulate, move_letter, capitalise # second import necessary if I want to access the original version of move_letter from . import moduleA to_replace{"r": "w"} def move_letter(string): newstring = moduleA.move_letter(string) return newstring[1]+newstring[0]+newstring[2:] (Obviously the manipulations I actually want to do are a bit more complex; but they, too, can be broken down into more atomic parts, of which only some should be overridden by the “child” modules) Unfortunately this doesn’t work. If the user calls moduleB.manipulate, it uses moduleA’s version of to_replace and move_letter …
tagged with: python
tagged with: module
has comment: http://stackoverflow.com/comment/89397983
has comment: http://stackoverflow.com/comment/89648423
answer count: 0

http://stackoverflow.com/comment/89388361
type: AnswerComment
comment on: http://stackoverflow.com/a/51201100
score: 1
has text: How come this type of links `javascript:document.form792.submit();` can be navigated? I've clearly mentioned in my question that they are javascript links. Thanks.
type: Comment

http://stackoverflow.com/a/51255306
answers question: http://stackoverflow.com/q/51244636
upvote count: 1
type: Answer
has body: Monotone interpolators are provided as PchipInterpolator and Akima1DInterpolator. Dierckx's FITPACK has some spline fitting with constraints, but it's not exposed to python.
downvote count: 0
score: 1

http://stackoverflow.com/comment/89371762
has text: `__init__()` is never called. `__init__` in python is the class constructor (kinda), but these are all top level functions, you haven't put your `__init__` in a class. `dijkstra()` doesn't do anything, all it does is set some *local* variables which are destroyed on exit. Your indentation is also all wrong. I copied this into pycharm and got 32 errors! Can you post the fixed indented code please? -- all in all, I think you're getting a bit ahead of yourself and you need to take a step back.
comment on: http://stackoverflow.com/q/51195038
type: Comment
type: QuestionComment
score: 8

http://stackoverflow.com/comment/89421196
has text: import playsound playsound.playsound('equal1.mp3', True)
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51220132

http://stackoverflow.com/a/51292160
upvote count: 2
has body: The Update contains a message, that tells you who sent it. The chat_id of the user is equal to the id of the User object. You can retrieve it as following: chat_id = update.message.from.id
answers question: http://stackoverflow.com/q/51266026
type: Answer
score: 2
downvote count: 0

http://stackoverflow.com/q/51229274
tagged with: ssh
has body: I have a common VM and remote VM. we have network devices, only remote VM has access to network devices. Python script will do configurations in network devices. I must trigger a python script from common VM. To implement this Currently I have two options in my mind. Configure password less between common vm to remote vm. Trigger a script from common vm which copies script to remote vm then start execution. directly ssh using paramiko to remote and again ssh using paramiko to network devices (This option is not tried, I am going to try now) Which is the better method or any other suggestions will welcome. Thanks
has title: Paramiko for remote ssh
has comment: http://stackoverflow.com/comment/89438252
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/8169739
has comment: http://stackoverflow.com/comment/89438308
answer count: 0
score: 0
type: Question
tagged with: paramiko
tagged with: python-2.7
tagged with: linux
has comment: http://stackoverflow.com/comment/89438563

http://stackoverflow.com/a/51172766
has comment: http://stackoverflow.com/comment/89410876
has comment: http://stackoverflow.com/comment/89410705
has comment: http://stackoverflow.com/comment/89410306
type: Answer
has body: import re s = 'foo (4,301) bar blah (4)% blah (USD)' re.sub(r'\((\d[^\)]*)\)', r'-\1', s) # 'foo -4,301 bar blah -4% blah (USD)'
answers question: http://stackoverflow.com/q/51172657
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/89410499
score: 0

http://stackoverflow.com/comment/89506528
type: Comment
comment on: http://stackoverflow.com/a/51254736
has text: @a_guest: you are right and I said so in my own notes. This was just the first thing that worked. I didn't dig too much into it, but I think the array-of-tuples that is the arg to dict/OrderedDict needs to be transformed before you give it to ast.Dict() - the latter takes two lists: keys and values. Definitely possible - on the other hand, now that I think of it, doing partial evals might be a way to convert the input into an actual OrderedDict while staying safe, as well as extend it to other constructor calls.
type: AnswerComment
score: 0

http://stackoverflow.com/comment/89331969
score: 0
type: Comment
type: QuestionComment
has text: Similar as "Company_name" with "Company_name_INC"
comment on: http://stackoverflow.com/q/51174253

http://stackoverflow.com/comment/89550285
comment on: http://stackoverflow.com/q/51285593
score: 0
type: Comment
type: QuestionComment
has text: [thesamiroli](https://stackoverflow.com/users/8804904/thesamiroli) if my answer isn't correct could you please expand on what am I missing? Thanks!

http://stackoverflow.com/q/51182182
upvote count: 15
downvote count: 0
favorite count: 0
tagged with: pandas
tagged with: python
has body: this code in pandas does not work. I want it to delete the row if the column contains any of the text/numbers provided Currently I can only get it to work if the cell matches the exact text being passed in my code .. as in it only deletes cells that say Fin* not Finance or Finly... df2 = df[df.Team != 'Fin*']
has answer: http://stackoverflow.com/a/51182200
answer count: 4
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/62405535
type: Question
has answer: http://stackoverflow.com/a/51182202
has title: Pandas: Delete Row if cell contains specific text
score: 15
has answer: http://stackoverflow.com/a/51182201

kolmogorov-smirnov
tags question: http://stackoverflow.com/q/51305126
type: Tag
tags question: http://stackoverflow.com/q/51181798
tag name: kolmogorov-smirnov

http://stackoverflow.com/a/51200086
upvote count: 1
type: AcceptedAnswer
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/51199760
accepted answer of: http://stackoverflow.com/q/51199760
score: 1
has body: Replace NaN with 0, transpose df, and matrix-multiply that with a "mask" matrix that is 1 where df is not null: mask = df.notnull().astype(int) df.fillna(0).T.dot(mask) A B C D E A 7.0 5.0 5.0 4.0 3.0 B 9.0 10.0 9.0 9.0 3.0 C 12.0 9.0 14.0 10.0 6.0 D 7.0 9.0 10.0 10.0 1.0 E 8.0 7.0 8.0 7.0 8.0

http://stackoverflow.com/q/51193630
linked to: http://stackoverflow.com/q/7100242
score: 4
has answer: http://stackoverflow.com/a/51193802
upvote count: 4
has body: I am trying to figure out the fastest way to count how many time two values are located one after the other in a numpy list. For example: list = [1, 5, 4, 1, 2, 4, 6, 7, 2, 1, 3, 3, 1, 2] and I want to count the number of times the value 1 follows the value 2 (but not vice versa) In the example above, the answer should be 1 since 1 follows 2 only once. I can obviously reach the answer with a simple for-loop that adds to a counter every time the item i is equal 1 and item i-1 equals 2, but I feel that there must be a faster way to do it, Thanks
has comment: http://stackoverflow.com/comment/89372163
has comment: http://stackoverflow.com/comment/89368818
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/51193692
answer count: 5
has answer: http://stackoverflow.com/a/51194532
has title: Count the number of exact co-occurences of items in a numpy list
tagged with: python
has answer: http://stackoverflow.com/a/51193764
has comment: http://stackoverflow.com/comment/89371628
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51193692
type: Question
tagged with: numpy
possible better answer: http://stackoverflow.com/a/51193907
has answer: http://stackoverflow.com/a/51193907

http://stackoverflow.com/a/51200716
answers question: http://stackoverflow.com/q/51200646
upvote count: 3
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/89383219
score: 3
downvote count: 0
has body: good way to keep the company name and ticker symbol together We just need to make an intermediate mapping for it: import difflib data = [("AAPL", "Apple Inc."), ("TSLA", "Tesla Inc."), ("BB", "BlackBerry Limited")] index = {name.lower(): symbol for symbol, name in data} index.update({symbol.lower(): symbol for symbol, name in data}) def search_for_company(text): return set( index[name_or_symbol] for name_or_symbol in difflib.get_close_matches(text.lower(), index.keys()) ) print search_for_company('Apple I') # set(['AAPL']) print search_for_company('BB') # set(['BB']) print search_for_company('aapl') # set(['AAPL'])
accepted answer of: http://stackoverflow.com/q/51200646
has comment: http://stackoverflow.com/comment/89383037

http://stackoverflow.com/a/51292965
type: Answer
downvote count: 0
score: 6
has body: If you have a long list, you should put all numbers into a Counter(iterable) - dictionary. from collections import Counter data = [1,2,3,2,1] c = Counter(data) cleaned = [x for x in data if c[x] &gt; 1] print(cleaned) This will count all occurences with one pass of your list (O(n)) and the lookup how often it occurs inside the created dictionary is O(1). Together this is much faster then use a list comprehension like result = [x for x in data if data.count(x) &gt; 1] for a list of 100 values it will go through your 100 values 100 times, to count each single one of them wich is O(n^2) - bad thing to have. Output: [1,2,2,1]
upvote count: 6
answers question: http://stackoverflow.com/q/51292725

http://stackoverflow.com/a/51307389
upvote count: 1
answers question: http://stackoverflow.com/q/51307228
downvote count: 1
score: 0
type: Answer
has body: I recommend going to agree with Django (and moving your csv into a database). Out of the box Django 2 brings sqlite which is a file based database that would offer you the ability to swap database files if you wanted. I've found this (https://www.fusioncharts.com/django-charts/) django-charts package that incorporates interactive charts with Django, and seems to have lots of examples.
has comment: http://stackoverflow.com/comment/89595870

http://stackoverflow.com/q/51307345
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89603897
tagged with: python
has body: I need to calculate the condition number of a dense matrix A many times(with some changes to A in each time), where the condition number define to be the largest eigenvalue of A divided by the smallest eigenvalue. A is in an order of about 1000x5000 and performing np.linalg.svd(A, compute_uv=False) take approximately 0.6 seconds on the other hand scipy.sparse.linalg.svds(A, 1, which='SM') and scipy.sparse.linalg.svds(A, 1) does not converge due to the density of A (I think) there is any way to compute only the largest and smallest eigenvalues of a dense matrix? or a way to manipulate A in such a way in which I could use scipy.sparse.linalg.svds without changing the eigenvalues?
has comment: http://stackoverflow.com/comment/89600124
has comment: http://stackoverflow.com/comment/89603822
has title: calculate largest and smallest eigenvalues
tagged with: scipy
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/89601135
has comment: http://stackoverflow.com/comment/89618250
has comment: http://stackoverflow.com/comment/89632353
score: 0
tagged with: svd
answer count: 0

http://stackoverflow.com/comment/89371075
type: QuestionComment
comment on: http://stackoverflow.com/q/51194601
has text: Please don't post an entire program. Instead, create a [mcve] specifically for the purposes of this question. Also, please make sure you get the formatting right on the code you post.
type: Comment
score: 1

image-processing
tags question: http://stackoverflow.com/q/51323364
tags question: http://stackoverflow.com/q/51182154
tags question: http://stackoverflow.com/q/51249848
tags question: http://stackoverflow.com/q/51227416
tags question: http://stackoverflow.com/q/51231989
tags question: http://stackoverflow.com/q/51189114
tags question: http://stackoverflow.com/q/51290691
tags question: http://stackoverflow.com/q/51200852
tags question: http://stackoverflow.com/q/51239715
tags question: http://stackoverflow.com/q/51277866
tags question: http://stackoverflow.com/q/51205502
tags question: http://stackoverflow.com/q/51320446
tags question: http://stackoverflow.com/q/51259361
tags question: http://stackoverflow.com/q/51243526
tags question: http://stackoverflow.com/q/51171028
tags question: http://stackoverflow.com/q/51313763
tags question: http://stackoverflow.com/q/51182852
tags question: http://stackoverflow.com/q/51248667
tags question: http://stackoverflow.com/q/51175396
tags question: http://stackoverflow.com/q/51324202
tags question: http://stackoverflow.com/q/51172555
tags question: http://stackoverflow.com/q/51198890
tags question: http://stackoverflow.com/q/51323679
tags question: http://stackoverflow.com/q/51235043
tags question: http://stackoverflow.com/q/51180423
tags question: http://stackoverflow.com/q/51188675
tags question: http://stackoverflow.com/q/51245877
tags question: http://stackoverflow.com/q/51168896
tags question: http://stackoverflow.com/q/51266831
tags question: http://stackoverflow.com/q/51203902
tags question: http://stackoverflow.com/q/51276704
tags question: http://stackoverflow.com/q/51206036
tags question: http://stackoverflow.com/q/51223006
tags question: http://stackoverflow.com/q/51237834
tags question: http://stackoverflow.com/q/51236214
tags question: http://stackoverflow.com/q/51270207
type: Tag
tags question: http://stackoverflow.com/q/51225589
tags question: http://stackoverflow.com/q/51277949
tags question: http://stackoverflow.com/q/51190561
tags question: http://stackoverflow.com/q/51293876
tags question: http://stackoverflow.com/q/51218869
tags question: http://stackoverflow.com/q/51242987
tags question: http://stackoverflow.com/q/51289629
tags question: http://stackoverflow.com/q/51259233
tags question: http://stackoverflow.com/q/51229202
tags question: http://stackoverflow.com/q/51270649
tags question: http://stackoverflow.com/q/51210836
tag name: image-processing
tags question: http://stackoverflow.com/q/51314824
tags question: http://stackoverflow.com/q/51294548
tags question: http://stackoverflow.com/q/51225657
tags question: http://stackoverflow.com/q/51249781
tags question: http://stackoverflow.com/q/51296492
tags question: http://stackoverflow.com/q/51227864

http://stackoverflow.com/a/51253636
downvote count: 0
has body: Reason for the error: It seems a string representation isn't satisfying enough for the DataFrame constructor Fix/Solutions: import ast # convert the string representation to a dict dict = ast.literal_eval(r6) # and use it as the input df_test2 = DataFrame(index = idx, data=(dict)) which will solve the error.
accepted answer of: http://stackoverflow.com/q/51252267
type: Answer
answers question: http://stackoverflow.com/q/51252267
score: 2
upvote count: 2
type: AcceptedAnswer

http://stackoverflow.com/q/51235508
has title: In which folder on PC (Windows 10) does load_data() save a dataset in Keras?
downvote count: 0
answer count: 1
tagged with: keras
favorite count: 0
tagged with: python
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51235704
has body: In which folder on PC (Windows 10) does dataset_name.load_data() save the dataset, so that I can use it further? For example: from keras.datasets import cifar100 (x_train, y_train), (x_test, y_test) = cifar100.load_data(label_mode='fine')
upvote count: 2
tagged with: tensorflow
type: Question
accepted answer: http://stackoverflow.com/a/51235704
tagged with: deep-learning

http://stackoverflow.com/a/51217625
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51217113
has comment: http://stackoverflow.com/comment/89416555
answers question: http://stackoverflow.com/q/51217113
score: 5
type: AcceptedAnswer
has body: The &lt;w:p&gt; element can have any of a large number of children, as you can see from the XML Schema excerpt here: http://python-docx.readthedocs.io/en/latest/dev/analysis/schema/ct_p.html (see the CT_P and EG_PContent definitions). In particular, it often has a w:pPr child, which is where the style setting goes. So your test isn't very reliable against false positives (if being empty is considered positive). I'd be inclined to use paragraph.text == '', which parses through the runs. A run can be empty (of text), so the mere presence of a run is not proof enough. The actual text is held in a a:t (text) element, which can also be empty. So the .text approach avoids all those low-level complications for you and has the benefit of being part of the API so much, much less likely to change in a future release.
upvote count: 5
type: Answer
has comment: http://stackoverflow.com/comment/89417032

http://stackoverflow.com/q/51218916
score: 0
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/51219151
has comment: http://stackoverflow.com/comment/89419275
has answer: http://stackoverflow.com/a/51219124
tagged with: python-2.7
possible better answer: http://stackoverflow.com/a/51219124
tagged with: django-templates
accepted answer: http://stackoverflow.com/a/51219151
has title: Insert python string into Django template context with markup
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/89418915
has body: If I render a static image in the .html template it works. But if I provide the static markup string as dictionary value to the template (the context), it will not work. It seems to be something to do with string formatting and not allowing me to use {% %} the way I need to. I have tried: 1. .format() 2. escaping the percent characters 3. raw strings 4. concatenation 5. autoescape 6. | safe and a number of other things Basically, I am constructing a multi-line string in view.py with '''{% %}''', and then rendering a template with this string as the context. Python 2. UPDATE Simple non-working example: view.py def index(request): image_insert = '' images = ['image1.jpg', 'image2.jpg', 'image3.jpg'] for image in images: image_insert += ' '.format(image) context = {'insert': image_insert} template = loader.get_template('index.html') return HttpResponse(template.render(context, request)) index.html {% load static %} Basic HTML File First Image Second Image Page Source: Basic HTML File Second Image Obviously, there is a difference. This is Django 1.11 btw if it makes a difference.
type: AnsweredQuestion

http://stackoverflow.com/a/51183669
has body: Before you start writing code (or using someone else's), you must understand the theory behind the scene. What are the main entities of your Production System? You need to formulate optimization objectives, optimal schedule but define in terms of optimization problem. One example that comes to my mind https://github.com/jpuigcerver/jsp-ga Take a look at this thesis http://lancet.mit.edu/mbwall/phd/thesis/
type: Answer
answers question: http://stackoverflow.com/q/51183477
has comment: http://stackoverflow.com/comment/89349294
score: 0

http://stackoverflow.com/a/51186654
type: Answer
has body: modify your aaa.py import os,time from get_newest_folder import * def main_test(): path,newest_folder = get_n_folder() print(newest_folder) print(path) if __name__ == '__main__': main_test()
accepted answer of: http://stackoverflow.com/q/51186430
score: 0
answers question: http://stackoverflow.com/q/51186430
type: AcceptedAnswer

http://stackoverflow.com/q/51264102
favorite count: 0
has comment: http://stackoverflow.com/comment/89505995
has title: How can i get the first column from group by ? Python Panda
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/20461165
tagged with: python
has body: Here is the code. import pandas as pd df = pd.DataFrame({'Age':[0,0,1,14,15,30,31,50,51,79,78,45,22,15,80]}) print(df['Age']) a=df.groupby(['Age']).size() print(a) Output: Age 0 2 1 1 14 1 15 2 22 1 30 1 31 1 45 1 50 1 51 1 78 1 79 1 80 1 dtype: int64 I want to get age as a first column and size as a second column into an array. How can i do that?
answer count: 0
score: 1
has comment: http://stackoverflow.com/comment/89509225
upvote count: 1
type: Question
tagged with: arrays
duplicate of: http://stackoverflow.com/q/20461165
tagged with: pandas-groupby
downvote count: 0

http://stackoverflow.com/q/51234314
has comment: http://stackoverflow.com/comment/89448135
has comment: http://stackoverflow.com/comment/89447965
tagged with: pandas
has title: Google BigQuery API Python
tagged with: python
accepted answer: http://stackoverflow.com/a/51236341
type: AnsweredQuestion
type: Question
tagged with: google-bigquery
has answer: http://stackoverflow.com/a/51236341
score: 0
has comment: http://stackoverflow.com/comment/89479719
has body: I am trying to generate queries in python and querying with them. I am working with pandas_gbq. My code looks like this: def generate_query( filter=['CENTRAL BANK','DRAGHI','FRANKFURT'], date ='20171214', datetimeformat='%Y%m%d', weekly_data=True ): filter = str(filter).replace('[','').replace(']','') if weekly_data == False: query = '''SELECT * FROM `gdelt-bq.gdeltv2.events` WHERE SQLDATE = {date}'''.format(date = date) else: date = datetime.datetime.strptime(date, datetimeformat) week = generate_week(date) query = '''SELECT * FROM `gdelt-bq.gdeltv2.events` WHERE SQLDATE IN ({week})'''.format( week = week).replace('[','').replace(']','') return query, date Did not figure how to indent the code on stackoverflow. The problem occurs when trying to query multiple dates: 'SELECT * FROM `gdelt-bq.gdeltv2.events` WHERE SQLDATE IN (\\'20171211\\', \\'20171212\\', \\'20171213\\', \\'20171214\\', \\'20171215\\')' I have no idea where the backslashes are coming from. Any idea why this is happening? The function generate_week: def generate_week(date): week = [] referenceday = date - datetime.timedelta(days = date.weekday()) for i in range(0,5): day = referenceday + datetime.timedelta(days = i) week.append(day.strftime('%Y%m%d')) return week The returned error is the following: pandas_gbq.gbq.GenericGBQException: Reason: 400 No matching signature for operator IN for argument types INT64 and {STRING} at [1:55] I would be extremely thankful for some help here! :)
has comment: http://stackoverflow.com/comment/89451025
answer count: 1

http://stackoverflow.com/q/51218962
downvote count: 0
has answer: http://stackoverflow.com/a/51221041
accepted answer: http://stackoverflow.com/a/51221041
answer count: 1
tagged with: python
has title: Box gets truncated using zoomed_inset_axes
favorite count: 0
has body: I want to use zoomed_inset_axes but the box gets truncated as soon as it passes the frame of the main figure. I could not get any better with f.tight_layout() f.subplots_adjust(bottom=...) 'figure.autolayout': True not even with hidden (white) text using f.text somewhere outside. Does anyone know how to do this properly? import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1.inset_locator import zoomed_inset_axes, mark_inset X = np.random.normal(.5,10,1000) Y = np.random.normal(.5,10,1000) f, ax = plt.subplots(1, figsize=(10,6)) ax.scatter(X,Y) # # Setup zoom window axins = zoomed_inset_axes(ax, 2, loc="center", bbox_to_anchor=(0,0)) mark_inset(ax, axins, loc1=2, loc2=4, fc="none", ec="0.5") axins.set_xlim([-15,0]) axins.set_ylim([-12,-3]) # # Plot zoom window axins.scatter(X,Y) f.tight_layout() f.savefig('test.png', dpi=70)
upvote count: 7
type: AnsweredQuestion
score: 7
tagged with: matplotlib
type: Question

http://stackoverflow.com/a/51266000
has comment: http://stackoverflow.com/comment/108096291
type: Answer
has body: TL; DR: Upgrade Django to version 1.11.17+ or 2.0+ This error is a known incompatibility related to Python issue #32012. Projects based on Django 1.11.16 and below will raise this exception when started with Python 3.7. A patch for this issue has been merged into Django 2.0 and 2.1 branches and cherry-picked later into Django 1.11.17. Note: Python 3.7 is officially supported by Django 1.11.17 and above, including any 2.x branch.
answers question: http://stackoverflow.com/q/51265858
score: 97
upvote count: 97
has comment: http://stackoverflow.com/comment/94771923
has comment: http://stackoverflow.com/comment/131610133
accepted answer of: http://stackoverflow.com/q/51265858
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/51217105
has comment: http://stackoverflow.com/comment/89415653
has comment: http://stackoverflow.com/comment/89415679
has comment: http://stackoverflow.com/comment/89415766
has body: With the in operator you're using substring match, which is why when output contains port 1.23, it also matches port 1.2. In this case you should use regex to make sure that the match occurs only on word boundaries. import re matches = re.findall('\b(?:%s)\b' % '|'.join(port_list), output)
type: Answer
upvote count: 1
downvote count: 1
answers question: http://stackoverflow.com/q/51217028
score: 0
has comment: http://stackoverflow.com/comment/89415607

http://stackoverflow.com/a/71429859
type: Answer
score: 11
downvote count: 0
has comment: http://stackoverflow.com/comment/140063098
has comment: http://stackoverflow.com/comment/127197365
has comment: http://stackoverflow.com/comment/131515660
upvote count: 11
has body: A useful workaround is to use the option computed_zorder=False (added in Feb 2021, see doc), and to plot the different elements in the desired order. The only caveat is that it requires knowing which points are below the surface, and which points are above. import pandas as pd import matplotlib import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import numpy as np df = pd.DataFrame({10: {10: 1,15: 1,20: 1,25: 1,30: 1,35: 1,40: 1,45: 1,50: 1,55: 1,60: 1,65: 1,70: 1,75: 1,80: 1,85: 1,90: 1}, 15: {10: 4,15: 1,20: 1,25: 1,30: 1,35: 1,40: 1,45: 1,50: 1,55: 1,60: 1,65: 1,70: 1,75: 1,80: 1,85: 1,90: 1}, 20: {10: 6,15: 3,20: 1,25: 1,30: 1,35: 1,40: 1,45: 1,50: 1,55: 1,60: 1,65: 1,70: 1,75: 1,80: 1,85: 1,90: 1}, 25: {10: 7,15: 5,20: 3,25: 1,30: 1,35: 1,40: 1,45: 1,50: 1,55: 1,60: 1,65: 1,70: 1,75: 1,80: 1,85: 1,90: 1}, 30: {10: 9,15: 6,20: 4,25: 3,30: 1,35: 1,40: 1,45: 1,50: 1,55: 1,60: 1,65: 1,70: 1,75: 1,80: 1,85: 1,90: 1}, 35: {10: 10,15: 7,20: 5,25: 4,30: 2,35: 1,40: 1,45: 1,50: 1,55: 1,60: 1,65: 1,70: 1,75: 1,80: 1,85: 1,90: 1}, 40: {10: 11,15: 8,20: 6,25: 4,30: 3,35: 2,40: 1,45: 1,50: 1,55: 1,60: 1,65: 1,70: 1,75: 1,80: 1,85: 1,90: 1}, 45: {10: 12,15: 9,20: 7,25: 5,30: 4,35: 3,40: 2,45: 1,50: 1,55: 1,60: 1,65: 1,70: 1,75: 1,80: 1,85: 1,90: 1}, 50: {10: 13,15: 9,20: 7,25: 6,30: 5,35: 4,40: 3,45: 2,50: 1,55: 1,60: 1,65: 1,70: 1,75: 1,80: 1,85: 1,90: 1}, 55: {10: 14,15: 10,20: 8,25: 7,30: 5,35: 4,40: 3,45: 3,50: 2,55: 1,60: 1,65: 1,70: 1,75: 1,80: 1,85: 1,90: 1}, 60: {10: 15,15: 11,20: 9,25: 7,30: 6,35: 5,40: 4,45: 3,50: 3,55: 2,60: 1,65: 1,70: 1,75: 1,80: 1,85: 1,90: 1}, 65: {10: 16,15: 12,20: 9,25: 8,30: 6,35: 5,40: 5,45: 4,50: 3,55: 2,60: 2,65: 1,70: 1,75: 1,80: 1,85: 1,90: 1}, 70: {10: 17,15: 12,20: 10,25: 8,30: 7,35: 6,40: 5,45: 4,50: 4,55: 3,60: 2,65: 2,70: 1,75: 1,80: 1,85: 1,90: 1}, 75: {10: 18,15: 13,20: 10,25: 9,30: 7,35: 6,40: 5,45: 5,50: 4,55: 3,60: 3,65: 2,70: 2,75: 1,80: 1,85: 1,90: 1}, 80: {10: 19,15: 14,20: 11,25: 9,30: 8,35: 7,40: 6,45…
answers question: http://stackoverflow.com/q/51241367

http://stackoverflow.com/comment/89437631
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51222162
has text: @nAJ in your python script you have to put `import sys`, `sys.path = ...` BEFORE `import boto3`, it does not matter, when you installed it. check the script, reorder the lines.

http://stackoverflow.com/q/51203869
type: UnansweredQuestion
has title: Machine Learning with an Unbalanced Dataset
downvote count: 2
tagged with: machine-learning
has comment: http://stackoverflow.com/comment/89388813
upvote count: 1
has body: I've got the following unbalanced dataset containing wine ratings from 1-10. The class balance is the following: Rating / # Samples (%) 1 - 0 (0.0%) 2 - 0 (0.0%) 3 - 10 (0.74%) 4 - 53 (3.90%) 5 - 577 (42.5%) 6 - 535 (39.40%) 7 - 167 (12.29%) 8 - 17 (1.25%) 9 - 0 (0.0%) 10 - 0 (0.0%) Since I can't get more data, what is the best possible of predicting rates using Scikit-Learning with this unbalanced data? Can SMOTE be applied on this case? Thanks all!
has answer: http://stackoverflow.com/a/51204005
has comment: http://stackoverflow.com/comment/89389187
score: -1
type: Question
has answer: http://stackoverflow.com/a/51204818
answer count: 2
tagged with: dataset
tagged with: scikit-learn
has comment: http://stackoverflow.com/comment/89389222
tagged with: data-science
favorite count: 0
has comment: http://stackoverflow.com/comment/89389036
tagged with: python

http://stackoverflow.com/comment/97988533
comment on: http://stackoverflow.com/q/51192862
score: 0
has text: @BenKalender I think I still have same issue. ANy update from You?
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51241834
has title: Pandas Merge Resample Result for Missing Rows
answer count: 1
has answer: http://stackoverflow.com/a/51241870
score: 0
tagged with: pandas
accepted answer: http://stackoverflow.com/a/51241870
tagged with: python
type: AnsweredQuestion
has body: Note: I asked a worse version of this yesterday, which I quickly deleted. However @FlorianGD left a comment which gave me the answer I needed - so I've added this up in any case with the solution he advised. Prepare Start Dataframe I have some dates: date_dict = {0: '1/31/2010', 1: '12/15/2009', 2: '3/19/2010', 3: '10/25/2009', 4: '1/17/2009', 5: '9/4/2009', 6: '2/21/2010', 7: '8/30/2009', 8: '1/31/2010', 9: '11/30/2008', 10: '2/8/2009', 11: '4/9/2010', 12: '9/13/2009', 13: '10/19/2009', 14: '1/24/2010', 15: '3/8/2009', 16: '11/30/2008', 17: '7/30/2009', 18: '12/12/2009', 19: '3/8/2009', 20: '6/18/2010', 21: '11/30/2008', 22: '12/30/2009', 23: '10/28/2009', 24: '1/28/2010'} Convert to dataframe and datetime format: import pandas as pd from datetime import datetime df = pd.DataFrame(list(date_dict.items()), columns=['Ind', 'Game_date']) df['Date'] = df['Game_date'].apply(lambda x: datetime.strptime(x.strip(), "%m/%d/%Y")) df.sort_values(by='Date', inplace=True) df.reset_index(drop=True, inplace=True) del df['Ind'], df['Game_date'] df['Count'] = 1 df Date 0 2008-11-30 1 2008-11-30 2 2008-11-30 3 2009-01-17 4 2009-02-08 5 2009-03-08 6 2009-03-08 7 2009-07-30 8 2009-08-30 9 2009-09-04 10 2009-09-13 11 2009-10-19 12 2009-10-25 13 2009-10-28 14 2009-12-12 15 2009-12-15 16 2009-12-30 17 2010-01-24 18 2010-01-28 19 2010-01-31 20 2010-01-31 21 2010-02-21 22 2010-03-19 23 2010-04-09 24 2010-06-18 Now what I want to do is to resample this dataframe to group rows into groups of weeks, and return the information to the original dataframe. 2 Use resample() to group for each week and return count I perform a resample for each week every Tuesday: c_index = df.set_index('Date', drop=True).resample('1W-TUE').sum()['Count'].reset_index() c_index.dropna(subset=['Count'], axis=0, inplace=True) c_index = c_index.reset_index(drop=True) c_index['Index_Col'] = c_index.index + 1 c_index Date Count Index_Col 0 2008-12-02 3.0 1 1 2009-01-20 1.0 2 2 2009-02-10 1.0 3 3 2009-03-10 2.0 4 4 2009-08…
tagged with: dataframe
tagged with: date
type: Question

http://stackoverflow.com/q/51219159
tagged with: metadata
has comment: http://stackoverflow.com/comment/89419702
accepted answer: http://stackoverflow.com/a/51219484
upvote count: 1
tagged with: python
tagged with: exif
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51219484
downvote count: 1
type: Question
has title: remove exif from all files in directory
has comment: http://stackoverflow.com/comment/89419712
has comment: http://stackoverflow.com/comment/89419504
answer count: 1
has comment: http://stackoverflow.com/comment/89419615
tagged with: python-2.7
score: 0
has body: I would like to remove the exif/metadata from all .JPG files in a directory. Here's what I have so far, but part of me doesn't think this will work, so...help? import os from gi.repository import GExiv2 rootdir = "c:\directory\subdirectory\subdirectory2" def noMeta(file): exif = GExiv2.Metadata(file + ".jpg") exif.clear_exif() exif.clear_xmp() exif.save_file() for root, dir, files in os.walk(rootdir): for file in files: if file.lower().endswith(".jpg"): noMeta(file)
favorite count: 0

http://stackoverflow.com/comment/89509836
type: AnswerComment
has text: Well now both values equal 0. Its supposed to count though. Why isn't it doing that? I don't seem why.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51265907

templates
tags question: http://stackoverflow.com/q/51182656
tag name: templates
type: Tag
tags question: http://stackoverflow.com/q/51221220

http://stackoverflow.com/q/51288330
tagged with: keras
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89594804
has title: Keras weights of first layer didn't change
has comment: http://stackoverflow.com/comment/89556124
tagged with: python
has comment: http://stackoverflow.com/comment/89595535
has answer: http://stackoverflow.com/a/51289294
has comment: http://stackoverflow.com/comment/89557837
upvote count: 3
has comment: http://stackoverflow.com/comment/89555349
tagged with: tensorflow
type: Question
score: 3
has body: I'm very new to Keras and I'm writing a custom layer which implements Gaussian function [exp(-(w*x-mean)^2/sigma^2) where W, mean, sigma are all randomly generated]. Below is code for the custom layer: class Gaussian(Layer): def __init__(self,**kwargs): super(Gaussian, self).__init__(**kwargs) def build(self, input_shape): # Create trainable weights for this layer. self.W_init = np.random.rand(1,input_shape[1]) self.W = K.variable(self.W_init, name="W") # Create trainable means for this layer. self.mean_init = np.random.rand(1,input_shape[1]) self.mean = K.variable(self.mean_init, name="mean") # Create trainable sigmas for this layer. self.sigma_init = np.random.rand(1,input_shape[1]) self.sigma = K.variable(self.sigma_init, name="sigma") self.trainable_weights = [self.mean, self.sigma] super(Gaussian, self).build(input_shape) # Be sure to call this somewhere! def call(self, x): result = tf.multiply(x, self.W) result = tf.subtract(x, self.mean) result = tf.multiply(tf.square(result),-1) result = tf.divide(result, tf.square(self.sigma)) return result def compute_output_shape(self, input_shape): return input_shape After putting it as the first layer in a Keras mnist tutorial(just wanted to make sure it runs without producing errors, didn't care for accuracy) and training the model, it appeared that the loss stopped decreasing after around 4 epochs and only the numbers of "mean" and "sigma" changed after training while the numbers of "W" remains the same. However, this doesn't happen if I put it as the second layer. I ran the Keras mnist tutorial again without the custom layer and found out that the weights of the first layer didn't change either. Is not updating the weights of first layer(more specifically the very first parameter) a Keras thing or am I missing something? Can I force it to update? Thank you!
tagged with: deep-learning
answer count: 1
downvote count: 0

http://stackoverflow.com/a/53189811
upvote count: 1
type: Answer
has body: Broadly yes, you are right. The type of clustering I have used before is the KMeans clustering (which can be found here https://scikit-learn.org/stable/modules/generated/sklearn.cluster.KMeans.html) but I can't guarantee they all work like that. Appending a new column onto the dataframe will work as you think it will.
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/51225794

http://stackoverflow.com/a/51240663
upvote count: 1
has comment: http://stackoverflow.com/comment/89460510
downvote count: 1
type: Answer
has body: If you have the sql file you should import it into a database and than use a library like MySQLdb for python to make your database requests. I would guess, that opening sql files directly is a good solution. If you want to work with files, I think csv files are the better solution.
answers question: http://stackoverflow.com/q/51240567
has comment: http://stackoverflow.com/comment/89460607
score: 0

http://stackoverflow.com/q/51273995
has body: I'm creating a robot with selenium that get all info from agencies in Brasil, i've alredy done the permutation click between all States and counties, all i have to do now's click in all agencies and get infos like: "telefone","endereço","HORÁRIO DE ATENDIMENTO". How can I do that?? That's my code till now: # -*- coding: UTF-8 -*- from selenium import webdriver from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support.select import Select import time import urllib import urllib.request from bs4 import BeautifulSoup import request def make_soup(url): thepage = urllib.request.urlopen(url) soupdata = BeautifulSoup(thepage,'html.parser') return soupdata chrome_path = r"D:\Users\gbenites\Desktop\Inovação\arquivos py\WebDriver\chromedriver.exe" url = 'http://www2.correios.com.br/sistemas/agencias/' driver = webdriver.Chrome(chrome_path) driver.get("http://www2.correios.com.br/sistemas/agencias/") #WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.ID, 'municipioAgencia'))) driver.maximize_window() time.sleep(3) estadoList = Select(driver.find_element_by_name('estadoAgencia')) for index in range(3,len(estadoList.options)): select = Select(driver.find_element_by_name('estadoAgencia')) print("selecting Estado: ",select.options[index].text) print("selecting Index: ",index) select.select_by_index(index) time.sleep(2) municípioList = Select(driver.find_element_by_name('municipioAgencia')) for index_b in range(1,len(municípioList.options)): select_b = Select(driver.find_element_by_name('municipioAgencia')) print("...selecting Municipio",select_b.options[index_b].text.replace("'","")) print("...selecting Municipio Index: ",index_b) select_b.select_by_index(index_b) time.sleep(3) get_info_list = WebDriverWait(driver, 10).until(EC.presence_of_all_elements_located((By.XPATH, "//table[@class = 'dadosAgencia']//td"))) info_list = dri…
tagged with: selenium
downvote count: 3
score: -1
has answer: http://stackoverflow.com/a/51274084
tagged with: dynamic-tables
type: Question
possible better answer: http://stackoverflow.com/a/51277479
answer count: 2
has comment: http://stackoverflow.com/comment/89526232
has answer: http://stackoverflow.com/a/51277479
has title: Selenium, python dynamic table
has comment: http://stackoverflow.com/comment/89538035
accepted answer: http://stackoverflow.com/a/51274084
favorite count: 0
upvote count: 2
tagged with: python
has comment: http://stackoverflow.com/comment/89547727
type: AnsweredQuestion

http://stackoverflow.com/comment/89421051
type: Comment
has text: In your answer you fixed it to second digit, i want to sort it by looking from end if last digits are same then it should look at second last digit.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51220059

http://stackoverflow.com/comment/89374720
has text: `["".join(islice(iterx,0,n)) for n in [10,8,32,4,4,2]]` :P
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51196478
type: AnswerComment

http://stackoverflow.com/comment/89575202
comment on: http://stackoverflow.com/q/51299070
has text: Okay, I'm sorry didn't know this could be an issue ^^'
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51189423
type: AnsweredQuestion
tagged with: windows-8.1
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89361259
type: Question
has answer: http://stackoverflow.com/a/51189751
has title: Installation error while installing scrapy
tagged with: python
has body: My system is windows 8.1 and installed python 3.7.2. Now, whenever I try to install -> pip install scrapy. It always shows me an error mention below: error: [WinError 3] The system cannot find the path specified: 'C:\\Program Files (x86)\\Microsoft SDKs\\Windows\\v8.1\\lib' ---------------------------------------- Command "c:\users\user\appdata\local\programs\python\python37-32\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Users\\User\\AppData\\Local\\Temp\\pip-install-5lpvl9q3\\Twisted\\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\User\AppData\Local\Temp\pip-record-5pmlq_y_\install-record.txt --single-version-externally-managed --compile" failed with error code 1 in C:\Users\User\AppData\Local\Temp\pip-install-5lpvl9q3\Twisted\ Thanks for help!
has comment: http://stackoverflow.com/comment/89360422
linked to: http://stackoverflow.com/q/43413914
score: 0
answer count: 1
duplicate of: http://stackoverflow.com/q/43413914
accepted answer: http://stackoverflow.com/a/51189751

http://stackoverflow.com/q/51227402
linked to: http://stackoverflow.com/q/8595973
type: Question
has comment: http://stackoverflow.com/comment/89435017
duplicate of: http://stackoverflow.com/q/8595973
answer count: 2
downvote count: 4
has answer: http://stackoverflow.com/a/51227476
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51227482
score: -3
tagged with: python
has title: Limit the decimal places in a float
has body: How can I limit the decimal places of a 'float' in python without rounding the number? For example: a = 1.45698946 &gt;&gt; Limit_a = 1.45698 And not: 1.45699
has comment: http://stackoverflow.com/comment/89435232
has comment: http://stackoverflow.com/comment/89434994
has comment: http://stackoverflow.com/comment/89434847
upvote count: 1

object
tags question: http://stackoverflow.com/q/51205716
tag name: object
tags question: http://stackoverflow.com/q/51228472
tags question: http://stackoverflow.com/q/51225748
tags question: http://stackoverflow.com/q/51289991
tags question: http://stackoverflow.com/q/51293796
tags question: http://stackoverflow.com/q/51255202
tags question: http://stackoverflow.com/q/51290827
tags question: http://stackoverflow.com/q/51282739
tags question: http://stackoverflow.com/q/51299920
tags question: http://stackoverflow.com/q/51299581
tags question: http://stackoverflow.com/q/51187180
tags question: http://stackoverflow.com/q/51215450
tags question: http://stackoverflow.com/q/51256565
tags question: http://stackoverflow.com/q/51198238
type: Tag
tags question: http://stackoverflow.com/q/51168556
tags question: http://stackoverflow.com/q/51296520

http://stackoverflow.com/a/51193744
score: 1
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51193342
type: Answer
has body: I checked, and you do need to compute a grid before plotting. You can just add something like : ... for i in iterator: number = np.random.rand() df.loc[i[0],i[1]] = number xv, yv = np.meshgrid(df.index, df.columns) surf = ax.plot_surface(xv, yv, df, cmap='viridis_r', linewidth=0.5, alpha = 0.5, edgecolor = 'k') ... I don't really know if this is the expected result, but you obtain a real surface ! meshgrid just creates matrices which correspond to different permutations of values from x and y, to allow you to have different x for one y and vice versa.
answers question: http://stackoverflow.com/q/51193342
upvote count: 1

http://stackoverflow.com/a/51263730
answers question: http://stackoverflow.com/q/51263436
has body: Depending on the questions you might step through the questions in a single loop, something like: questions=["1+2?","3+4?","5+6?"] answers=["3","7","11"] idx=0 while idx&lt;3: if answers[idx]==input(questions[idx]): idx=idx+1 print("Okay") However if validation involves separate, different procedures, Willem's answer is more manageable.
score: 0
type: Answer

http://stackoverflow.com/comment/89453329
comment on: http://stackoverflow.com/a/51215278
has text: Thanks Yuva. I understand the limitation. I would like to know if there is a work around for it? Thank you!
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/51178143
answer count: 1
type: UnansweredQuestion
tagged with: python
tagged with: css
has title: Flask main.css file not working with base.html file
has body: I'm relatively new to Flask and I'm trying to get my main.ss file to interact with my base.html file. When I make the changes to the CSS code it's not reflected when I view the application in the browser. Any help would be greatly appreciated! The filepath to base.html is documents/ds/ds/templates/base.html The filepath to main.css is documents/ds/ds/static/main.css The title base.html code reads: Deplorable Snowflake Is it the way i'm linking to it in the header? ...
type: Question
has answer: http://stackoverflow.com/a/51179686
tagged with: flask
score: 0
tagged with: http://stackoverflow.com/tag/html